Skip to content

Truly independent web browser

LibWeb: Replace the differential style engine

Andreas Kling8ea3ff332fa7
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 061efeb618c..d2a8584fee3 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -196,6 +196,7 @@ set(SOURCES
CSS/SelectorMatching.cpp
CSS/Serialize.cpp
CSS/Sizing.cpp
+ CSS/DevToolsAppliedStyleRules.cpp
CSS/StyleComputer.cpp
CSS/StyleEngineBridge.cpp
CSS/StyleEngineInput.cpp
@@ -262,6 +263,7 @@ set(SOURCES
DOM/CommitMessages.cpp
DOM/CustomEvent.cpp
DOM/Document.cpp
+ DOM/DocumentHighlightStyles.cpp
DOM/DocumentFragment.cpp
DOM/DocumentLoadEventDelayer.cpp
DOM/DocumentLoading.cpp
diff --git a/Libraries/LibWeb/CSS/CSSAnimation.cpp b/Libraries/LibWeb/CSS/CSSAnimation.cpp
index 67c2449ee6e..7ee3a138a07 100644
--- a/Libraries/LibWeb/CSS/CSSAnimation.cpp
+++ b/Libraries/LibWeb/CSS/CSSAnimation.cpp
@@ -12,6 +12,7 @@
#include <LibWeb/Animations/ViewTimeline.h>
#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/PropertyID.h>
+#include <LibWeb/CSS/PseudoElement.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
@@ -47,8 +48,31 @@ int CSSAnimation::class_specific_composite_order(GC::Ref<Animations::Animation>
// - ::after
// - element children
if (owning_element() != other->owning_element()) {
- // FIXME: Sort by tree order
- return 0;
+ auto& element = owning_element()->element();
+ auto& other_element = other->owning_element()->element();
+ if (&element != &other_element) {
+ // NB: An element's pseudo-elements sort with it, so before its children.
+ return element.document().compare_elements_in_tree_order_for_composite_order(element, other_element);
+ }
+ auto rank = [](Optional<PseudoElement> pseudo_element) {
+ if (!pseudo_element.has_value())
+ return 0;
+ switch (*pseudo_element) {
+ case PseudoElement::Marker:
+ return 1;
+ case PseudoElement::Before:
+ return 2;
+ case PseudoElement::After:
+ return 4;
+ default:
+ return 3;
+ }
+ };
+ auto pseudo_element = owning_element()->pseudo_element();
+ auto other_pseudo_element = other->owning_element()->pseudo_element();
+ if (auto order = rank(pseudo_element) - rank(other_pseudo_element); order != 0)
+ return order;
+ return pseudo_element_name(*pseudo_element) < pseudo_element_name(*other_pseudo_element) ? -1 : 1;
}
// 2. Otherwise, sort A and B based on their position in the computed value of the animation-name property of the
@@ -161,25 +185,25 @@ void CSSAnimation::apply_css_properties(AnimationProperties const& animation_pro
m_applied_definition_range = animation_properties.range;
m_applied_definition = {
.values = {
- .duration_is_auto = animation_properties.duration.has<Utf16String>(),
.duration = animation_properties.duration.visit(
[](double duration) { return duration; },
[](Utf16String const&) { return 0.0; }),
.iteration_count = animation_properties.iteration_count,
+ .delay = animation_properties.delay,
+ .range_start_px = animation_properties.range.start.offset_px,
+ .range_start_percentage = animation_properties.range.start.offset_percentage,
+ .range_end_px = animation_properties.range.end.offset_px,
+ .range_end_percentage = animation_properties.range.end.offset_percentage,
+ .duration_is_auto = animation_properties.duration.has<Utf16String>(),
.direction = to_underlying(animation_properties.direction),
.play_state = to_underlying(animation_properties.play_state),
- .delay = animation_properties.delay,
.fill_mode = to_underlying(animation_properties.fill_mode),
.composition = to_underlying(animation_properties.composition),
.timeline_kind = to_underlying(animation_properties.timeline.kind),
.scroll_scroller = to_underlying(animation_properties.timeline.scroller),
.scroll_axis = to_underlying(animation_properties.timeline.axis),
.range_start_name = to_underlying(animation_properties.range.start.name),
- .range_start_px = animation_properties.range.start.offset_px,
- .range_start_percentage = animation_properties.range.start.offset_percentage,
.range_end_name = to_underlying(animation_properties.range.end.name),
- .range_end_px = animation_properties.range.end.offset_px,
- .range_end_percentage = animation_properties.range.end.offset_percentage,
},
.keyframe_set = m_applied_keyframe_set.ptr(),
.timing_function = m_applied_timing_function_value.data(),
diff --git a/Libraries/LibWeb/CSS/CSSStyleProperties.cpp b/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
index bc012fcc90f..2afa603f287 100644
--- a/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
+++ b/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
@@ -216,10 +216,7 @@ Optional<StyleProperty const&> CSSStyleProperties::custom_property(Utf16FlyStrin
if (!data)
return {};
- if (auto const* property = data->get(custom_property_name))
- return *property;
-
- return {};
+ return data->get(custom_property_name);
}
return custom_properties().get(custom_property_name);
@@ -375,15 +372,15 @@ static NonnullRefPtr<StyleValue const> style_value_for_transform_origin(Transfor
return StyleValueList::create(move(offsets), StyleValueList::Separator::Space, StyleValueList::Collapsible::No);
}
-static RefPtr<StyleValue const> style_value_for_shadow(ShadowStyleValue::ShadowType shadow_type, ReadonlySpan<ShadowData> shadow_data)
+static RefPtr<StyleValue const> style_value_for_shadow(ShadowStyleValue::ShadowType shadow_type, ReadonlySpan<ShadowData> shadow_data, Color current_color)
{
if (shadow_data.is_empty())
return KeywordStyleValue::create(Keyword::None);
- auto make_shadow_style_value = [shadow_type](ShadowData const& shadow) {
+ auto make_shadow_style_value = [shadow_type, current_color](ShadowData const& shadow) {
return ShadowStyleValue::create(
shadow_type,
- ColorStyleValue::create_from_color(shadow.color, ColorSyntax::Modern),
+ ColorStyleValue::create_from_color(shadow.resolved_color(current_color), ColorSyntax::Modern),
style_value_for_css_pixels(shadow.offset_x),
style_value_for_css_pixels(shadow.offset_y),
style_value_for_css_pixels(shadow.blur_radius),
@@ -595,9 +592,21 @@ Optional<StyleProperty> CSSStyleProperties::get_property_internal(PropertyNameAn
// shorthand property must serialize to the empty string.
if (list.first()->is_pending_substitution()) {
auto original_shorthand_value = list.first()->as_pending_substitution().original_shorthand_value();
+ // NB: A longhand of a shorthand nested in the one written pends the nested shorthand, which pends the
+ // written one in turn. Writing an equal value again leaves longhands holding equal values, not
+ // the same one, so what they have in common is the shorthand written and its value as written.
+ auto written_shorthand = [](ValueComparingNonnullRefPtr<StyleValue const> value) {
+ while (value->as_pending_substitution().original_shorthand_value()->is_pending_substitution())
+ value = value->as_pending_substitution().original_shorthand_value();
+ return value;
+ };
+ auto const first_written_shorthand = written_shorthand(list.first());
auto all_from_same_original = all_of(list, [&](auto const& value) {
- return value->is_pending_substitution()
- && value->as_pending_substitution().original_shorthand_value()->rust_style_value_data() == original_shorthand_value->rust_style_value_data();
+ if (!value->is_pending_substitution())
+ return false;
+ auto const this_written_shorthand = written_shorthand(value);
+ return this_written_shorthand->as_pending_substitution().original_shorthand() == first_written_shorthand->as_pending_substitution().original_shorthand()
+ && this_written_shorthand->as_pending_substitution().original_shorthand_value() == first_written_shorthand->as_pending_substitution().original_shorthand_value();
});
if (all_from_same_original) {
return StyleProperty {
@@ -641,16 +650,15 @@ static void install_engine_pseudo_element_style(Layout::BegunRead const& read, D
if (!answer.is_absent && answer.record.style_record == 0)
return;
StyleRecordID record { answer.record.style_record };
- element.set_computed_style(pseudo_element, record);
+ element.set_computed_style(read, pseudo_element, InstalledStyle { answer.record.host_record });
// A pseudo-element that generates no box holds the environment its rules declare, if any rule styles it.
- auto environment = !!record ? style_engine.style_record_custom_property_environment(read, record) : answer.custom_property_environment;
+ auto environment = !!record ? InstalledStyle { answer.record.host_record }.custom_property_environment() : answer.custom_property_environment;
if (!!record || environment != 0)
element.install_engine_pseudo_element_custom_property_data(read, pseudo_element, environment);
else
element.set_custom_property_data(pseudo_element, nullptr);
if (!!record)
element.document().style_computer().compose_installed_engine_record(read, target, {});
- StyleEngineFFI::style_engine_acknowledge_engine_computed_record(style_engine.host(), element.style_node_id());
}
static void ensure_pseudo_element_style_for_cssom(Layout::BegunRead const& read, DOM::AbstractElement abstract_element)
@@ -727,7 +735,7 @@ static NonnullRefPtr<StyleValue const> resolve_unresolvable_anchor_functions(Pro
// NB: An element without a layout node may still generate a box whose layout is not up to date yet, so this only
// looks at whether the element's style places it outside the box tree.
-static bool element_generates_no_box(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ComputedValues const& style)
+static bool element_generates_no_box(DOM::AbstractElement abstract_element, ComputedValues const& style)
{
if (style.display().is_none() || style.display().is_contents())
return true;
@@ -741,8 +749,8 @@ static bool element_generates_no_box(Layout::BegunRead const& read, DOM::Abstrac
if ((is_before_or_after || *pseudo_element == PseudoElement::Marker) && content->is_keyword() && content->to_keyword() == Keyword::None)
return true;
}
- auto style_record = abstract_element.style_record_identity();
- return !!style_record && has_flag(abstract_element.document().style_computer().style_engine().style_record_dependency_flags(read, style_record), StyleRecordDependencyFlag::InDisplayNoneSubtree);
+ auto const& installed_style = abstract_element.installed_style();
+ return installed_style && has_flag(installed_style.dependency_flags(), StyleRecordDependencyFlag::InDisplayNoneSubtree);
}
// Brings style (and, when the property needs it, layout) up to date for computed-style property
@@ -778,11 +786,14 @@ static Optional<Layout::NodeWithStyle*> prepare_computed_style_and_layout_for_pr
// so the leaf and its inheritance ancestors may still be stale at this point.
// NB: Only the style record's presence and its display:none-subtree bit matter here, so probe
// those directly instead of materializing a full style record view.
- auto style_record = abstract_element.style_record_identity();
- bool const style_is_in_display_none_subtree = !layout_node
- && !!style_record
- && has_flag(abstract_element.document().style_computer().style_engine().style_record_dependency_flags(read, style_record), StyleRecordDependencyFlag::InDisplayNoneSubtree);
- if (!style_record || style_is_in_display_none_subtree)
+ auto const& style = abstract_element.installed_style();
+ // NB: An element moved below a display:none element holds the record it had where it stood, and its box until
+ // layout next runs.
+ bool const style_is_in_display_none_subtree = style
+ && ((!layout_node && has_flag(style.dependency_flags(), StyleRecordDependencyFlag::InDisplayNoneSubtree))
+ || ((!layout_node || !abstract_element.document().layout_is_up_to_date())
+ && abstract_element.element().has_inclusive_ancestor_with_display_none_ignoring_animations()));
+ if (!style || style_is_in_display_none_subtree)
abstract_element.document().update_style_for_element(abstract_element);
else
abstract_element.document().update_style_for_element(abstract_element, DOM::Document::StyleUpdateMode::OnlyIfNeeded);
@@ -809,6 +820,11 @@ static Optional<Layout::NodeWithStyle*> prepare_computed_style_and_layout_for_pr
if (needs_layout_for_container_queries) {
abstract_element.document().update_layout_if_needed_for_node(abstract_element.element(), DOM::UpdateLayoutReason::ResolvedCSSStyleDeclarationProperty);
layout_node = abstract_element.layout_node(read);
+ // NB: The style update of the layout skips display:none subtrees, so a style read below one is answered
+ // again against the container sizes the layout settled.
+ if (auto const& settled_style = abstract_element.installed_style(); !layout_node && settled_style
+ && has_flag(settled_style.dependency_flags(), StyleRecordDependencyFlag::InDisplayNoneSubtree))
+ abstract_element.document().update_style_for_element(abstract_element);
// A synthetic pseudo which is not rendered is not part of the layout-driven pseudo
// recomputation above. Refresh its CSSOM-only style against the settled container size.
ensure_pseudo_element_style_for_cssom(read, abstract_element);
@@ -965,9 +981,9 @@ Optional<StyleProperty> CSSStyleProperties::get_direct_property(PropertyNameAndI
case PropertyID::WebkitTextFillColor:
return resolve_color_style_value(*computed_value, computed_values->webkit_text_fill_color()).release_nonnull();
case PropertyID::BoxShadow:
- return style_value_for_shadow(ShadowStyleValue::ShadowType::Normal, computed_values->box_shadow()).release_nonnull();
+ return style_value_for_shadow(ShadowStyleValue::ShadowType::Normal, computed_values->box_shadow(), computed_values->color()).release_nonnull();
case PropertyID::TextShadow:
- return style_value_for_shadow(ShadowStyleValue::ShadowType::Text, computed_values->text_shadow()).release_nonnull();
+ return style_value_for_shadow(ShadowStyleValue::ShadowType::Text, computed_values->text_shadow(), computed_values->color()).release_nonnull();
case PropertyID::BackdropFilter:
case PropertyID::Filter:
return resolve_filter_style_value(move(computed_value), computed_values->color());
@@ -981,7 +997,7 @@ Optional<StyleProperty> CSSStyleProperties::get_direct_property(PropertyNameAndI
// For backwards-compatibility, the resolved value of this keyword is zero for boxes of all [CSS2]
// display types (block and inline boxes, inline blocks, and all table display types) when
// 'aspect-ratio' is 'auto'. It also resolves to zero when no box is generated.
- if (computed_value->to_keyword() == Keyword::Auto && element_generates_no_box(read, abstract_element, *computed_values))
+ if (computed_value->to_keyword() == Keyword::Auto && element_generates_no_box(abstract_element, *computed_values))
return LengthStyleValue::create(Length::make_px(0));
return resolve_unresolvable_anchor_functions(computed_property_id, move(computed_value));
case PropertyID::MaxHeight:
@@ -1016,7 +1032,7 @@ Optional<StyleProperty> CSSStyleProperties::get_direct_property(PropertyNameAndI
return {};
return StyleProperty {
.property_id = property_id,
- .value = unscaled_by_zoom(property_id, value.release_nonnull(), layout_node->style_group<ComputedValues::InheritedBoxValues>().effective_zoom_value()),
+ .value = unscaled_by_zoom(property_id, value.release_nonnull(), effective_zoom_of(layout_node->inherited_set_values())),
};
}
@@ -1364,7 +1380,7 @@ RefPtr<StyleValue const> CSSStyleProperties::style_value_for_computed_property(L
static_cast<StyleValueFFI::StyleValueData const*>(handle.pointer)));
return resolve_color_style_value(
*style_value,
- background_values->background_color_value(),
+ background_values->background_color_value(element.style_group<ComputedValues::InheritedTextValues>(pseudo_element)->color_value()),
color_resolution_style);
}
case PropertyID::BorderBottomColor:
@@ -1376,7 +1392,7 @@ RefPtr<StyleValue const> CSSStyleProperties::style_value_for_computed_property(L
case PropertyID::BorderTopColor:
return resolve_color_style_value(*get_computed_value(property_id), layout_node.border_top().color, color_resolution_style);
case PropertyID::BoxShadow:
- return style_value_for_shadow(ShadowStyleValue::ShadowType::Normal, layout_node.box_shadow());
+ return style_value_for_shadow(ShadowStyleValue::ShadowType::Normal, layout_node.box_shadow(), layout_node.color());
case PropertyID::CaretColor:
return resolve_color_style_value(*get_computed_value(property_id), layout_node.caret_color(), color_resolution_style);
case PropertyID::Color: {
@@ -1396,7 +1412,7 @@ RefPtr<StyleValue const> CSSStyleProperties::style_value_for_computed_property(L
case PropertyID::TextDecorationColor:
return resolve_color_style_value(*get_computed_value(property_id), layout_node.text_decoration_color(), color_resolution_style);
case PropertyID::TextShadow:
- return style_value_for_shadow(ShadowStyleValue::ShadowType::Text, layout_node.text_shadow());
+ return style_value_for_shadow(ShadowStyleValue::ShadowType::Text, layout_node.text_shadow(), layout_node.color());
case PropertyID::BackdropFilter:
case PropertyID::Filter:
return resolve_filter_style_value(*get_computed_value(property_id), layout_node.color());
@@ -1411,7 +1427,7 @@ RefPtr<StyleValue const> CSSStyleProperties::style_value_for_computed_property(L
return line_height;
auto const* font_values = element.style_group<ComputedValues::FontValues>(pseudo_element);
VERIFY(font_values);
- return LengthStyleValue::create(Length::make_px(font_values->line_height_used));
+ return LengthStyleValue::create(Length::make_px(font_values->line_height_used_value()));
}
// -> block-size
@@ -1855,6 +1871,11 @@ Utf16String CSSStyleProperties::serialized() const
if (already_serialized.contains(property))
continue;
+ // AD-HOC: A shorthand pending an outer shorthand has no value of its own to serialize. The outer shorthand
+ // serializes for it, or else each of its longhands does.
+ if (property_is_shorthand(property) && declaration.value->is_pending_substitution())
+ continue;
+
// 3. If property maps to one or more shorthand properties, let shorthands be an array of those shorthand properties, in preferred order.
if (property_maps_to_shorthand(property)) {
auto shorthands = shorthands_for_longhand(property);
diff --git a/Libraries/LibWeb/CSS/ComputedValues.cpp b/Libraries/LibWeb/CSS/ComputedValues.cpp
index 3b884153230..07128b8f944 100644
--- a/Libraries/LibWeb/CSS/ComputedValues.cpp
+++ b/Libraries/LibWeb/CSS/ComputedValues.cpp
@@ -158,6 +158,14 @@ void ComputedValues::borrow_style_record_groups(void const* groups)
m_noninherited.reset_bits = style_record_reset_bits(groups);
}
+bool InstalledStyle::display_is_none_ignoring_animations() const
+{
+ if (!m_record)
+ return false;
+ auto view = this->view();
+ return StyleEngineFFI::style_engine_view_display_is_none_ignoring_animations(&view);
+}
+
bool InstalledStyle::display_is_none() const
{
if (!m_record)
diff --git a/Libraries/LibWeb/CSS/CountersSet.cpp b/Libraries/LibWeb/CSS/CountersSet.cpp
index d5624f2670f..d56e81eec23 100644
--- a/Libraries/LibWeb/CSS/CountersSet.cpp
+++ b/Libraries/LibWeb/CSS/CountersSet.cpp
@@ -20,7 +20,7 @@ bool innermost_list_item_counter_is_own_forward_counter(DOM::Element const& elem
auto const& style = element.installed_style();
if (!style)
return false;
- return Layout::RustFFI::style_resets_forward_list_item_counter(style.view().payloads, style.view().payload_count);
+ return Layout::RustFFI::style_resets_forward_list_item_counter(style.view().groups);
}
Utf16FlyString const& list_item_counter_name()
diff --git a/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp b/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
new file mode 100644
index 00000000000..8328f1cfafc
--- /dev/null
+++ b/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp
@@ -0,0 +1,533 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Array.h>
+#include <AK/BinarySearch.h>
+#include <AK/Bitmap.h>
+#include <AK/BuiltinWrappers.h>
+#include <AK/Debug.h>
+#include <AK/Error.h>
+#include <AK/Find.h>
+#include <AK/FixedBitmap.h>
+#include <AK/Function.h>
+#include <AK/HashMap.h>
+#include <AK/HashTable.h>
+#include <AK/JsonObject.h>
+#include <AK/Math.h>
+#include <AK/NeverDestroyed.h>
+#include <AK/NonnullRawPtr.h>
+#include <AK/QuickSort.h>
+#include <AK/ScopeGuard.h>
+#include <AK/Utf8View.h>
+#include <LibGC/Heap.h>
+#include <LibGfx/Font/FontDatabase.h>
+#include <LibWeb/Animations/AnimationEffect.h>
+#include <LibWeb/Animations/DocumentTimeline.h>
+#include <LibWeb/Animations/ScrollTimeline.h>
+#include <LibWeb/Animations/ViewTimeline.h>
+#include <LibWeb/Bindings/PrincipalHostDefined.h>
+#include <LibWeb/CSS/AnimationEvent.h>
+#include <LibWeb/CSS/CSSAnimation.h>
+#include <LibWeb/CSS/CSSImportRule.h>
+#include <LibWeb/CSS/CSSLayerBlockRule.h>
+#include <LibWeb/CSS/CSSLayerStatementRule.h>
+#include <LibWeb/CSS/CSSNestedDeclarations.h>
+#include <LibWeb/CSS/CSSScopeRule.h>
+#include <LibWeb/CSS/CSSStyleProperties.h>
+#include <LibWeb/CSS/CSSStyleRule.h>
+#include <LibWeb/CSS/CSSTransition.h>
+#include <LibWeb/CSS/ComputedStyleWorkingSet.h>
+#include <LibWeb/CSS/ContainerQuery.h>
+#include <LibWeb/CSS/CustomPropertyData.h>
+#include <LibWeb/CSS/CustomPropertyRegistration.h>
+#include <LibWeb/CSS/FontComputer.h>
+#include <LibWeb/CSS/FontFace.h>
+#include <LibWeb/CSS/FontFaceState.h>
+#include <LibWeb/CSS/HypotheticalElement.h>
+#include <LibWeb/CSS/Parser/Parser.h>
+#include <LibWeb/CSS/Parser/SyntaxParsing.h>
+#include <LibWeb/CSS/PropertyNameAndID.h>
+#include <LibWeb/CSS/SelectorMatching.h>
+#include <LibWeb/CSS/StyleComputeFFI.h>
+#include <LibWeb/CSS/StyleComputer.h>
+#include <LibWeb/CSS/StyleEngineEffectTiming.h>
+#include <LibWeb/CSS/StyleEngineInput.h>
+#include <LibWeb/CSS/StyleProperty.h>
+#include <LibWeb/CSS/StyleScope.h>
+#include <LibWeb/CSS/StyleSheetIdentifier.h>
+#include <LibWeb/CSS/StyleSheetState.h>
+#include <LibWeb/CSS/StyleValues/AngleStyleValue.h>
+#include <LibWeb/CSS/StyleValues/ColorStyleValue.h>
+#include <LibWeb/CSS/StyleValues/CustomIdentStyleValue.h>
+#include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
+#include <LibWeb/CSS/StyleValues/FontStyleStyleValue.h>
+#include <LibWeb/CSS/StyleValues/FrequencyStyleValue.h>
+#include <LibWeb/CSS/StyleValues/FunctionStyleValue.h>
+#include <LibWeb/CSS/StyleValues/IntegerStyleValue.h>
+#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
+#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
+#include <LibWeb/CSS/StyleValues/NumberStyleValue.h>
+#include <LibWeb/CSS/StyleValues/PendingSubstitutionStyleValue.h>
+#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
+#include <LibWeb/CSS/StyleValues/RatioStyleValue.h>
+#include <LibWeb/CSS/StyleValues/ShorthandStyleValue.h>
+#include <LibWeb/CSS/StyleValues/StringStyleValue.h>
+#include <LibWeb/CSS/StyleValues/StyleValueList.h>
+#include <LibWeb/CSS/StyleValues/TimeStyleValue.h>
+#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>
+#include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>
+#include <LibWeb/DOM/Attr.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/Element.h>
+#include <LibWeb/DOM/SelectorQuery.h>
+#include <LibWeb/DOM/ShadowRoot.h>
+#include <LibWeb/DOM/Text.h>
+#include <LibWeb/HTML/AttributeNames.h>
+#include <LibWeb/HTML/HTMLBRElement.h>
+#include <LibWeb/HTML/HTMLImageElement.h>
+#include <LibWeb/HTML/HTMLInputElement.h>
+#include <LibWeb/HTML/HTMLSlotElement.h>
+#include <LibWeb/HTML/HTMLVideoElement.h>
+#include <LibWeb/HTML/Parser/HTMLParser.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/Layout/LayoutRustBridge.h>
+#include <LibWeb/Layout/Node.h>
+#include <LibWeb/MathML/MathMLElement.h>
+#include <LibWeb/Namespace.h>
+#include <LibWeb/Page/Page.h>
+#include <LibWeb/Page/RenderingStats.h>
+#include <LibWeb/Platform/FontPlugin.h>
+#include <LibWeb/SVG/SVGElement.h>
+#include <LibWeb/StyleValueRustFFI.h>
+#include <LibWeb/ValueParserRustFFI.h>
+#include <math.h>
+
+namespace Web::CSS {
+
+// What a rule contributes, for the two rule types that carry a declaration block.
+static RustDeclarationBlock const& declaration_of_rule(CSSRule const& rule)
+{
+ if (rule.type() == CSSRule::Type::Style)
+ return static_cast<CSSStyleRule const&>(rule).declaration();
+ if (rule.type() == CSSRule::Type::NestedDeclarations)
+ return static_cast<CSSNestedDeclarations const&>(rule).declaration();
+ VERIFY_NOT_REACHED();
+}
+
+static bool custom_property_inherits(DOM::Document const& document, Utf16FlyString const& name)
+{
+ // A custom property inherits unless it has been registered with an explicit `inherits: false`.
+ auto registration = document.get_registered_custom_property(name);
+ return !registration.has_value() || registration->inherit;
+}
+
+enum class IsCustomProperty : u8 {
+ No,
+ Yes,
+};
+
+enum class Inherits : u8 {
+ No,
+ Yes,
+};
+
+enum class NameIsValid : u8 {
+ No,
+ Yes,
+};
+
+enum class IsValid : u8 {
+ No,
+ Yes,
+};
+
+static JsonObject serialize_devtools_style_declaration(
+ String name,
+ String value,
+ Important important,
+ IsCustomProperty is_custom_property,
+ Inherits inherits,
+ NameIsValid is_name_valid,
+ IsValid is_valid)
+{
+ JsonObject serialized_property;
+ serialized_property.set("name"sv, move(name));
+ serialized_property.set("value"sv, move(value));
+ serialized_property.set("priority"sv, important == Important::Yes ? "important"sv : ""sv);
+ serialized_property.set("isCustomProperty"sv, is_custom_property == IsCustomProperty::Yes);
+ serialized_property.set("inherits"sv, inherits == Inherits::Yes);
+ serialized_property.set("isNameValid"sv, is_name_valid == NameIsValid::Yes);
+ serialized_property.set("isValid"sv, is_valid == IsValid::Yes);
+ return serialized_property;
+}
+
+static JsonArray serialize_devtools_style_declarations(DOM::Document const& document, RustDeclarationBlock const& declaration)
+{
+ JsonArray declarations;
+
+ auto serialize_property = [&](Utf16FlyString const& name, StyleProperty const& property, IsCustomProperty is_custom_property, Inherits inherits) {
+ declarations.must_append(serialize_devtools_style_declaration(
+ name.to_utf16_string().to_utf8_but_should_be_ported_to_utf16(),
+ property.value->to_string(SerializationMode::Normal),
+ property.important,
+ is_custom_property,
+ inherits,
+ NameIsValid::Yes,
+ IsValid::Yes));
+ };
+
+ for (auto const& property : declaration.properties()) {
+ serialize_property(
+ string_from_property_id(property.property_id),
+ property,
+ IsCustomProperty::No,
+ is_inherited_property(property.property_id) ? Inherits::Yes : Inherits::No);
+ }
+
+ for (auto const& custom_property : declaration.custom_properties())
+ serialize_property(
+ custom_property.key,
+ custom_property.value,
+ IsCustomProperty::Yes,
+ custom_property_inherits(document, custom_property.key) ? Inherits::Yes : Inherits::No);
+
+ return declarations;
+}
+
+static JsonArray serialize_devtools_style_declarations(DOM::Document const& document, Vector<Parser::DevToolsStyleDeclaration> const& declarations)
+{
+ JsonArray serialized_declarations;
+
+ for (auto const& declaration : declarations) {
+ bool inherits = declaration.is_custom_property
+ ? custom_property_inherits(document, declaration.name)
+ : PropertyNameAndID::from_name(declaration.name)
+ .map([](auto const& property) { return !property.is_custom_property() && is_inherited_property(property.id()); })
+ .value_or(false);
+
+ serialized_declarations.must_append(serialize_devtools_style_declaration(
+ MUST(declaration.name.view().to_utf8()),
+ declaration.value.to_utf8(),
+ declaration.important,
+ declaration.is_custom_property ? IsCustomProperty::Yes : IsCustomProperty::No,
+ inherits ? Inherits::Yes : Inherits::No,
+ declaration.is_name_valid ? NameIsValid::Yes : NameIsValid::No,
+ declaration.is_valid ? IsValid::Yes : IsValid::No));
+ }
+
+ return serialized_declarations;
+}
+
+static Vector<Parser::DevToolsStyleDeclaration> parse_devtools_style_declarations(DOM::Document const& document, StringView declaration_block)
+{
+ return Parser::parse_css_declaration_block_for_devtools(Parser::ParsingParams(document), declaration_block);
+}
+
+static Vector<Parser::DevToolsStyleDeclaration> parse_devtools_style_declarations(DOM::Document const& document, Utf16View declaration_block)
+{
+ return Parser::parse_css_declaration_block_for_devtools(Parser::ParsingParams(document), declaration_block);
+}
+
+static Optional<size_t> source_offset_for_line_and_column(StringView source, SourcePosition const& position)
+{
+ size_t line = 0;
+ size_t column = 0;
+
+ Utf8View source_code_points { source };
+ for (auto it = source_code_points.begin(); it != source_code_points.end();) {
+ auto offset = source_code_points.byte_offset_of(it);
+ if (line == position.line && column == position.column)
+ return offset;
+
+ auto code_point = *it;
+ ++it;
+
+ if (code_point == '\r') {
+ if (offset + 1 < source.length() && source[offset + 1] == '\n')
+ ++it;
+ ++line;
+ column = 0;
+ } else if (code_point == '\n' || code_point == '\f') {
+ ++line;
+ column = 0;
+ } else {
+ ++column;
+ }
+ }
+
+ if (line == position.line && column == position.column)
+ return source.length();
+
+ return {};
+}
+
+static Optional<String> extract_css_declaration_block_from_source(CSSRule const& rule)
+{
+ if (rule.type() != CSSRule::Type::Style)
+ return {};
+
+ auto const* style_sheet = rule.parent_style_sheet();
+ if (!style_sheet)
+ return {};
+
+ auto const source_text = style_sheet->source_text();
+ if (!source_text.has_value())
+ return {};
+
+ auto source = source_text->to_utf8();
+ auto source_view = source.bytes_as_string_view();
+ auto const& source_location = rule.source_location();
+ if (!source_location.has_value())
+ return {};
+
+ auto maybe_offset = source_offset_for_line_and_column(source_view, *source_location);
+ if (!maybe_offset.has_value())
+ return {};
+
+ Optional<u8> string_quote;
+ bool in_comment = false;
+ bool escaped = false;
+ Optional<size_t> block_start;
+ size_t block_depth = 0;
+
+ for (size_t offset = *maybe_offset; offset < source_view.length(); ++offset) {
+ auto ch = source_view[offset];
+ auto next_ch = offset + 1 < source_view.length() ? source_view[offset + 1] : '\0';
+
+ if (in_comment) {
+ if (ch == '*' && next_ch == '/') {
+ in_comment = false;
+ ++offset;
+ }
+ continue;
+ }
+
+ if (string_quote.has_value()) {
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (ch == '\\') {
+ escaped = true;
+ continue;
+ }
+ if (ch == *string_quote)
+ string_quote = {};
+ continue;
+ }
+
+ if (ch == '/' && next_ch == '*') {
+ in_comment = true;
+ ++offset;
+ continue;
+ }
+
+ if (ch == '"' || ch == '\'') {
+ string_quote = ch;
+ continue;
+ }
+
+ if (ch == '{') {
+ if (!block_start.has_value())
+ block_start = offset + 1;
+ ++block_depth;
+ continue;
+ }
+
+ if (ch == '}' && block_start.has_value()) {
+ VERIFY(block_depth > 0);
+ --block_depth;
+ if (block_depth == 0)
+ return MUST(String::from_utf8(source_view.substring_view(*block_start, offset - *block_start)));
+ }
+ }
+
+ return {};
+}
+
+static bool has_inherited_declaration(DOM::Document const& document, ReadonlySpan<StyleProperty> properties, OrderedHashMap<Utf16FlyString, StyleProperty> const& custom_properties)
+{
+ if (any_of(properties, [](auto const& property) {
+ return CSS::is_inherited_property(property.property_id);
+ })) {
+ return true;
+ }
+
+ return any_of(custom_properties, [&](auto const& custom_property) {
+ return custom_property_inherits(document, custom_property.key);
+ });
+}
+
+static JsonObject serialize_devtools_style_sheet_identifier(StyleSheetIdentifier const& identifier)
+{
+ JsonObject serialized_identifier;
+ serialized_identifier.set("type"sv, style_sheet_identifier_type_to_string(identifier.type));
+ if (identifier.dom_element_unique_id.has_value())
+ serialized_identifier.set("domElementUniqueId"sv, identifier.dom_element_unique_id->value());
+ if (identifier.url.has_value())
+ serialized_identifier.set("url"sv, identifier.url->to_utf8());
+ serialized_identifier.set("ruleCount"sv, identifier.rule_count);
+ return serialized_identifier;
+}
+
+// What DevTools shows for one rule the engine says decides for this element. Which of the rule's
+// selectors matched is asked with a selector query, because the engine reports the rule rather than
+// the entry, and a panel can afford to match each selector again.
+static JsonObject serialize_devtools_applied_rule(DOM::Document& document, CSSRule const& rule, DOM::AbstractElement const& element)
+{
+ auto const& declaration = declaration_of_rule(rule);
+ auto authored_text = extract_css_declaration_block_from_source(rule);
+ SelectorList const* selector_list = nullptr;
+ if (auto const* style_rule = as_if<CSSStyleRule>(rule))
+ selector_list = &style_rule->absolutized_selectors();
+ else if (auto const* nested = as_if<CSSNestedDeclarations>(rule))
+ selector_list = &nested->absolutized_selectors();
+ SelectorList const empty_selectors;
+ auto const& selectors = selector_list ? *selector_list : empty_selectors;
+
+ JsonArray serialized_selectors;
+ JsonArray specificities;
+ JsonArray matched_selector_indexes;
+ for (size_t index = 0; index < selectors.size(); ++index) {
+ auto const& selector = selectors[index];
+ serialized_selectors.must_append(selector->serialize().to_utf8());
+ specificities.must_append(selector->specificity());
+ SelectorList selector_query_list;
+ selector_query_list.append(selector);
+ auto selector_query = DOM::SelectorQuery::create(move(selector_query_list));
+ if (selector_query->matches(element.element(), document))
+ matched_selector_indexes.must_append(index);
+ }
+
+ JsonObject serialized_rule;
+ serialized_rule.set("type"sv, to_underlying(rule.type()));
+ serialized_rule.set("className"sv, rule.type() == CSSRule::Type::Style ? "CSSStyleRule"sv : "CSSNestedDeclarations"sv);
+ serialized_rule.set("selectors"sv, move(serialized_selectors));
+ serialized_rule.set("selectorsSpecificity"sv, move(specificities));
+ serialized_rule.set("matchedSelectorIndexes"sv, move(matched_selector_indexes));
+ serialized_rule.set("cssText"sv, rule.serialized().to_utf8());
+ if (authored_text.has_value()) {
+ serialized_rule.set("authoredText"sv, *authored_text);
+ serialized_rule.set("declarations"sv, serialize_devtools_style_declarations(document, parse_devtools_style_declarations(document, authored_text->bytes_as_string_view())));
+ } else {
+ auto style = rule.type() == CSSRule::Type::Style
+ ? static_cast<CSSStyleRule const&>(rule).style()
+ : static_cast<CSSNestedDeclarations const&>(rule).style();
+ serialized_rule.set("authoredText"sv, style->serialized().to_utf8());
+ serialized_rule.set("declarations"sv, serialize_devtools_style_declarations(document, declaration));
+ }
+ if (auto* sheet = rule.parent_style_sheet()) {
+ if (auto identifier = style_sheet_identifier_for(*sheet); identifier.has_value())
+ serialized_rule.set("ruleId"sv, serialize_devtools_style_sheet_identifier(*identifier));
+ }
+ return serialized_rule;
+}
+
+static JsonObject serialize_devtools_inline_style(DOM::Document const& document, DOM::AbstractElement abstract_element, CSSStyleProperties const& declaration)
+{
+ auto authored_text = abstract_element.element().get_attribute(HTML::AttributeNames::style);
+
+ JsonObject serialized_rule;
+ serialized_rule.set("type"sv, 100);
+ serialized_rule.set("className"sv, 100);
+ serialized_rule.set("cssText"sv, declaration.serialized().to_utf8());
+ if (authored_text.has_value()) {
+ auto authored_text_utf8 = authored_text->to_utf8();
+ serialized_rule.set("authoredText"sv, authored_text_utf8);
+ serialized_rule.set("declarations"sv, serialize_devtools_style_declarations(document, parse_devtools_style_declarations(document, authored_text->utf16_view())));
+ } else {
+ serialized_rule.set("authoredText"sv, declaration.serialized().to_utf8());
+ serialized_rule.set("declarations"sv, serialize_devtools_style_declarations(document, declaration.declaration_block()));
+ }
+ serialized_rule.set("isSystem"sv, false);
+ serialized_rule.set("nodeId"sv, abstract_element.element().unique_id().value());
+ return serialized_rule;
+}
+
+static void append_devtools_applied_style_entry(JsonArray& entries, JsonObject rule, Optional<UniqueNodeID> inherited_node_id = {})
+{
+ JsonObject entry;
+
+ JsonValue matched_selector_indexes { JsonArray {} };
+ if (auto value = rule.get("matchedSelectorIndexes"sv); value.has_value())
+ matched_selector_indexes = *value;
+ rule.remove("matchedSelectorIndexes"sv);
+ auto is_system = rule.get_bool("isSystem"sv).value_or(false);
+
+ entry.set("rule"sv, move(rule));
+ entry.set("isSystem"sv, is_system);
+ entry.set("matchedSelectorIndexes"sv, move(matched_selector_indexes));
+ if (inherited_node_id.has_value())
+ entry.set("inheritedNodeId"sv, inherited_node_id->value());
+ else
+ entry.set("inherited"sv, JsonValue {});
+
+ entries.must_append(move(entry));
+}
+
+JsonArray StyleComputer::collect_devtools_applied_style_rules(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, bool include_inherited, bool include_user_agent_styles)
+{
+ JsonArray entries;
+
+ auto append_rules_for_abstract_element = [&](DOM::AbstractElement current_element, Optional<UniqueNodeID> inherited_node_id) {
+ if (auto inline_style = current_element.inline_style()) {
+ if (!inherited_node_id.has_value() || has_inherited_declaration(m_document, inline_style->properties(), inline_style->custom_properties()))
+ append_devtools_applied_style_entry(entries, serialize_devtools_inline_style(m_document, current_element, *inline_style), inherited_node_id);
+ }
+
+ auto node = current_element.element().style_node_id();
+ if (node == 0)
+ return;
+ Vector<StyleEngine::MatchedRule> matches;
+ if (!style_engine().matched_rules(read, node, matches))
+ return;
+
+ // The engine reports the rules in the order the cascade applies them, and the panel lists
+ // the winning one first.
+ for (auto const& match : matches.in_reverse()) {
+ if (match.pseudo_element != NumericLimits<u32>::max())
+ continue;
+ auto target = style_engine_rule_target(read, StyleEngineRuleID { match.rule });
+ if (!target.has_value() || !target->source_style_sheet)
+ continue;
+ if (target->cascade_origin == CascadeOrigin::UserAgent && !include_user_agent_styles)
+ continue;
+ if (inherited_node_id.has_value()) {
+ struct Context {
+ GC::Ref<DOM::Document const> document;
+ bool has_inherited_declaration { false };
+ } context { m_document };
+ Parser::ValueParserFFI::rust_declaration_data_visit(target->declaration.data(), &context, [](void* raw_context, Parser::ValueParserFFI::FfiDeclaredProperty const* property) {
+ auto& context = *static_cast<Context*>(raw_context);
+ if (context.has_inherited_declaration)
+ return;
+ if (property->name.length == 0)
+ context.has_inherited_declaration = is_inherited_property(static_cast<PropertyID>(property->property_id));
+ else
+ context.has_inherited_declaration = custom_property_inherits(context.document, Utf16FlyString::from_utf16({ reinterpret_cast<char16_t const*>(property->name.utf16), property->name.length }));
+ });
+ if (!context.has_inherited_declaration)
+ continue;
+ }
+ auto* rule = target->source_style_sheet->rules().rule_for_identity(target->rule_identity);
+ if (!rule)
+ continue;
+ append_devtools_applied_style_entry(entries, serialize_devtools_applied_rule(m_document, *rule, current_element), inherited_node_id);
+ }
+ };
+
+ append_rules_for_abstract_element(abstract_element, {});
+
+ if (!include_inherited)
+ return entries;
+
+ for (auto current_element = abstract_element.element_to_inherit_style_from(); current_element.has_value(); current_element = current_element->element_to_inherit_style_from())
+ append_rules_for_abstract_element(*current_element, current_element->element().unique_id());
+
+ return entries;
+}
+
+}
diff --git a/Libraries/LibWeb/CSS/HypotheticalElement.cpp b/Libraries/LibWeb/CSS/HypotheticalElement.cpp
index 6c7b314a940..066674249ff 100644
--- a/Libraries/LibWeb/CSS/HypotheticalElement.cpp
+++ b/Libraries/LibWeb/CSS/HypotheticalElement.cpp
@@ -60,7 +60,7 @@ RefPtr<StyleValue const> AbstractOrHypotheticalElement::get_custom_property(Utf1
return abstract_element.get_custom_property(name);
},
[&](HypotheticalElement* hypothetical_element) -> RefPtr<StyleValue const> {
- if (auto const* property = hypothetical_element->custom_property_data->get(name))
+ if (auto property = hypothetical_element->custom_property_data->get(name); property.has_value())
return property->value;
return nullptr;
});
diff --git a/Libraries/LibWeb/CSS/InstalledStyle.h b/Libraries/LibWeb/CSS/InstalledStyle.h
index 51fc97114d5..cafe72d9133 100644
--- a/Libraries/LibWeb/CSS/InstalledStyle.h
+++ b/Libraries/LibWeb/CSS/InstalledStyle.h
@@ -6,44 +6,101 @@
#pragma once
+#include <AK/StdLibExtras.h>
#include <LibWeb/CSS/StyleRecordID.h>
#include <LibWeb/StyleEngineRustFFI.h>
namespace Web::CSS {
-// The style record an element or a pseudo-element installed, with the view of it the host reads. The element holds the
-// record in the style engine for as long as it has it installed, and a record's view is written once and replaced,
-// never changed, so reading the installed style asks nothing of the engine, which may be in a frame in flight.
+enum class StyleRecordDependencyFlag : u8;
+
+// The computed style an element or a pseudo-element installed: a counted reference to the record the engine installed
+// for it, or to the sample of its animations over that record. Records never change, so reading the installed style
+// reads the record and asks nothing of the engine, which may be in a frame in flight.
class InstalledStyle {
public:
InstalledStyle() = default;
- InstalledStyle(StyleRecordID record, StyleEngineFFI::FfiStyleRecordView const& view)
+ // Takes a reference to `record`, a record the engine handed out, or none for null.
+ explicit InstalledStyle(void const* record)
: m_record(record)
- , m_view(view)
{
+ if (m_record)
+ StyleEngineFFI::style_engine_record_retain(m_record);
+ }
+ // Takes over a reference to `record` the engine handed out, or none for null.
+ static InstalledStyle adopt(void const* record)
+ {
+ InstalledStyle installed;
+ installed.m_record = record;
+ return installed;
+ }
+ InstalledStyle(InstalledStyle const& other)
+ : InstalledStyle(other.m_record)
+ {
+ }
+ InstalledStyle(InstalledStyle&& other)
+ : m_record(exchange(other.m_record, nullptr))
+ {
+ }
+ InstalledStyle& operator=(InstalledStyle const& other)
+ {
+ if (this != &other) {
+ InstalledStyle copy { other };
+ swap(m_record, copy.m_record);
+ }
+ return *this;
+ }
+ InstalledStyle& operator=(InstalledStyle&& other)
+ {
+ if (this != &other) {
+ InstalledStyle moved { move(other) };
+ swap(m_record, moved.m_record);
+ }
+ return *this;
+ }
+ ~InstalledStyle()
+ {
+ if (m_record)
+ StyleEngineFFI::style_engine_record_release(m_record);
}
- StyleRecordID record() const { return m_record; }
- StyleEngineFFI::FfiStyleRecordView const& view() const { return m_view; }
- explicit operator bool() const { return m_view.present; }
+ StyleRecordID record() const { return m_record ? StyleRecordID { StyleEngineFFI::style_engine_record_identity(m_record) } : StyleRecordID {}; }
+ StyleEngineFFI::FfiStyleRecordView view() const { return m_record ? StyleEngineFFI::style_engine_record_view(m_record) : StyleEngineFFI::FfiStyleRecordView {}; }
+ explicit operator bool() const { return m_record; }
+ // Whether both hold the same record, which no other record shares the identity of.
+ bool operator==(InstalledStyle const& other) const { return m_record == other.m_record; }
- // The record's group payloads, one per style group, or null where nothing is installed.
- void const* payloads() const { return m_view.present ? m_view.payloads : nullptr; }
+ // What the record's values depend on, or nothing where nothing is installed.
+ StyleRecordDependencyFlag dependency_flags() const { return static_cast<StyleRecordDependencyFlag>(view().dependency_flags); }
+
+ // The identity of the custom-property environment the record was resolved in, or 0.
+ u64 custom_property_environment() const { return m_record ? StyleEngineFFI::style_engine_record_custom_property_environment(m_record) : 0; }
+
+ // The record itself, as the engine's entries that read a record the host holds take it, or null.
+ void const* record_pointer() const { return m_record; }
+
+ // The record's groups, which `CSS::style_record_group` reads, or null where nothing is installed. NB: A record's
+ // groups are at its head.
+ void const* groups() const { return m_record; }
// Whether the record's own display, beneath any animation, is none, read straight out of its box group payload.
bool display_is_none() const;
+ bool display_is_none_ignoring_animations() const;
// Whether `animated_overlay` changes any effective value of the record in place of its own overlay, read from the
// record itself.
bool animation_overlay_changed(void const* animated_overlay) const
{
- VERIFY(m_view.present);
- return StyleEngineFFI::style_engine_animation_overlay_changed(&m_view, animated_overlay);
+ VERIFY(m_record);
+ auto view = this->view();
+ return StyleEngineFFI::style_engine_animation_overlay_changed(&view, animated_overlay);
}
private:
- StyleRecordID m_record;
- StyleEngineFFI::FfiStyleRecordView m_view {};
+ void const* m_record { nullptr };
};
+// NB: Every element and pseudo-element the host styles holds one of these.
+static_assert(sizeof(InstalledStyle) == sizeof(void*));
+
}
diff --git a/Libraries/LibWeb/CSS/StyleEngineBridge.cpp b/Libraries/LibWeb/CSS/StyleEngineBridge.cpp
index 72068c24a31..f2a991b2dc2 100644
--- a/Libraries/LibWeb/CSS/StyleEngineBridge.cpp
+++ b/Libraries/LibWeb/CSS/StyleEngineBridge.cpp
@@ -7,6 +7,7 @@
#include <AK/HashTable.h>
#include <AK/StdLibExtras.h>
#include <AK/Time.h>
+#include <LibGC/WeakInlines.h>
#include <LibWeb/CSS/ComputedStyleWorkingSet.h>
#include <LibWeb/CSS/FontComputer.h>
#include <LibWeb/CSS/FontResolution.h>
@@ -28,7 +29,6 @@
namespace Web::CSS {
-static_assert(StyleEngineFFI::LAST_SYNTHETIC_PSEUDO_ELEMENT_KIND == to_underlying(last_synthetic_pseudo_element));
static_assert(StyleEngineFFI::FIRST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND == to_underlying(first_element_reference_pseudo_element));
static_assert(StyleEngineFFI::LAST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND == to_underlying(last_element_reference_pseudo_element));
static_assert(!IsMoveConstructible<StyleEngine>);
@@ -36,27 +36,46 @@ static_assert(!IsMoveAssignable<StyleEngine>);
StyleEngine::StyleEngine(StyleComputer* style_computer)
: m_render_document(Layout::RenderDocument::create())
- , m_style_node_ids(StyleEngineFFI::style_node_id_allocator_create())
, m_style_computer(style_computer)
{
- if (m_style_computer) {
- StyleEngineFFI::style_engine_set_pseudo_element_style_deferred(host(), to_underlying(PseudoElement::Selection), true);
- StyleEngineFFI::style_engine_set_pseudo_element_style_deferred(host(), to_underlying(PseudoElement::SearchText), true);
- StyleEngineFFI::style_engine_set_pseudo_element_style_deferred(host(), to_underlying(PseudoElement::SearchTextCurrent), true);
- StyleEngineFFI::style_engine_set_pseudo_element_style_deferred(host(), to_underlying(PseudoElement::SpellingError), true);
- }
}
-StyleEngine::~StyleEngine()
-{
- StyleEngineFFI::style_node_id_allocator_destroy(m_style_node_ids);
-}
+StyleEngine::~StyleEngine() = default;
void StyleEngine::visit_edges(GC::Cell::Visitor& visitor)
{
visitor.visit(m_style_computer);
}
+// More nodes than this waiting to arrive at once are found along the marks instead.
+static constexpr size_t max_listed_arrivals = 4096;
+
+void StyleEngine::list_arrival(DOM::Node& node)
+{
+ if (m_arrivals_unlisted)
+ return;
+ if (m_listed_arrivals.size() == max_listed_arrivals) {
+ m_arrivals_unlisted = true;
+ m_listed_arrivals.clear();
+ return;
+ }
+ m_listed_arrivals.append(GC::Weak<DOM::Node> { node });
+}
+
+Optional<GC::RootVector<GC::Ref<DOM::Node>>> StyleEngine::take_listed_arrivals()
+{
+ auto listed = move(m_listed_arrivals);
+ if (exchange(m_arrivals_unlisted, false))
+ return {};
+ GC::RootVector<GC::Ref<DOM::Node>> nodes;
+ nodes.ensure_capacity(listed.size());
+ for (auto const& node : listed) {
+ if (auto pointer = node.ptr())
+ nodes.unchecked_append(*pointer);
+ }
+ return nodes;
+}
+
StyleNodeID StyleEngine::mint_style_node()
{
StyleNodeID node;
@@ -69,13 +88,7 @@ void StyleEngine::mint_style_nodes(Span<StyleNodeID> nodes)
if (nodes.is_empty())
return;
Span<u32> raw_nodes { reinterpret_cast<u32*>(nodes.data()), nodes.size() };
- StyleEngineFFI::style_node_id_allocator_mint(m_style_node_ids, false, raw_nodes);
- StyleEngineFFI::style_engine_mint_style_nodes(m_render_document->host(), raw_nodes);
- // An element minted beside a style transaction that flew is unknown to it, whenever its arrival is recorded.
- if (has_flown_style_transaction()) {
- for (auto node : nodes)
- StyleEngineFFI::style_engine_note_style_node_beside_flown_transaction(host(), node.value());
- }
+ StyleEngineFFI::style_engine_mint_style_nodes(m_render_document->host(), false, raw_nodes);
}
void StyleEngine::mint_text_style_nodes(Span<StyleNodeID> nodes)
@@ -83,8 +96,7 @@ void StyleEngine::mint_text_style_nodes(Span<StyleNodeID> nodes)
if (nodes.is_empty())
return;
Span<u32> raw_nodes { reinterpret_cast<u32*>(nodes.data()), nodes.size() };
- StyleEngineFFI::style_node_id_allocator_mint(m_style_node_ids, true, raw_nodes);
- StyleEngineFFI::style_engine_mint_style_nodes(m_render_document->host(), raw_nodes);
+ StyleEngineFFI::style_engine_mint_style_nodes(m_render_document->host(), true, raw_nodes);
}
HashTable<StyleNodeID> StyleEngine::take_deferred_element_initial_features()
@@ -103,9 +115,9 @@ void StyleEngine::set_element_parts(StyleNodeID node, ReadonlySpan<StyleAtomID>
StyleEngineFFI::style_engine_set_element_parts(m_render_document->host(), node.value(), reinterpret_cast<u32 const*>(names.data()), reinterpret_cast<u32 const*>(hosts.data()), names.size());
}
-SheetID StyleEngine::add_sheet(u32 object, StyleEngineFFI::FfiCascadeOrigin origin)
+SheetID StyleEngine::add_sheet(StyleEngineFFI::FfiCascadeOrigin origin)
{
- return SheetID { StyleEngineFFI::style_engine_add_sheet(m_render_document->host(), object, origin) };
+ return SheetID { StyleEngineFFI::style_engine_add_sheet(m_render_document->host(), origin) };
}
void StyleEngine::finish_sheet_rules_replacement(SheetID sheet)
@@ -135,26 +147,14 @@ void StyleEngine::set_element_presentational_hint_properties(StyleNodeID node, S
note_css_transitions_may_observe_style_changes();
}
-StyleEngine::StyleRecordDelta StyleEngine::publish_computed_groups(Layout::BegunRead const& read, StyleNodeID node, u8 pseudo_kind, ReadonlySpan<void const*> payloads, size_t inherited_group_count, u64 custom_property_environment, bool inherited_group_swap_candidate, u64 counter_style_environment_identity, u64 animation_overlay_identity, void const* animated_overlay, ReadonlySpan<void const*> animation_overlay_payloads, void const* computed_longhand_table, void const* custom_property_store)
+StyleRecordID StyleEngine::install_host_style_record(Layout::BegunRead const& read, ReadonlySpan<void const*> payloads, ComputedValuesFFI::InheritedSetValues inherited, ComputedValuesFFI::ResetBits reset, u64 custom_property_environment, u64 counter_style_environment_identity, void const* source_record, void const* custom_property_store)
{
- VERIFY(inherited_group_count <= payloads.size());
- auto delta = StyleEngineFFI::style_engine_publish_computed_groups(host(), &read, node.value(), pseudo_kind, payloads.data(), payloads.size(), inherited_group_count, custom_property_environment, inherited_group_swap_candidate, counter_style_environment_identity, animation_overlay_identity, animated_overlay, animation_overlay_payloads.data(), animation_overlay_payloads.size(), computed_longhand_table, custom_property_store);
- return { StyleRecordID { delta.old_style_record }, StyleRecordID { delta.new_style_record } };
+ return StyleRecordID { StyleEngineFFI::style_engine_install_host_style_record(host(), &read, payloads.data(), payloads.size(), inherited.bits, inherited.effective_zoom_bits, reset, custom_property_environment, counter_style_environment_identity, source_record, custom_property_store) };
}
-StyleRecordDependencyFlag StyleEngine::style_record_dependency_flags(Layout::BegunRead const& read, StyleRecordID style_record) const
+void const* StyleEngine::host_record(Layout::BegunRead const& read, StyleRecordID style_record) const
{
- return static_cast<StyleRecordDependencyFlag>(StyleEngineFFI::style_engine_style_record_dependency_flags(m_render_document->host(), &read, style_record.value()));
-}
-
-u64 StyleEngine::style_record_custom_property_environment(Layout::BegunRead const& read, StyleRecordID style_record) const
-{
- return StyleEngineFFI::style_engine_style_record_custom_property_environment(m_render_document->host(), &read, style_record.value());
-}
-
-StyleEngine::StyleRecordView StyleEngine::style_record_view(Layout::BegunRead const& read, StyleRecordID style_record) const
-{
- return StyleEngineFFI::style_engine_style_record_view(host(), &read, style_record.value());
+ return StyleEngineFFI::style_engine_host_record(host(), &read, style_record.value());
}
ParkedRandomBaseValues StyleEngine::park_element_random_base_values(StyleNodeID node)
@@ -173,17 +173,6 @@ ParkedRandomBaseValues::~ParkedRandomBaseValues()
StyleEngineFFI::style_engine_release_random_base_values(m_slot);
}
-StyleEngine::StyleRecordDelta StyleEngine::remove_computed_pseudo(Layout::BegunRead const& read, StyleNodeID node, u8 pseudo_kind)
-{
- auto delta = StyleEngineFFI::style_engine_remove_computed_pseudo(host(), &read, node.value(), pseudo_kind);
- return { StyleRecordID { delta.old_style_record }, StyleRecordID { delta.new_style_record } };
-}
-
-StyleRecordID StyleEngine::republish_record_environment(Layout::BegunRead const& read, StyleNodeID node, u64 environment, void const* store)
-{
- return StyleRecordID { StyleEngineFFI::style_engine_republish_record_environment(host(), &read, node.value(), environment, store) };
-}
-
#define ASSERT_DEMANDED_PSEUDO_ELEMENT_KIND(name) \
static_assert(to_underlying(StyleEngine::DemandedPseudoElement::name) == to_underlying(PseudoElement::name));
ASSERT_DEMANDED_PSEUDO_ELEMENT_KIND(After)
@@ -236,9 +225,17 @@ StyleAtomID StyleEngine::intern_text_atom(Utf16View text)
StyleAtomID StyleEngine::intern_language_atom(Utf16View text)
{
+ // OPTIMIZATION: Elements arrive in tree order, and most of them have the language of the one before, which the
+ // engine was given the tag of already, unless the atom was reclaimed since.
+ auto generation = atom_generation();
+ if (m_last_language_atom.value() != 0 && m_last_language_atom_generation == generation && m_last_language_text.utf16_view() == text)
+ return m_last_language_atom;
auto atom = intern_text_atom(text);
// The engine is given the language's tag the first time the host names it.
StyleEngineFFI::style_engine_set_element_language(host(), 0, atom.value(), StyleEngineFFI::ffi_utf16_view(text));
+ m_last_language_text = Utf16String::from_utf16(text);
+ m_last_language_atom = atom;
+ m_last_language_atom_generation = generation;
return atom;
}
@@ -249,16 +246,27 @@ void StyleEngine::publish_html_element_namespace(StyleAtomID namespace_atom)
StyleEngineFFI::style_engine_set_html_element_namespace(host(), namespace_atom);
}
-void StyleEngine::backfill_attribute_value_text_if_required(StyleAtomID name, Utf16String const& value)
+StyleEngine::WithheldFeaturesNowRead StyleEngine::take_withheld_features_now_read(Layout::BegunRead const& read)
{
- if (!StyleEngineFFI::document_host_attribute_value_text_is_known_unread(host(), name.value()))
- (void)intern_attribute_value(name, value);
+ WithheldFeaturesNowRead now_read;
+ if (m_withheld_local_link_states.is_empty() && m_withheld_attribute_carriers.is_empty())
+ return now_read;
+ StyleEngineFFI::document_host_learn_selector_requirements(host(), &read);
+ if (!m_withheld_local_link_states.is_empty() && !local_link_is_known_untested())
+ now_read.local_link_states = move(m_withheld_local_link_states);
+ Vector<WithheldAttributeName> names_now_read;
+ for (auto const& [name, carriers] : m_withheld_attribute_carriers) {
+ if (!attribute_is_known_unread(intern_attribute_name(name.local_name, name.namespace_uri)))
+ names_now_read.append(name);
+ }
+ for (auto const& name : names_now_read)
+ now_read.attributes.set(name, m_withheld_attribute_carriers.take(name).release_value());
+ return now_read;
}
void StyleEngine::publish_attribute_value_texts_if_requirements_moved(Layout::BegunRead const& read)
{
- if (StyleEngineFFI::document_host_refresh_attribute_value_text_requirements(host(), &read) && m_style_computer)
- publish_required_attribute_value_texts(*this, *m_style_computer);
+ StyleEngineFFI::document_host_refresh_attribute_value_text_requirements(host(), &read);
}
// Recording input gives the next rendering update style work to do, but touches no layout tree
@@ -332,12 +340,22 @@ void StyleEngine::record_tree_delta(StyleEngineFFI::FfiTreeDelta const& delta)
StyleEngineFFI::style_engine_stage_tree_delta(host(), &delta);
}
-void StyleEngine::record_element_arrival(StyleEngineFFI::FfiElementArrival const& arrival, ReadonlySpan<StyleAtomID> custom_states)
+void StyleEngine::record_element_arrivals(ReadonlySpan<StyleEngineFFI::FfiArrivingElement> elements)
{
+ if (elements.is_empty())
+ return;
flush_deferred_geometry_transaction_before_non_replayable_input(*this, m_style_computer);
request_frame_for_first_recorded_input(*this, m_style_computer);
- StyleEngineFFI::style_engine_stage_element_arrival(host(), &arrival, reinterpret_cast<u32 const*>(custom_states.data()), custom_states.size());
- note_style_node_arrived_or_retired(StyleNodeID { arrival.node });
+ StyleEngineFFI::style_engine_stage_element_arrivals(host(), elements);
+}
+
+void StyleEngine::record_element_arrival(StyleEngineFFI::FfiElementArrival const& arrival, ReadonlySpan<StyleAtomID> custom_states, ReadonlySpan<StyleAtomID> classes, ReadonlySpan<StyleAtomID> attributes)
+{
+ VERIFY(custom_states.size() == arrival.custom_state_count && classes.size() == arrival.class_count && attributes.size() == 2 * static_cast<size_t>(arrival.attribute_count));
+ flush_deferred_geometry_transaction_before_non_replayable_input(*this, m_style_computer);
+ request_frame_for_first_recorded_input(*this, m_style_computer);
+ static_assert(sizeof(StyleAtomID) == sizeof(u32));
+ StyleEngineFFI::style_engine_stage_element_arrival(host(), &arrival, reinterpret_cast<u32 const*>(custom_states.data()), reinterpret_cast<u32 const*>(classes.data()), reinterpret_cast<u32 const*>(attributes.data()));
}
void StyleEngine::record_local_feature_delta(StyleEngineFFI::FfiLocalFeatureDelta const& delta)
@@ -375,25 +393,20 @@ void StyleEngine::record_derived_element_style_input_change(StyleNodeID style_no
}
}
-void StyleEngine::record_container_query_input_change(StyleNodeID style_node)
+void StyleEngine::set_highlight_observing_elements(PseudoElement pseudo_element, ReadonlySpan<StyleNodeID> style_nodes)
{
- if (style_node == 0)
- return;
flush_deferred_geometry_transaction_before_non_replayable_input(*this, m_style_computer);
request_frame_for_first_recorded_input(*this, m_style_computer);
- StyleEngineFFI::style_engine_record_container_query_input(host(), style_node);
+ StyleEngineFFI::style_engine_set_highlight_observing_elements(host(), to_underlying(pseudo_element), style_nodes);
}
-void StyleEngine::record_flat_tree_descendant_style_input_changes(StyleNodeID style_node, u8 reaction, u8 inherited_style_groups)
+void StyleEngine::record_container_query_input_change(StyleNodeID style_node)
{
- if (style_node == 0 || reaction == 0)
+ if (style_node == 0)
return;
-
flush_deferred_geometry_transaction_before_non_replayable_input(*this, m_style_computer);
- // The relation columns must include every tree delta recorded before this derived action.
- submit_recorded_input();
request_frame_for_first_recorded_input(*this, m_style_computer);
- StyleEngineFFI::style_engine_record_flat_tree_descendant_style_inputs(host(), style_node, reaction, inherited_style_groups);
+ StyleEngineFFI::style_engine_record_container_query_input(host(), style_node);
}
void StyleEngine::record_size_container_query_dependents(StyleNodeID container)
@@ -414,10 +427,10 @@ void StyleEngine::evaluate_size_containers_needing_evaluation_after_layout(Layou
StyleEngineFFI::style_engine_evaluate_size_containers_needing_evaluation_after_layout(host());
}
-Vector<StyleNodeID> StyleEngine::viewport_dependent_style_nodes(Layout::BegunRead const& read)
+Vector<StyleNodeID> StyleEngine::viewport_dependent_style_nodes(Layout::BegunRead const& read, u8 moved_axes)
{
Vector<StyleNodeID> nodes;
- StyleEngineFFI::style_engine_viewport_dependent_nodes(m_render_document->host(), &read, &nodes, [](void* context, u32 node) {
+ StyleEngineFFI::style_engine_viewport_dependent_nodes(m_render_document->host(), &read, moved_axes, &nodes, [](void* context, u32 node) {
static_cast<Vector<StyleNodeID>*>(context)->append(StyleNodeID { node });
});
return nodes;
@@ -435,7 +448,8 @@ void StyleEngine::submit_recorded_input()
Layout::ForcedReadScope read { render_document() };
if (m_style_computer) {
take_in_pending_style_arrivals(m_style_computer->document(), HiddenChildArrivals::MayWait);
- publish_pending_element_features(*this, *m_style_computer);
+ publish_pending_element_features(*this, *m_style_computer, read);
+ publish_withheld_element_features(*this, *m_style_computer, read);
}
StyleEngineFFI::style_engine_submit_staged_input(host());
@@ -450,33 +464,10 @@ void StyleEngine::flush()
StyleEngineFFI::style_engine_flush(m_render_document->host());
}
-bool StyleEngine::take_diagnostic_style_transaction(Layout::BegunRead const& read, StyleNodeID root, Function<void(ReadonlySpan<StyleNodeID>)>&& consume)
-{
- Vector<StyleNodeID> reaction_nodes;
- auto take_reaction_nodes = [&](auto const& reactions) {
- for (auto const& reaction : reactions) {
- // A pseudo-element record is part of its element's reaction.
- if (reaction.pseudo_kind != NumericLimits<u8>::max())
- continue;
- reaction_nodes.append(StyleNodeID { reaction.style_node });
- }
- };
- auto transaction = take_style_transaction(read, root);
- take_reaction_nodes(transaction.reactions);
- // A pass the host would install in waves reports every wave.
- while (StyleEngineFFI::style_engine_has_suspended_style_pass(m_render_document->host(), &read))
- take_reaction_nodes(take_style_transaction(read, root).reactions);
- discard_style_transaction_outputs(read);
- if (!transaction.is_scoped)
- return false;
- consume(reaction_nodes.span());
- return true;
-}
-
-void StyleEngine::discard_style_transaction_outputs(Layout::BegunRead const& read)
+void StyleEngine::discard_style_update_outputs()
{
// The end of the transaction releases the identities no reader can name any more, which are minted again first.
- StyleEngineFFI::style_engine_end_style_transaction(m_render_document->host(), &read, m_style_node_ids);
+ StyleEngineFFI::style_engine_end_style_update(m_render_document->host());
}
namespace {
@@ -536,12 +527,11 @@ Vector<CollectedStyleSheetResourceContext> collect_style_sheet_resource_contexts
}
-// What a style transaction's document computation inputs lend the engine for the call that takes them, which copies
+// What a style update's document computation inputs lend the engine for the call that takes them, which copies
// what it keeps.
struct StyleEngine::LentComputationInputs {
StyleEngineFFI::FfiDocumentStyleComputationInputs inputs {};
String document_base_url;
- Vector<StyleEngineFFI::FfiStyleSheetResourceContextEntry> resource_contexts;
Vector<StyleEngineFFI::FfiCustomFunctionEntry> custom_functions;
};
@@ -552,27 +542,30 @@ void StyleEngine::gather_computation_inputs(LentComputationInputs& lent)
auto& document = m_style_computer->document();
document.publish_animation_keyframes_for_style_update();
lent.document_base_url = document.serialized_base_url();
- auto document_api_base_url = HTML::relevant_settings_object(document).api_base_url().to_string();
+ auto document_api_base_url = HTML::relevant_settings_object(document).api_base_url();
if (!m_style_sheet_resource_contexts.has_value()
|| m_style_sheet_resource_contexts->style_sheet_set_generation != document.style_sheet_set_generation()
|| m_style_sheet_resource_contexts->document_api_base_url != document_api_base_url) {
+ auto contexts = collect_style_sheet_resource_contexts(document, document_api_base_url.to_string());
+ Vector<StyleEngineFFI::FfiStyleSheetResourceContextEntry> entries;
+ entries.ensure_capacity(contexts.size());
+ for (auto const& context : contexts) {
+ entries.unchecked_append({
+ .source_identity = context.source_identity,
+ .base_url = context.base_url.bytes().data(),
+ .base_url_length = context.base_url.bytes().size(),
+ .has_base_url = context.has_base_url,
+ .origin_clean = context.origin_clean,
+ });
+ }
m_style_sheet_resource_contexts = StyleSheetResourceContexts {
- .contexts = collect_style_sheet_resource_contexts(document, document_api_base_url),
+ .contexts = move(contexts),
+ .entries = move(entries),
.style_sheet_set_generation = document.style_sheet_set_generation(),
.document_api_base_url = move(document_api_base_url),
+ .version = ++m_style_sheet_resource_contexts_version,
};
}
- auto const& collected_resource_contexts = m_style_sheet_resource_contexts->contexts;
- lent.resource_contexts.ensure_capacity(collected_resource_contexts.size());
- for (auto const& context : collected_resource_contexts) {
- lent.resource_contexts.unchecked_append({
- .source_identity = context.source_identity,
- .base_url = context.base_url.bytes().data(),
- .base_url_length = context.base_url.bytes().size(),
- .has_base_url = context.has_base_url,
- .origin_clean = context.origin_clean,
- });
- }
auto const viewport_rect = m_style_computer->viewport_rect_for_style_environment();
auto const& media_environment = *m_style_computer->ensure_media_environment_for_style_update();
// Each scope's @function rules, published after the media environment is settled: a media
@@ -638,8 +631,9 @@ void StyleEngine::gather_computation_inputs(LentComputationInputs& lent)
.custom_property_registration_generation = m_style_computer->document().custom_property_registration_generation(),
.document_base_url = reinterpret_cast<StyleEngineFFI::FfiHostHandle>(lent.document_base_url.bytes().data()),
.document_base_url_length = lent.document_base_url.bytes().size(),
- .style_sheet_resource_contexts = reinterpret_cast<StyleEngineFFI::FfiHostHandle>(lent.resource_contexts.data()),
- .style_sheet_resource_context_count = lent.resource_contexts.size(),
+ .style_sheet_resource_contexts = reinterpret_cast<StyleEngineFFI::FfiHostHandle>(m_style_sheet_resource_contexts->entries.data()),
+ .style_sheet_resource_context_count = m_style_sheet_resource_contexts->entries.size(),
+ .style_sheet_resource_contexts_version = m_style_sheet_resource_contexts->version,
.media_feature_values = reinterpret_cast<StyleEngineFFI::FfiHostHandle>(media_environment.values),
.media_feature_value_count = media_environment.value_count,
.media_length_resolution_context = reinterpret_cast<StyleEngineFFI::FfiHostHandle>(media_environment.length_resolution_context),
@@ -662,35 +656,42 @@ void StyleEngine::gather_computation_inputs(LentComputationInputs& lent)
}
}
-StyleEngine::PublishedStyleTransaction StyleEngine::take_style_transaction(Layout::BegunRead const& read, StyleNodeID root)
+static StyleEngine::StyleUpdateTimings style_update_timings(MonotonicTime submission_started_at, MonotonicTime bridge_started_at)
+{
+ return {
+ .submission_microseconds = static_cast<u64>((bridge_started_at - submission_started_at).to_microseconds()),
+ .bridge_microseconds = static_cast<u64>((MonotonicTime::now() - bridge_started_at).to_microseconds()),
+ };
+}
+
+StyleEngine::StyleUpdateTimings StyleEngine::run_style_update(Layout::BegunRead const& read, StyleNodeID root)
{
auto submission_started_at = MonotonicTime::now();
- submit_recorded_input();
LentComputationInputs lent;
+ submit_recorded_input();
gather_computation_inputs(lent);
auto bridge_started_at = MonotonicTime::now();
if (m_style_computer)
publish_font_faces(m_style_computer->document().font_computer());
- auto view = StyleEngineFFI::style_engine_take_style_transaction(m_render_document->host(), &read, root.value(), lent.inputs);
- return publish_style_transaction_view(view, submission_started_at, bridge_started_at);
+ StyleEngineFFI::style_engine_run_style_update(m_render_document->host(), &read, root.value(), lent.inputs);
+ return style_update_timings(submission_started_at, bridge_started_at);
}
-StyleEngine::PublishedStyleTransaction StyleEngine::take_flown_style_transaction(Layout::BegunRead const& read)
+StyleEngine::StyleUpdateTimings StyleEngine::drain_flown_style_update(Layout::BegunRead const& read)
{
auto submission_started_at = MonotonicTime::now();
// What was recorded beside the transaction is queued behind its drain, as the next transaction's input.
submit_recorded_input();
auto bridge_started_at = MonotonicTime::now();
- auto view = StyleEngineFFI::style_engine_take_flown_style_transaction(m_render_document->host(), &read);
+ StyleEngineFFI::style_engine_drain_flown_style_update(m_render_document->host(), &read);
// The transaction's reactions were read inside the style record view epoch its seal opened.
if (m_style_computer)
m_style_computer->end_style_record_view_epoch();
- return publish_style_transaction_view(view, submission_started_at, bridge_started_at);
+ return style_update_timings(submission_started_at, bridge_started_at);
}
void StyleEngine::end_flown_style_drain()
{
- m_style_nodes_with_animations_changed_beside_flown_transaction.clear();
StyleEngineFFI::style_engine_end_flown_style_drain(m_render_document->host());
// Behind the writes made beside the transaction, the children it counted whose siblings changed beside it are
// counted again.
@@ -702,6 +703,16 @@ void StyleEngine::end_flown_style_drain()
m_style_computer->document().font_computer().did_end_flown_style_drain();
}
+void StyleEngine::take_in_fonts_resolved_against_older_tables()
+{
+ if (!m_style_computer)
+ return;
+ // NB: A pass resolves against an older table than the memo's only while the one the engine holds is behind.
+ auto& font_computer = m_style_computer->document().font_computer();
+ if (m_published_font_environment_generation != font_computer.environment_generation())
+ font_computer.take_in_resolutions_against_older_tables();
+}
+
void StyleEngine::restyle_children_reading_sibling_position(DOM::Element& parent)
{
parent.for_each_child_of_type<DOM::Element>([&](DOM::Element& element) {
@@ -712,38 +723,12 @@ void StyleEngine::restyle_children_reading_sibling_position(DOM::Element& parent
});
}
-bool StyleEngine::has_flown_style_transaction() const
+bool StyleEngine::has_flown_style_update() const
{
- return m_style_computer && m_style_computer->document().has_flown_style_transaction();
+ return m_style_computer && m_style_computer->document().has_flown_style_update();
}
-void StyleEngine::note_style_node_arrived_or_retired(StyleNodeID style_node)
-{
- if (has_flown_style_transaction())
- StyleEngineFFI::style_engine_note_style_node_beside_flown_transaction(host(), style_node.value());
-}
-
-void StyleEngine::note_animations_changed(StyleNodeID style_node)
-{
- if (has_flown_style_transaction())
- m_style_nodes_with_animations_changed_beside_flown_transaction.set(style_node);
-}
-
-StyleEngine::PublishedStyleTransaction StyleEngine::publish_style_transaction_view(StyleEngineFFI::FfiStyleTransactionView const& view, MonotonicTime submission_started_at, MonotonicTime bridge_started_at)
-{
- auto bridge_microseconds = (MonotonicTime::now() - bridge_started_at).to_microseconds();
- return {
- .version = { view.transaction_version, view.program_version },
- .reactions = { view.answers, view.count },
- .is_scoped = view.scoped,
- .only_derived_child_reactions = view.only_derived_child_reactions,
- .connected_element_count = view.connected_element_count,
- .submission_microseconds = static_cast<u64>((bridge_started_at - submission_started_at).to_microseconds()),
- .bridge_microseconds = static_cast<u64>(bridge_microseconds),
- };
-}
-
-bool StyleEngine::let_style_transaction_fly(Layout::BegunRead const& read, StyleUpdateInputs const&, StyleNodeID root, Layout::RustFFI::FfiFlightBlocker blocker)
+bool StyleEngine::let_style_update_fly(StyleUpdateInputs const&, StyleNodeID root, Layout::RustFFI::FfiFlightBlocker blocker)
{
if (!m_style_computer)
return false;
@@ -752,11 +737,9 @@ bool StyleEngine::let_style_transaction_fly(Layout::BegunRead const& read, Style
gather_computation_inputs(lent);
publish_font_faces(m_style_computer->document().font_computer());
// The reactions are read inside the style record view epoch the transaction is taken in, which stays open until
- // take_style_transaction() takes them.
+ // run_style_update() takes them.
m_style_computer->begin_style_record_view_epoch();
- // The frame the transaction flies in runs the first round of the update's layout after it.
- m_style_computer->document().seal_first_layout_round(read);
- if (StyleEngineFFI::style_engine_let_style_transaction_fly(m_render_document->host(), root.value(), lent.inputs, blocker))
+ if (StyleEngineFFI::style_engine_let_style_update_fly(m_render_document->host(), root.value(), lent.inputs, blocker))
return true;
m_style_computer->end_style_record_view_epoch();
return false;
@@ -764,7 +747,7 @@ bool StyleEngine::let_style_transaction_fly(Layout::BegunRead const& read, Style
bool StyleEngine::has_pending_transaction(Layout::BegunRead const& read) const
{
- return has_recorded_input() || has_flown_style_transaction() || StyleEngineFFI::style_engine_has_pending_transaction(m_render_document->host(), &read);
+ return has_recorded_input() || has_flown_style_update() || StyleEngineFFI::style_engine_has_pending_transaction(m_render_document->host(), &read);
}
bool StyleEngine::pending_transaction_may_affect_layout_geometry(Layout::BegunRead const& read)
@@ -783,11 +766,11 @@ bool StyleEngine::has_deferred_geometry_transaction(Layout::BegunRead const& rea
return m_geometry_read_deferred_transaction;
}
-bool StyleEngine::defer_pending_transaction_for_geometry_read(Layout::BegunRead const& read)
+void StyleEngine::defer_pending_transaction_for_geometry_read(Layout::BegunRead const& read)
{
submit_recorded_input();
m_geometry_read_deferred_transaction = true;
- return StyleEngineFFI::style_engine_defer_pending_transaction_for_geometry_read(m_render_document->host(), &read);
+ StyleEngineFFI::style_engine_defer_pending_transaction_for_geometry_read(m_render_document->host(), &read);
}
bool StyleEngine::begin_deferred_geometry_transaction_flush(Layout::BegunRead const& read)
@@ -796,30 +779,28 @@ bool StyleEngine::begin_deferred_geometry_transaction_flush(Layout::BegunRead co
return StyleEngineFFI::style_engine_begin_deferred_geometry_transaction_flush(m_render_document->host(), &read);
}
-bool StyleEngine::match_element(Layout::BegunRead const& read, StyleNodeID node, Vector<RuleMatch>& matches, MatchPurpose purpose)
+bool StyleEngine::matched_rules(Layout::BegunRead const& read, StyleNodeID node, Vector<MatchedRule>& matches)
{
// A synchronous match is an observation boundary. Most matching follows a published style
// transaction, but detached-document style reads can arrive directly while mutation facts are
// still staged. Settle those facts before asking the committed arrangement.
if (has_pending_transaction(read))
flush();
- matches.resize(max(m_element_match_capacity, 16u));
+ auto raw_node = node.value();
+ matches.resize(64);
auto match = [&] {
- return StyleEngineFFI::style_engine_match_element(host(), &read, node.value(), matches.data(), matches.size(), purpose == MatchPurpose::Cascade);
+ return StyleEngineFFI::style_engine_matched_rules(host(), &read, &raw_node, 1, matches.data(), matches.size(), true);
};
auto count = match();
- if (count == NumericLimits<size_t>::max())
- return false;
if (count > matches.size()) {
// Nothing was written, so grow and ask again rather than reporting a truncated answer.
- m_element_match_capacity = count * 2;
- matches.resize(m_element_match_capacity);
+ matches.resize(count);
count = match();
- if (count == NumericLimits<size_t>::max() || count > matches.size())
- return false;
+ VERIFY(count <= matches.size());
}
matches.shrink(count);
- return true;
+ // An element that could not be matched is reported with a rule of zero.
+ return !(count == 1 && matches[0].rule == 0);
}
bool StyleEngine::counter(Layout::BegunRead const& read, size_t index, StringView& out_name, u64& out_value) const
@@ -835,29 +816,29 @@ bool StyleEngine::counter(Layout::BegunRead const& read, size_t index, StringVie
// Resolves the children's environments over what the element hands down, and substitutes the element's own values under
// what its animations sampled, laid over what its style resolves to: name the environment the element holds, and the
// one its animation overlay lies over, with what each hands down under the registrations as they are now.
-void StyleEngine::note_element_custom_property_environments(Layout::BegunRead const& read, DOM::Element const& element, CustomPropertyData const& data)
+void StyleEngine::note_element_custom_property_environments(Layout::BegunRead const& read, DOM::Element const& element, CustomPropertyData const& data, IsAnimationOverlay is_animation_overlay)
{
auto note = [&](CustomPropertyData const& environment) {
+ // NB: Many elements of an installation take one environment, which the render side keeps by identity.
+ if (!element.document().style_computer().custom_property_environment_needs_note(environment))
+ return;
auto inheritable = environment.inheritable(read, element.document());
StyleEngineFFI::style_engine_note_custom_property_environment(host(), environment.identity(), environment.rust_store(),
inheritable ? inheritable->identity() : 0, inheritable ? inheritable->rust_store() : nullptr);
};
- if (data.is_animation_overlay_for({ element })) {
+ if (is_animation_overlay == IsAnimationOverlay::Yes) {
if (auto base = data.parent())
note(*base);
}
note(data);
}
-void StyleEngine::set_element_custom_property_data(Layout::BegunRead const& read, DOM::Element const& element, CustomPropertyData const* data)
+void StyleEngine::set_element_custom_property_data(Layout::BegunRead const& read, DOM::Element const& element, CustomPropertyData const* data, IsAnimationOverlay is_animation_overlay)
{
- // A move of the environment the element inherits reads whether this is its animation overlay, and
- // whether what the element's style resolves to declares custom properties of its own.
- bool const is_animation_overlay = data && data->is_animation_overlay_for({ element });
- auto const* base = is_animation_overlay ? data->parent().ptr() : data;
+ auto const* base = is_animation_overlay == IsAnimationOverlay::Yes ? data->parent().ptr() : data;
if (data)
- note_element_custom_property_environments(read, element, *data);
- StyleEngineFFI::style_engine_set_element_custom_property_data(m_render_document->host(), element.style_node_id().value(), data, data ? data->identity() : 0, is_animation_overlay, base && base->declared_count() > 0,
+ note_element_custom_property_environments(read, element, *data, is_animation_overlay);
+ StyleEngineFFI::style_engine_set_element_custom_property_data(m_render_document->host(), element.style_node_id().value(), data, data ? data->identity() : 0, is_animation_overlay == IsAnimationOverlay::Yes,
base ? base->identity() : 0);
}
@@ -876,7 +857,7 @@ void StyleEngine::republish_element_custom_property_environments(Layout::BegunRe
auto element = context.document->style_computer().element_for_style_node(StyleNodeID { style_node });
if (!element)
return;
- context.style_engine.note_element_custom_property_environments(context.read, *element, *static_cast<CustomPropertyData const*>(data));
+ context.style_engine.note_element_custom_property_environments(context.read, *element, *static_cast<CustomPropertyData const*>(data), element->custom_property_data_is_animation_overlay({}) ? IsAnimationOverlay::Yes : IsAnimationOverlay::No);
});
}
diff --git a/Libraries/LibWeb/CSS/StyleEngineBridge.h b/Libraries/LibWeb/CSS/StyleEngineBridge.h
index 37dd15421d0..e5ea4ae4b75 100644
--- a/Libraries/LibWeb/CSS/StyleEngineBridge.h
+++ b/Libraries/LibWeb/CSS/StyleEngineBridge.h
@@ -19,6 +19,9 @@
#include <AK/Vector.h>
#include <LibGC/Cell.h>
#include <LibGC/Ptr.h>
+#include <LibGC/RootVector.h>
+#include <LibGC/Weak.h>
+#include <LibURL/URL.h>
#include <LibWeb/CSS/ParkedRandomBaseValues.h>
#include <LibWeb/CSS/PseudoClass.h>
#include <LibWeb/CSS/StyleEngineIdentifiers.h>
@@ -36,7 +39,7 @@ using Layout::RustFFI::DocumentHost;
// The entries of the table in Rust/src/css/style/boundary.rs, which cbindgen cannot see: a macro expands to them. A
// test there checks each declaration against its row. An AK Span crosses by value as the table's FfiSpan.
extern "C" {
-void style_engine_set_pseudo_element_style_deferred(DocumentHost const*, u8 kind, bool deferred);
+void style_engine_set_highlight_observing_elements(DocumentHost const*, u8 kind, ReadonlySpan<StyleNodeID> nodes);
void style_engine_set_fold_id_and_class_name_case(DocumentHost const*, bool fold);
void style_engine_set_html_element_namespace(DocumentHost const*, StyleAtomID namespace_atom);
void style_engine_mark_relation_only_style_node(DocumentHost const*, StyleNodeID node);
@@ -46,14 +49,12 @@ void style_engine_retire_text_style_nodes(DocumentHost const*, ReadonlySpan<Styl
void style_engine_set_slot_assigned_nodes(DocumentHost const*, StyleNodeID slot, ReadonlySpan<StyleNodeID> assigned);
void style_engine_set_top_layer_elements(DocumentHost const*, ReadonlySpan<StyleNodeID> members);
void style_engine_set_text_is_ascii_whitespace(DocumentHost const*, StyleNodeID node, bool value);
-void style_engine_set_text_is_in_user_agent_shadow_tree(DocumentHost const*, StyleNodeID node, bool value);
-void style_engine_set_text_is_password_input(DocumentHost const*, StyleNodeID node, bool value);
void style_engine_set_node_dom_paint_facts(DocumentHost const*, StyleNodeID node, u8 facts);
void style_engine_set_element_unique_node_id(DocumentHost const*, StyleNodeID node, u64 unique_node_id);
void style_engine_set_element_table_spans(DocumentHost const*, StyleNodeID node, u32 column_span, u32 row_span);
void style_engine_set_element_id_name(DocumentHost const*, StyleNodeID node, StyleAtomID name);
void style_engine_set_shadow_root(DocumentHost const*, StyleNodeID shadow_host, StyleNodeID shadow_root);
-void style_engine_record_environment_change(DocumentHost const*);
+void style_engine_record_environment_change(DocumentHost const*, u8 changes);
void style_engine_record_custom_property_registration_change(DocumentHost const*, StyleAtomID name);
void style_engine_flush(DocumentHost const*);
void style_engine_finish_sheet_rules_replacement(DocumentHost const*, SheetID sheet, u32 declaration_block);
@@ -61,54 +62,54 @@ void style_engine_attach_sheet(DocumentHost const*, SheetID sheet, TreeScopeID t
void style_engine_detach_sheet(DocumentHost const*, SheetID sheet, TreeScopeID tree_scope);
void style_engine_attach_sheet_occurrence(DocumentHost const*, SheetID sheet, TreeScopeID tree_scope, u64 identity, u64 before, bool conditions_hold);
void style_engine_detach_sheet_occurrence(DocumentHost const*, TreeScopeID tree_scope, u64 identity);
-void style_engine_set_sheet_kept_for_reattachment(DocumentHost const*, SheetID sheet, bool kept);
void style_engine_set_sheet_occurrence_conditions(DocumentHost const*, TreeScopeID tree_scope, u64 identity, bool conditions_hold);
void style_engine_set_element_part_exposure(DocumentHost const*, StyleNodeID node, StyleAtomID exposure);
void style_engine_set_element_directionality(DocumentHost const*, StyleNodeID node, StyleAtomID directionality);
void style_engine_set_element_custom_states(DocumentHost const*, StyleNodeID node, ReadonlySpan<StyleAtomID> states);
void style_engine_end_deferred_geometry_transaction_flush(DocumentHost const*);
void style_engine_record_container_query_input(DocumentHost const*, StyleNodeID node);
-void style_engine_note_children_explicitly_inherit(DocumentHost const*, StyleNodeID node, u32 groups);
void style_engine_record_derived_element_style_input(DocumentHost const*, StyleNodeID node, u8 reaction, u8 inherited_style_groups);
void style_engine_record_font_input_changes(DocumentHost const*, ReadonlySpan<u32> family_name_lengths, ReadonlySpan<u16> family_name_units, ReadonlySpan<u64> font_lists);
-void style_engine_record_flat_tree_descendant_style_inputs(DocumentHost const*, StyleNodeID root, u8 reaction, u8 inherited_style_groups);
+void style_engine_fill_loaded_font_faces(DocumentHost const*, ReadonlySpan<u64> fills);
void style_engine_consume_element_style_input(DocumentHost const*, StyleNodeID node);
-void style_engine_note_style_reaction_applied(DocumentHost const*, StyleNodeID node, u8 reaction, u8 inherited_style_groups_changed, u32 changed_non_inherited_style_groups, u32 facts);
void style_engine_set_element_adjustment_facts(DocumentHost const*, StyleNodeID node, u32 facts);
void style_engine_set_element_construction_facts(DocumentHost const*, StyleNodeID node, u32 facts);
void style_engine_set_element_box_kind(DocumentHost const*, StyleNodeID node, u8 box_kind);
void style_engine_set_element_replaced_content_input(DocumentHost const*, StyleNodeID node, u8 kind, u8 present, u32 const* values);
void style_engine_set_element_heading_level(DocumentHost const*, StyleNodeID node, u8 level);
-void style_engine_acknowledge_engine_computed_record(DocumentHost const*, StyleNodeID node);
-void style_engine_record_transition_baseline(DocumentHost const*, StyleNodeID node, u8 pseudo_kind, u64 style_record);
+void style_engine_record_transition_baseline(DocumentHost const*, StyleNodeID node, u8 pseudo_kind, void const* style_record);
void style_engine_release_transition_baselines(DocumentHost const*);
-void style_engine_pin_style_record(DocumentHost const*, u64 style_record);
-void style_engine_unpin_style_record(DocumentHost const*, u64 style_record);
void style_engine_begin_style_record_view_epoch(DocumentHost const*);
void style_engine_end_style_record_view_epoch(DocumentHost const*);
void style_engine_set_tree_scope_uses_document_sheets(DocumentHost const*, TreeScopeID tree_scope);
-void style_engine_set_element_custom_property_names(DocumentHost const*, StyleNodeID node, ReadonlySpan<StyleAtomID> name_atoms, bool uses_unnamed, bool uses_custom_functions);
-void style_engine_set_element_animation_names(DocumentHost const*, StyleNodeID node, ReadonlySpan<StyleAtomID> name_atoms);
-void style_engine_set_element_recomputes_on_environment_move(DocumentHost const*, StyleNodeID node, bool recomputes);
void style_engine_set_element_scroll_state(DocumentHost const*, StyleNodeID node, u8 stuck, u8 snapped, u8 scrollable, u8 scrolled);
void style_engine_set_element_size_container_query_facts(DocumentHost const*, StyleNodeID node, bool is_queried_container, bool depends_on_size_container_query);
void style_engine_note_size_container_needs_evaluation_after_layout(DocumentHost const*, StyleNodeID node);
void style_engine_record_size_container_query_dependents(DocumentHost const*, StyleNodeID container);
void style_engine_evaluate_size_containers_needing_evaluation_after_layout(DocumentHost const*);
-void style_engine_set_element_associated_pseudo_kind(DocumentHost const*, StyleNodeID node, u8 pseudo_kind_plus_one);
+void style_engine_set_element_backing_pseudo_kind(DocumentHost const*, StyleNodeID node, u8 pseudo_kind_plus_one);
void style_engine_set_counter_style_environment_identity(DocumentHost const*, TreeScopeID tree_scope, u64 identity);
-void style_engine_set_held_style_record(DocumentHost const*, StyleNodeID node, u64 style_record);
-void style_engine_set_held_pseudo_style_record(DocumentHost const*, StyleNodeID node, u8 pseudo_kind, u64 style_record);
+void style_engine_set_held_style_record(DocumentHost const*, StyleNodeID node, void const* record);
+void style_engine_set_held_pseudo_style_record(DocumentHost const*, StyleNodeID node, u8 pseudo_kind, u64 style_record, void const* released);
void style_engine_set_element_css_defined_animations(DocumentHost const*, StyleNodeID node, u8 slot, ReadonlySpan<FlatPtr> names, ReadonlySpan<FfiAppliedAnimationDefinition> definitions);
void style_engine_set_tree_scope_root(DocumentHost const*, TreeScopeID tree_scope, StyleNodeID root);
void style_engine_set_sheet_conditions_hold(DocumentHost const*, SheetID sheet, bool conditions_hold);
u32 style_engine_connected_element_count(DocumentHost const*, BegunRead const*);
-bool style_engine_has_suspended_style_pass(DocumentHost const*, BegunRead const*);
+bool style_engine_self_check_is_enabled(DocumentHost const*);
+bool style_engine_custom_property_environment_is_engine_made(DocumentHost const*, BegunRead const*, u64 identity);
bool style_engine_pending_transaction_may_affect_layout_geometry(DocumentHost const*, BegunRead const*);
-bool style_engine_defer_pending_transaction_for_geometry_read(DocumentHost const*, BegunRead const*);
+void style_engine_defer_pending_transaction_for_geometry_read(DocumentHost const*, BegunRead const*);
bool style_engine_begin_deferred_geometry_transaction_flush(DocumentHost const*, BegunRead const*);
bool style_engine_has_deferred_geometry_transaction(DocumentHost const*, BegunRead const*);
-size_t style_engine_match_document(DocumentHost const*, BegunRead const*, StyleNodeID root);
+u64 style_engine_cold_pass(DocumentHost const*, BegunRead const*, StyleNodeID root, bool verify, u32 threads);
+u64 style_engine_cold_pass_report(DocumentHost const*, BegunRead const*, u32 index);
+u64 style_engine_live_report(DocumentHost const*, BegunRead const*, StyleNodeID root, bool verify, u32 index);
+u64 style_engine_style_counter(DocumentHost const*, BegunRead const*, u32 index);
+bool style_engine_reset_style_counters(DocumentHost const*, BegunRead const*);
+bool style_engine_last_pass_is_full(DocumentHost const*, BegunRead const*);
+u32 style_engine_last_pass_size(DocumentHost const*, BegunRead const*, StyleNodeID root, bool changed);
+u32 style_engine_last_pass_element(DocumentHost const*, BegunRead const*, StyleNodeID root, bool changed, u32 index);
+u64 style_engine_animated_style_samples(DocumentHost const*, BegunRead const*, bool rebuilt_every_group, bool reset);
u32 style_engine_layer_index(DocumentHost const*, BegunRead const*, TreeScopeID tree_scope, u32 layer);
u64 style_engine_size_query_container_scan_visits(DocumentHost const*, BegunRead const*, bool reset);
u64 style_engine_ensure_random_base_value(DocumentHost const*, BegunRead const*, StyleNodeID node, ReadonlySpan<u16> name, bool element_shared);
@@ -150,8 +151,11 @@ struct CollectedStyleSheetResourceContext {
// element, so they are collected again only once either has moved on.
struct StyleSheetResourceContexts {
Vector<CollectedStyleSheetResourceContext> contexts;
+ // What the engine is lent of the contexts, which borrows from them.
+ Vector<StyleEngineFFI::FfiStyleSheetResourceContextEntry> entries;
u64 style_sheet_set_generation { 0 };
- String document_api_base_url;
+ ::URL::URL document_api_base_url;
+ u64 version { 0 };
};
// Owns one document's StyleEngine. The engine itself lives entirely on the Rust side: selector
@@ -192,6 +196,8 @@ public:
m_nodes_awaiting_first_style_computation.remove(style_node);
}
[[nodiscard]] bool has_deferred_element_initial_features(StyleNodeID style_node) const { return m_nodes_with_pending_initial_features.contains(style_node); }
+ // Whether any element waits to have its initial features published, or to be prepared for its first style.
+ [[nodiscard]] bool has_elements_awaiting_initial_style_work() const { return !m_nodes_with_pending_initial_features.is_empty() || !m_nodes_awaiting_first_style_computation.is_empty(); }
HashTable<StyleNodeID> take_deferred_element_initial_features();
HashTable<StyleNodeID> take_elements_awaiting_first_style_computation();
@@ -201,24 +207,15 @@ public:
// continuation semantics.
void set_element_inline_style_properties(StyleNodeID node, Parser::ValueParserFFI::DeclarationBlock const*);
void set_element_presentational_hint_properties(StyleNodeID node, StyleEngineFFI::FfiElementDeclarationKind, ReadonlySpan<StyleProperty>);
- struct StyleRecordDelta {
- StyleRecordID old_style_record;
- StyleRecordID new_style_record;
- };
- using StyleRecordView = StyleEngineFFI::FfiStyleRecordView;
- // Publish the immutable input identities of an element or pseudo-element's base style and
- // return its previous and current StyleRecordID assignments. A zero node interns an unassigned
- // record for a style target which is not registered in the engine.
- [[nodiscard]] StyleRecordDelta publish_computed_groups(Layout::BegunRead const& read, StyleNodeID node, u8 pseudo_kind, ReadonlySpan<void const*> payloads, size_t inherited_group_count, u64 custom_property_environment, bool inherited_group_swap_candidate, u64 counter_style_environment_identity, u64 animation_overlay_identity, void const* animated_overlay, ReadonlySpan<void const*> animation_overlay_payloads, void const* computed_longhand_table, void const* custom_property_store);
- [[nodiscard]] StyleRecordDependencyFlag style_record_dependency_flags(Layout::BegunRead const& read, StyleRecordID style_record) const;
- [[nodiscard]] u64 style_record_custom_property_environment(Layout::BegunRead const& read, StyleRecordID style_record) const;
- // The borrowed views are stable while a base record exists or an animation-overlay generation remains assigned or
- // pinned.
- [[nodiscard]] StyleRecordView style_record_view(Layout::BegunRead const& read, StyleRecordID style_record) const;
- // Remove the retained input identities for one pseudo-element kind and return its removal.
- [[nodiscard]] StyleRecordDelta remove_computed_pseudo(Layout::BegunRead const& read, StyleNodeID node, u8 pseudo_kind);
+ // Install the record of a style the host made outside the engine, such as a layout node's, which holds every
+ // computed group. Nothing holds the record until the caller pins it.
+ [[nodiscard]] StyleRecordID install_host_style_record(Layout::BegunRead const& read, ReadonlySpan<void const*> payloads, ComputedValuesFFI::InheritedSetValues inherited, ComputedValuesFFI::ResetBits reset, u64 custom_property_environment, u64 counter_style_environment_identity, void const* source_record, void const* custom_property_store);
+ // The record the engine holds for the host for a record identity, or null for one it does not hold. The engine
+ // holds it while it holds the identity, which a base record or an assigned or pinned animation-overlay generation
+ // keeps; an InstalledStyle holds it longer.
+ [[nodiscard]] void const* host_record(Layout::BegunRead const& read, StyleRecordID style_record) const;
// A sheet the host numbers itself, which the engine adds as it applies the host's writes.
- [[nodiscard]] SheetID add_sheet(u32 object, StyleEngineFFI::FfiCascadeOrigin origin);
+ [[nodiscard]] SheetID add_sheet(StyleEngineFFI::FfiCascadeOrigin origin);
// Ends a replacement of the sheet's rules that style_engine_begin_sheet_rules_replacement() began.
void finish_sheet_rules_replacement(SheetID sheet);
@@ -232,8 +229,7 @@ public:
// Counts the reclaims of this document's atoms, so a cache keyed by atoms can tell when one may have been reused.
[[nodiscard]] u64 atom_generation() const;
// Moves a node's record to the environment its inherited custom-property data was refreshed
- // to; the new record's identity, or zero when nothing moved.
- [[nodiscard]] StyleRecordID republish_record_environment(Layout::BegunRead const&, StyleNodeID, u64 environment, void const* store);
+ // to; the record the host holds for the new one, or null when nothing moved.
// What a read of an element's style, or one of its pseudo-elements', made before the next style update asks of
// the style engine, and the pseudo-element a demand may read.
using RecordDemand = StyleEngineFFI::FfiRecordDemand;
@@ -244,8 +240,8 @@ public:
// Answers a record demand of an element: the record the engine derived from the document as it is now, or zero
// where the read is C++'s.
[[nodiscard]] StyleEngineFFI::FfiRecordDemandAnswer answer_record_demand(Layout::BegunRead const& read, StyleNodeID, RecordDemand);
- // Whether an environment identity is one the engine minted for an environment it resolved.
- [[nodiscard]] static bool is_engine_custom_property_environment(u64 identity) { return (identity & (1ull << 62)) != 0; }
+ // Whether the environment `identity` names is one the engine resolved.
+ [[nodiscard]] bool is_engine_custom_property_environment(Layout::BegunRead const& read, u64 identity) const { return identity && StyleEngineFFI::style_engine_custom_property_environment_is_engine_made(host(), &read, identity); }
// A name both a selector and the DOM produce as text, with no interned identity on either side:
// a language subtag and a `:dir()` keyword. Matched ASCII case-insensitively.
@@ -276,14 +272,46 @@ public:
return StyleEngineFFI::document_host_attribute_is_known_unread(host(), name.value());
}
- // Demand expansion already has every value identity. Check the name before interning the text
- // so attributes nothing reads as text do not pay another string hash.
- void backfill_attribute_value_text_if_required(StyleAtomID name, Utf16String const& value);
+ // Whether the document host knows that no selector tests `:local-link`.
+ bool local_link_is_known_untested() const
+ {
+ return StyleEngineFFI::document_host_local_link_is_known_untested(host());
+ }
+ // What an element arrives with that the host knows nothing reads is withheld from the engine: whether a link is a
+ // local link where no selector tests `:local-link`, and each attribute no selector and no attr() reads. Each
+ // withheld fact notes the element it was withheld from, so that once something may read it, it is published for
+ // those elements alone.
+ struct WithheldAttributeName {
+ Utf16FlyString local_name;
+ Optional<Utf16FlyString> namespace_uri;
+ bool operator==(WithheldAttributeName const&) const = default;
+ };
+ struct WithheldAttributeNameTraits : public DefaultTraits<WithheldAttributeName> {
+ static unsigned hash(WithheldAttributeName const& name) { return pair_int_hash(name.local_name.hash(), name.namespace_uri.has_value() ? name.namespace_uri->hash() : 0); }
+ };
+ // NB: An element's identity may have been retired, or taken by another element, by the time a fact withheld from
+ // it is published: what is published is read from whatever element holds the identity then.
+ using WithheldAttributeCarriers = HashMap<WithheldAttributeName, HashTable<StyleNodeID>, WithheldAttributeNameTraits>;
+ void note_local_link_state_withheld(StyleNodeID node) { m_withheld_local_link_states.set(node); }
+ void note_attribute_withheld(Utf16FlyString const& local_name, Optional<Utf16FlyString> const& namespace_uri, StyleNodeID node)
+ {
+ m_withheld_attribute_carriers.ensure({ local_name, namespace_uri }).set(node);
+ }
+ // What was withheld that something may read now, which is withheld no longer, with the elements it was withheld
+ // from.
+ struct WithheldFeaturesNowRead {
+ HashTable<StyleNodeID> local_link_states;
+ WithheldAttributeCarriers attributes;
+ };
+ WithheldFeaturesNowRead take_withheld_features_now_read(Layout::BegunRead const&);
// The document host stages deltas, which cross to the engine in one batch per style flush, never one write per
// element.
void record_tree_delta(StyleEngineFFI::FfiTreeDelta const&);
- void record_element_arrival(StyleEngineFFI::FfiElementArrival const&, ReadonlySpan<StyleAtomID> custom_states);
+ // Everything an element's selectors test arrives with it, as one row: its custom states, classes, and attributes
+ // as name and value atom pairs, beside the facts the arrival names.
+ void record_element_arrivals(ReadonlySpan<StyleEngineFFI::FfiArrivingElement>);
+ void record_element_arrival(StyleEngineFFI::FfiElementArrival const&, ReadonlySpan<StyleAtomID> custom_states, ReadonlySpan<StyleAtomID> classes, ReadonlySpan<StyleAtomID> attributes);
void record_local_feature_delta(StyleEngineFFI::FfiLocalFeatureDelta const&);
void record_state_delta(StyleEngineFFI::FfiStateDelta const&);
// The hover moves to `target`, or off the document for none, as the events of a mouse move hover it, once the rest
@@ -293,41 +321,32 @@ public:
enum StyleReaction : u8 {
PublishedStyle = 1 << 0,
RecomputeStyle = 1 << 1,
- InheritedStyle = 1 << 2,
- InheritedCustomProperties = 1 << 3,
- RecomputeDescendantStyles = 1 << 4,
- AncestorBecameVisible = 1 << 5,
- PseudoInputsMayHaveChanged = 1 << 6,
- FontInputsChanged = 1 << 7,
- };
- // What applying a style reaction found, reported so the engine derives the children's reactions.
- enum StyleReactionAppliedFact : u32 {
- DidChangeCustomProperties = 1 << 0,
- InvalidationIsNone = 1 << 1,
- NeedsLayoutTreeRebuild = 1 << 2,
- RecomputeDescendants = 1 << 3,
- ChildrenExplicitlyInherit = 1 << 4,
- ShadowChildrenExplicitlyInherit = 1 << 5,
- WasUnstyled = 1 << 6,
- WasDisplayNone = 1 << 7,
- DisplayChanged = 1 << 11,
};
// A style reaction of one element, for the engine to settle where it can. It names what moved,
// not who computes the element's style again.
void record_derived_element_style_input_change(StyleNodeID style_node, u8 reaction, u8 inherited_style_groups = 0);
- void record_flat_tree_descendant_style_input_changes(StyleNodeID style_node, u8 reaction, u8 inherited_style_groups = 0);
+ // The elements the host shows the highlight pseudo-element of the kind in, which style updates
+ // style that pseudo-element of. Those that start or stop showing it are restyled.
+ void set_highlight_observing_elements(PseudoElement, ReadonlySpan<StyleNodeID>);
// What a container query or container-relative length read of the element's containers moved.
void record_container_query_input_change(StyleNodeID style_node);
// Records every element whose style a size query or container-relative unit decided against the container.
void record_size_container_query_dependents(StyleNodeID container);
// Records the dependents of every container a style computation asked about before it had a box.
void evaluate_size_containers_needing_evaluation_after_layout(Layout::BegunRead const& read);
- [[nodiscard]] Vector<StyleNodeID> viewport_dependent_style_nodes(Layout::BegunRead const& read);
+ // The style nodes whose style depends on the axes of the viewport moved_axes names, as DOM::StyleEnvironmentChange bits.
+ [[nodiscard]] Vector<StyleNodeID> viewport_dependent_style_nodes(Layout::BegunRead const& read, u8 moved_axes);
[[nodiscard]] bool has_recorded_input() const;
// Nodes that connected without taking an identity yet count as recorded input: they arrive when the input is
// next submitted.
void note_pending_arrivals(size_t count);
void forget_pending_arrivals() { m_pending_arrival_count = 0; }
+ // The nodes marked as waiting to arrive since the last take-in, which it takes in without walking the marks down
+ // from the document where the list holds every node marked since.
+ void list_arrival(DOM::Node&);
+ void note_unlisted_arrivals() { m_arrivals_unlisted = true; }
+ // The nodes listed, or none where a node was marked that the list does not hold.
+ Optional<GC::RootVector<GC::Ref<DOM::Node>>> take_listed_arrivals();
[[nodiscard]] bool has_pending_arrivals() const { return m_pending_arrival_count > 0; }
// Children that wait to arrive in a display:none subtree may have to arrive now. Nothing is recorded until the
// input is next submitted, so this can be noted while a style update applies its reactions.
@@ -360,7 +379,7 @@ public:
// host knows without reading the render state.
[[nodiscard]] bool may_have_deferred_geometry_transaction() const { return m_geometry_read_deferred_transaction; }
[[nodiscard]] bool pending_transaction_may_affect_layout_geometry(Layout::BegunRead const& read);
- [[nodiscard]] bool defer_pending_transaction_for_geometry_read(Layout::BegunRead const& read);
+ void defer_pending_transaction_for_geometry_read(Layout::BegunRead const& read);
[[nodiscard]] bool begin_deferred_geometry_transaction_flush(Layout::BegunRead const& read);
// Geometry reads establish the before-change style used by CSS transitions. Keep this
// monotonic because an inactive rule or a later inline edit can expose the transition only
@@ -371,45 +390,26 @@ public:
// Submits everything recorded since the last flush as one transaction and normalizes it.
void flush();
- using PublishedStyleDelta = StyleEngineFFI::FfiStyleDelta;
- struct PublishedTransactionVersion {
- u64 transaction;
- u64 program;
- };
- struct PublishedStyleTransaction {
- PublishedTransactionVersion version;
- ReadonlySpan<PublishedStyleDelta> reactions;
- bool is_scoped;
- bool only_derived_child_reactions;
- u32 connected_element_count;
- // Returned to the caller so diagnostic transactions do not charge style-update clocks.
- u64 submission_microseconds;
- u64 bridge_microseconds;
+ struct StyleUpdateTimings {
+ u64 submission_microseconds { 0 };
+ u64 bridge_microseconds { 0 };
};
- // Takes pending inputs. The diagnostic transaction reports reaction nodes and then discards
- // its matching outputs. The style transaction publishes versioned match-answer records. False
- // means the result is broad enough to prefer complete matching scratch.
- // NB: The returned reactions borrow Rust storage until the next mutable engine call or an
- // explicit discard. Consume them synchronously before asking the engine anything else.
- bool take_diagnostic_style_transaction(Layout::BegunRead const& read, StyleNodeID root, Function<void(ReadonlySpan<StyleNodeID>)>&&);
- PublishedStyleTransaction take_style_transaction(Layout::BegunRead const& read, StyleNodeID root);
- // Lets the pending style transaction under root, taken against `inputs`, fly beside the event loop where `blocker` is
- // none, and answers whether it flies. The next style update drains it first, with take_flown_style_transaction().
- [[nodiscard]] bool let_style_transaction_fly(Layout::BegunRead const& read, StyleUpdateInputs const& inputs, StyleNodeID root, Layout::RustFFI::FfiFlightBlocker blocker);
- // Whether a style transaction flew whose reactions no style update has drained yet, which its document knows.
- [[nodiscard]] bool has_flown_style_transaction() const;
- // Takes the style transaction that flew in, waiting for it to land, to drain its reactions against the inputs it
+ // Takes pending inputs, and answers how long that took.
+ StyleUpdateTimings run_style_update(Layout::BegunRead const& read, StyleNodeID root);
+ // Lets the pending style update under root, taken against `inputs`, fly beside the event loop where `blocker` is
+ // none, and answers whether it flies. The next style update drains it first, with drain_flown_style_update().
+ [[nodiscard]] bool let_style_update_fly(StyleUpdateInputs const& inputs, StyleNodeID root, Layout::RustFFI::FfiFlightBlocker blocker);
+ // Whether a style update flew whose reactions have not been drained yet, which its document knows.
+ [[nodiscard]] bool has_flown_style_update() const;
+ // Takes the style update that flew in, waiting for it to land, to drain its reactions against the inputs it
// was sealed with. What was written beside it waits for end_flown_style_drain(): it is the next transaction's.
- PublishedStyleTransaction take_flown_style_transaction(Layout::BegunRead const& read);
+ StyleUpdateTimings drain_flown_style_update(Layout::BegunRead const& read);
void end_flown_style_drain();
- // The transaction that flew knows an element that arrived or was removed beside it as it was sealed: the drain
- // leaves its change, and what inherits from it, to the next transaction.
- void note_style_node_arrived_or_retired(StyleNodeID);
- // The transaction that flew decided which of its rows the host composes from the animations each element had as it
- // was sealed: an element whose animations changed beside it holds them composed from the next transaction on.
- void note_animations_changed(StyleNodeID);
- [[nodiscard]] bool animations_changed_beside_flown_transaction(StyleNodeID style_node) const { return m_style_nodes_with_animations_changed_beside_flown_transaction.contains(style_node); }
+ // Takes in the fonts passes resolved against a table older than the document's. Those of a transaction that flew wait
+ // for the end of its drain, as what was written beside it does; a drain's own later passes publish the newer table
+ // ahead of that.
+ void take_in_fonts_resolved_against_older_tables();
// Has the engine recompute the children of `parent` whose style reads their place among their siblings, where some
// child's does.
void restyle_children_reading_sibling_position(DOM::Element& parent);
@@ -421,26 +421,20 @@ public:
if (parent != 0)
m_parents_whose_children_changed_beside_flown_transaction.set(parent);
}
- void discard_style_transaction_outputs(Layout::BegunRead const& read);
-
- using RuleMatch = StyleEngineFFI::FfiRuleMatch;
+ void discard_style_update_outputs();
- enum class MatchPurpose {
- Exact,
- Cascade,
- };
+ using MatchedRule = StyleEngineFFI::FfiMatchedRule;
- // Every rule that decides for one element, in the order the cascade applies them. Cascade
- // callers may omit rules whose declarations cannot win; exact callers receive the same answer
- // as the document pass. Returns false when matching could not complete.
- bool match_element(Layout::BegunRead const& read, StyleNodeID node, Vector<RuleMatch>&, MatchPurpose);
+ // Every rule that matches one element, user agent rules included, in the order the cascade
+ // applies them. Returns false when matching could not complete.
+ bool matched_rules(Layout::BegunRead const& read, StyleNodeID node, Vector<MatchedRule>&);
// Give the engine the document's @font-face table and cascade memo, when they moved since it was last given them.
void publish_font_faces(FontComputer const&);
// The custom-property environment each element holds is kept here; the element keeps none of its own.
- void set_element_custom_property_data(Layout::BegunRead const& read, DOM::Element const&, CustomPropertyData const*);
- void note_element_custom_property_environments(Layout::BegunRead const& read, DOM::Element const&, CustomPropertyData const&);
+ void set_element_custom_property_data(Layout::BegunRead const& read, DOM::Element const&, CustomPropertyData const*, IsAnimationOverlay);
+ void note_element_custom_property_environments(Layout::BegunRead const& read, DOM::Element const&, CustomPropertyData const&, IsAnimationOverlay);
void republish_element_custom_property_environments(Layout::BegunRead const& read, DOM::Document&);
// Enumerates the engine's counters. Returns false once index is past the last counter.
@@ -456,28 +450,35 @@ public:
private:
struct LentComputationInputs;
void gather_computation_inputs(LentComputationInputs&);
- PublishedStyleTransaction publish_style_transaction_view(StyleEngineFFI::FfiStyleTransactionView const&, MonotonicTime submission_started_at, MonotonicTime bridge_started_at);
void submit_recorded_input();
void publish_attribute_value_texts_if_requirements_moved(Layout::BegunRead const& read);
Optional<StyleSheetResourceContexts> m_style_sheet_resource_contexts;
+ u64 m_style_sheet_resource_contexts_version { 0 };
NonnullRefPtr<Layout::RenderDocument> m_render_document;
- StyleEngineFFI::StyleNodeIdAllocator* m_style_node_ids { nullptr };
u64 m_published_font_environment_generation { 0 };
GC::Ptr<StyleComputer> m_style_computer;
+ // The language the host interned last, which most elements arriving after one share: its tag, its atom, and the
+ // atom generation the atom was interned in.
+ Utf16String m_last_language_text;
+ StyleAtomID m_last_language_atom;
+ u64 m_last_language_atom_generation { 0 };
HashTable<StyleNodeID> m_nodes_with_pending_initial_features;
HashTable<StyleNodeID> m_nodes_awaiting_first_style_computation;
- size_t m_element_match_capacity { 64 };
- HashTable<StyleNodeID> m_style_nodes_with_animations_changed_beside_flown_transaction;
HashTable<StyleNodeID> m_parents_whose_children_changed_beside_flown_transaction;
size_t m_pending_arrival_count { 0 };
+ // NB: The list holds the nodes weakly: a node that left the tree and was collected arrives nowhere.
+ Vector<GC::Weak<DOM::Node>> m_listed_arrivals;
+ bool m_arrivals_unlisted { false };
RelationalArrivalKeys m_relational_arrival_keys;
Optional<u64> m_waiting_children_checked_against_keys_version;
bool m_may_have_waiting_children { false };
+ HashTable<StyleNodeID> m_withheld_local_link_states;
+ WithheldAttributeCarriers m_withheld_attribute_carriers;
bool m_css_transitions_may_observe_style_changes { false };
mutable bool m_geometry_read_deferred_transaction { false };
StyleAtomID m_html_element_namespace;
diff --git a/Libraries/LibWeb/CSS/StyleUpdateInputs.h b/Libraries/LibWeb/CSS/StyleUpdateInputs.h
index 5c91beb5fb0..1e3a1c0f717 100644
--- a/Libraries/LibWeb/CSS/StyleUpdateInputs.h
+++ b/Libraries/LibWeb/CSS/StyleUpdateInputs.h
@@ -23,7 +23,7 @@ class ContainerLayoutUpToDate {
// of the document does this first, ahead of its own style update scopes, as it is a read of the embedding document's.
ContainerLayoutUpToDate lay_out_container_for_style_update(DOM::Document&);
-// Proof that a style update brought up to date and recorded what a document's style transaction is taken against: the
+// Proof that update_style() brought up to date and recorded what a document's style update runs against: the
// layout of its container, its dirty style attributes, its viewport, its media rules, its user-agent and user sheets,
// the sample of an animation-only update, and its counter styles. Only begin_style_update_inputs() makes one, and the
// document takes or lets fly a transaction only with one, so a transaction taken without them does not compile.
@@ -36,8 +36,8 @@ private:
StyleUpdateInputs() = default;
};
-// Brings up to date and records what a style transaction of the document is taken against, as a style update does
-// before it takes one, and the seal of a transaction that flies before it lets it fly. Runs inside a style update of the
+// Brings up to date and records what a style update of the document runs against, as update_style() does
+// before it runs one, and the seal of a transaction that flies before it lets it fly. Runs inside a style update of the
// document (StyleComputer::begin_style_update()). Answers nothing where the document's style is up to date once its
// animations are sampled, so that there is no transaction to take.
Optional<StyleUpdateInputs> begin_style_update_inputs(Layout::BegunRead const&, DOM::Document&, ContainerLayoutUpToDate);
diff --git a/Libraries/LibWeb/CSS/UpdateStyle.cpp b/Libraries/LibWeb/CSS/UpdateStyle.cpp
index b22780e2b87..a8104e6fde6 100644
--- a/Libraries/LibWeb/CSS/UpdateStyle.cpp
+++ b/Libraries/LibWeb/CSS/UpdateStyle.cpp
@@ -4,11 +4,14 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/AnyOf.h>
+#include <AK/Format.h>
#include <AK/HashTable.h>
#include <AK/ScopeGuard.h>
#include <LibWeb/Animations/AnimationEffect.h>
#include <LibWeb/CSS/ComputedValues.h>
#include <LibWeb/CSS/CustomPropertyData.h>
+#include <LibWeb/CSS/MainEffects.h>
#include <LibWeb/CSS/StyleComputer.h>
#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleInvalidation.h>
@@ -28,6 +31,7 @@
#include <LibWeb/HTML/NavigableContainer.h>
#include <LibWeb/Layout/Box.h>
#include <LibWeb/Layout/NodeArena.h>
+#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/Selection/Selection.h>
namespace Web::CSS {
@@ -85,16 +89,16 @@ enum class DocumentWithoutBrowsingContext {
};
// Where a style update's first transaction comes from: what was recorded since the last transaction, whose inputs the
// update brings up to date first, unless the document has no browsing context to render it...
-struct RecordedStyleTransaction {
+struct RecordedStyleUpdate {
DocumentWithoutBrowsingContext document_without_browsing_context { DocumentWithoutBrowsingContext::Skip };
};
// ...or the transaction that flew beside the event loop, whose reactions are drained against the inputs it was sealed
// with.
-struct FlownStyleTransaction {
+struct FlownStyleUpdate {
StyleUpdateInputs sealed_inputs;
};
-template<typename FirstTransaction = RecordedStyleTransaction>
+template<typename FirstTransaction = RecordedStyleUpdate>
static void update_style(Layout::BegunRead const&, DOM::Document&, FirstTransaction = {});
static bool update_style_for_element(Layout::BegunRead const&, DOM::Document&, DOM::AbstractElement const&, StyleUpdateMode);
static bool embedding_document_chain_has_no_pending_style_or_layout_work(DOM::Document const&);
@@ -106,13 +110,14 @@ static void apply_element_style_invalidation_after_style_change(Layout::BegunRea
else if (invalidation.accumulated_visual_contexts() == AccumulatedVisualContextInvalidation::Rebuild)
element.document().schedule_accumulated_visual_context_update(read, element, DOM::Document::AccumulatedVisualContextUpdateScope::Structure);
- if (invalidation.needs_scroll_container_resnap)
+ if (invalidation.needs_scroll_container_resnap) {
element.document().schedule_scroll_container_resnap();
+ }
- // A frame applied the element's record to its box ahead of this install, and marked the relayout the move asks
- // for, which the frame's layout round, or the host's next one, runs.
- bool const needs_relayout = invalidation.needs_relayout()
- && !StyleEngineFFI::style_engine_frame_marked_relayout(element.document().style_computer().style_engine().host(), element.style_node_id().value(), element.style_record_identity().value());
+ // The render state installed the element's record in its box ahead of this install, and marked the relayout, or the
+ // layout tree rebuild, the move asks for, which a frame's layout round, or the host's next one, runs.
+ bool const installed_by_render_state = StyleEngineFFI::style_engine_render_state_installed(element.document().style_computer().style_engine().host(), element.style_node_id().value(), element.style_record_identity().value());
+ bool const needs_relayout = invalidation.needs_relayout() && !installed_by_render_state;
// Only a full layout pass applies viewport propagation again, so a relayout of an element the viewport takes its
// overflow, writing mode, or direction from must not finish as a partial relayout of that element.
@@ -140,10 +145,16 @@ static void apply_element_style_invalidation_after_style_change(Layout::BegunRea
element.set_needs_layout_update(DOM::SetNeedsLayoutReason::StyleChange);
}
}
- if (invalidation.needs_layout_tree_rebuild())
- element.set_needs_layout_tree_rebuild(read, DOM::SetNeedsLayoutTreeUpdateReason::StyleChange, invalidation.layout_tree_rebuild_root());
- else if (invalidation.white_space_collapse_changed)
+ if (invalidation.needs_layout_tree_rebuild()) {
+ if (installed_by_render_state) {
+ // NB: The layout tree build the render state marked is a rendering update's to run.
+ Painting::request_document_repaint(element.document(), InvalidateDisplayList::No);
+ } else {
+ element.set_needs_layout_tree_rebuild(read, DOM::SetNeedsLayoutTreeUpdateReason::StyleChange, invalidation.layout_tree_rebuild_root());
+ }
+ } else if (invalidation.white_space_collapse_changed) {
element.set_needs_layout_tree_update(true, DOM::SetNeedsLayoutTreeUpdateReason::WhitespaceTextBoxChange);
+ }
}
static void apply_document_style_invalidation_after_style_change(DOM::Document& document, RequiredInvalidationAfterStyleChange const& invalidation)
@@ -156,57 +167,6 @@ static void apply_document_style_invalidation_after_style_change(DOM::Document&
document.set_needs_to_record_display_list_keeping_hit_test_display_list();
}
-// What an element's style was before a reaction applied to it.
-struct StyleBeforeReaction {
- explicit StyleBeforeReaction(DOM::Element const& element)
- : was_unstyled(!element.has_style())
- , style_record(element.document().style_computer(), (element.has_children() || element.shadow_root() || is<HTML::HTMLSlotElement>(element)) ? element.style_record_identity() : StyleRecordID {})
- {
- if (auto const* box_values = element.style_group<ComputedValues::BoxValues>())
- display = display_from_ffi_display(box_values->display);
- }
-
- bool was_unstyled { false };
- Optional<Display> display;
- StyleRecordPin style_record;
-};
-
-// Reports what applying a reaction to the element did, from which the engine derives the reactions of its children.
-static void note_style_reaction_applied(Layout::BegunRead const& read, DOM::Element const& element, u8 reaction, StyleBeforeReaction const& before, RequiredInvalidationAfterStyleChange const& invalidation, u32 facts = 0)
-{
- // A counter-style rebuild moves no style, so it is not what the children react to.
- if (invalidation.style_change_is_none())
- facts |= StyleEngine::InvalidationIsNone;
- if (invalidation.style_change_needs_layout_tree_rebuild())
- facts |= StyleEngine::NeedsLayoutTreeRebuild;
- if (invalidation.recompute_descendant_styles)
- facts |= StyleEngine::RecomputeDescendants;
- // NB: Explicit inheritance reads both the base and the composition, which may cover a changed value.
- auto changed_non_inherited_style_groups = [&]() -> u32 {
- if (!before.style_record.style_record() || !element.has_style())
- return NumericLimits<u32>::max();
- auto old_record = element.document().style_computer().style_engine().style_record_view(read, before.style_record.style_record());
- auto new_record = element.installed_style().view();
- if (!old_record.longhand_table || !new_record.longhand_table)
- return NumericLimits<u32>::max();
- auto groups = StyleEngineFFI::style_engine_changed_style_groups(&old_record, &new_record, ComputedValues::inherited_style_group_count, old_record.payload_count);
- return groups | ComputedValuesFFI::rust_computed_longhand_table_non_inherited_inheritance_changes(static_cast<ComputedValuesFFI::ComputedLonghandTable const*>(old_record.longhand_table), static_cast<ComputedValuesFFI::ComputedLonghandTable const*>(new_record.longhand_table));
- }();
- if (element.children_explicitly_inherited_non_inherited_style_groups() & changed_non_inherited_style_groups)
- facts |= StyleEngine::ChildrenExplicitlyInherit;
- if (auto shadow_root = element.shadow_root(); shadow_root && (shadow_root->children_explicitly_inherited_non_inherited_style_groups() & changed_non_inherited_style_groups))
- facts |= StyleEngine::ShadowChildrenExplicitlyInherit;
- if (before.was_unstyled)
- facts |= StyleEngine::WasUnstyled;
- if (before.display.has_value() && before.display->is_none())
- facts |= StyleEngine::WasDisplayNone;
- // A descendant whose style was cleared on entry to display:none can receive a reaction which only updates
- // style-engine bookkeeping, such as a synthetic pseudo-element reaction, and stays unstyled.
- if (auto const* box_values = element.style_group<ComputedValues::BoxValues>(); box_values && before.display.has_value() && *before.display != display_from_ffi_display(box_values->display))
- facts |= StyleEngine::DisplayChanged;
- StyleEngineFFI::style_engine_note_style_reaction_applied(element.document().style_computer().style_engine().host(), element.style_node_id(), reaction, invalidation.inherited_style_groups_changed(), changed_non_inherited_style_groups, facts);
-}
-
// One element's computed style answers for another only while the inputs it was keyed on still mean what they meant. A
// transaction boundary is exactly where they stop doing so: a declaration keyed on by identity may have been edited,
// and a sheet may have come or gone. The engine resolves custom properties against the registrations in force, and an
@@ -219,21 +179,18 @@ static void prepare_for_style_engine_transaction(Layout::BegunRead const& read,
document.style_computer().prepare_for_style_engine_transaction();
}
-// Consume everything recorded since the last transaction boundary, or the transaction computed beside the event loop,
-// and publish its match answers.
-//
-// The reaction batch is a superset by construction: routing may over-approximate, and every subject it yields is
-// checked exactly before publication. What it may not do is under-approximate, so a region that could not be proven
-// narrower covers the whole document rather than guessing at part of it.
-StyleEngineFFI::FfiTakenStyleTransaction StyleEngineFFI::web_css_take_style_transaction(StyleReactionApplication* application, bool flown)
+// Runs the next style update of this update_style() on the document's render state: the writes recorded since the last
+// one, or the update already computed beside the event loop where `flown`. The engine restyles what those writes can
+// reach, and the application takes the rows it answers.
+void StyleEngineFFI::web_css_run_style_update(StyleReactionApplication* application, bool flown)
{
auto const& read = application->read;
auto& document = *application->document;
auto& style_engine = document.style_computer().style_engine();
auto& counters = document.style_invalidation_counters();
- StyleEngine::PublishedStyleTransaction transaction {};
+ StyleEngine::StyleUpdateTimings transaction {};
if (flown) {
- transaction = style_engine.take_flown_style_transaction(read);
+ transaction = style_engine.drain_flown_style_update(read);
} else {
auto transaction_setup_started_at = MonotonicTime::now();
++counters.style_engine_transaction_setups;
@@ -244,22 +201,15 @@ StyleEngineFFI::FfiTakenStyleTransaction StyleEngineFFI::web_css_take_style_tran
auto* root = document.document_element();
if (!root || root->style_node_id() == 0) {
style_engine.flush();
- return {};
+ return;
}
- transaction = style_engine.take_style_transaction(read, root->style_node_id());
+ transaction = style_engine.run_style_update(read, root->style_node_id());
}
counters.style_update_submission_microseconds += transaction.submission_microseconds;
counters.style_update_bridge_microseconds += transaction.bridge_microseconds;
- return {
- .reactions = transaction.reactions.data(),
- .count = transaction.reactions.size(),
- .scoped = transaction.is_scoped,
- .only_derived_child_reactions = transaction.only_derived_child_reactions,
- .connected_element_count = transaction.connected_element_count,
- };
}
-bool StyleEngineFFI::web_css_has_pending_style_transaction(StyleReactionApplication* application)
+bool StyleEngineFFI::web_css_has_pending_style_update(StyleReactionApplication* application)
{
auto& style_engine = application->document->style_computer().style_engine();
style_engine.note_waiting_arrivals_if_keys_moved(application->read);
@@ -285,274 +235,20 @@ void StyleEngineFFI::web_css_begin_style_update_pass(StyleReactionApplication* a
application->document->record_style_stabilization_pass(application->read);
}
-// The swapped groups are the parent's base values; a child of a parent holding animated values inherits the
-// animated ones, which the engine never sees.
-bool StyleEngineFFI::web_css_parent_style_has_animated_values(DOM::Element* element)
+// The host samples an element's animations over the record the engine computed once it is installed, as an animation
+// update samples them over the record an element holds, and publishes what they compose.
+static void sample_animations_for_installed_record(DOM::AbstractElement abstract_element)
{
- auto parent = DOM::AbstractElement { *element }.element_to_inherit_style_from();
- if (!parent.has_value())
- return false;
- auto parent_style = parent->computed_style();
- return parent_style && parent_style->has_animated_values();
-}
-
-// A C++ computation collects an element's animations into the style it computes. For a record the engine derived
-// beneath them, the host samples them over the record once it is installed, as an animation update samples them over
-// the record an element holds, and publishes what they compose.
-static void sample_animations_for_installed_record(Layout::BegunRead const& read, DOM::AbstractElement abstract_element)
-{
- auto style_record = abstract_element.style_record_identity();
- if (!style_record)
+ auto const& style = abstract_element.installed_style();
+ if (!style)
return;
- Animations::AnimationUpdateContext::ElementData element_data { style_record, abstract_element.document().style_computer().reconstruct_computed_properties_for_animation(read, style_record) };
+ Animations::AnimationUpdateContext::ElementData element_data { style, abstract_element.document().style_computer().reconstruct_computed_properties_for_animation(style) };
element_data.base_is_current = true;
- element_data.inherited_style_update_owned_by_reaction = true;
Animations::AnimationUpdateContext context;
context.elements.set(abstract_element, move(element_data));
context.publish();
}
-// The custom-property environment an engine-computed record was published with, against the one the
-// element inherits: the parent's inheritable data, which is the parent's own unless a registration
-// made some of it non-inherited.
-StyleEngineFFI::FfiRecordEnvironment StyleEngineFFI::web_css_engine_record_environment(StyleReactionApplication* application, DOM::Element* element, u64 style_record)
-{
- bool installable = false;
- auto data = element->custom_property_environment_of_engine_record(application->read, StyleRecordID { style_record }, installable);
- if (!installable)
- return FfiRecordEnvironment::Uninstallable;
- RefPtr<CustomPropertyData const> inherited_data;
- if (auto parent = DOM::AbstractElement { *element }.element_to_inherit_style_from(); parent.has_value()) {
- if (auto parent_data = parent->custom_property_data())
- inherited_data = parent_data->inheritable(application->read, *application->document);
- }
- if ((data ? data->identity() : 0) == (inherited_data ? inherited_data->identity() : 0))
- return FfiRecordEnvironment::Inherited;
- return FfiRecordEnvironment::ResolvedOverInherited;
-}
-
-static RefPtr<CustomPropertyData const> custom_property_environment_base(DOM::Element const& element, RefPtr<CustomPropertyData const> data)
-{
- if (data && data->is_animation_overlay_for({ element }))
- return data->parent();
- return data;
-}
-
-// An element that has to compute again is recorded with a recompute reaction alone: its descendants are the move's, or
-// that computation's, to reach.
-static void record_environment_move_recompute(StyleEngine& style_engine, DOM::Element& element)
-{
- style_engine.record_derived_element_style_input_change(element.style_node_id(), StyleEngine::RecomputeStyle);
-}
-
-// The environments a moved element's pseudo-elements held: one that held the element's own takes the
-// moved one, and one that held what the element hands down takes what the moved one hands down. A
-// pseudo-element that resolved its own computes the element again.
-static void move_pseudo_element_environments(Layout::BegunRead const& read, DOM::Document& document, DOM::Element& element, CustomPropertyData const* existing, CustomPropertyData const* existing_inheritable, RefPtr<CustomPropertyData const> const& moved)
-{
- auto moved_inheritable = moved ? moved->inheritable(read, document) : nullptr;
- auto& style_engine = document.style_computer().style_engine();
- for (auto kind = 0; kind < to_underlying(PseudoElement::KnownPseudoElementCount); ++kind) {
- auto pseudo_element = static_cast<PseudoElement>(kind);
- auto pseudo_data = element.custom_property_data(pseudo_element);
- if (!pseudo_data)
- continue;
- if (pseudo_data.ptr() == existing)
- element.set_custom_property_data(pseudo_element, moved);
- else if (pseudo_data.ptr() == existing_inheritable)
- element.set_custom_property_data(pseudo_element, moved_inheritable);
- else
- record_environment_move_recompute(style_engine, element);
- }
-}
-
-// An element's custom properties moved from `old_data` to `new_data`: the style engine moves what the element's
-// descendants inherit, and calls back for what the move leaves the host.
-static void move_custom_property_environment_below(StyleReactionApplication& application, DOM::Element& element, RefPtr<CustomPropertyData const> const& old_data, RefPtr<CustomPropertyData const> const& new_data)
-{
- auto const& read = application.read;
- auto& document = *application.document;
- auto old_inheritable = old_data ? old_data->inheritable(read, document) : nullptr;
- auto new_inheritable = new_data ? new_data->inheritable(read, document) : nullptr;
- auto named = [](CustomPropertyData const* data) -> StyleEngineFFI::FfiNamedEnvironment {
- return { .identity = data ? data->identity() : 0, .store = data ? data->rust_store() : nullptr };
- };
- StyleEngineFFI::FfiEnvironmentMove const moved {
- .old_environment = named(old_data.ptr()),
- .new_environment = named(new_data.ptr()),
- .old_inheritable = old_inheritable ? old_inheritable->identity() : 0,
- .new_inheritable = named(new_inheritable.ptr()),
- .new_inheritable_data = new_inheritable.ptr(),
- .new_inheritable_declares = new_inheritable && new_inheritable->declared_count() > 0,
- };
- StyleEngineFFI::style_engine_move_custom_property_environment(document.style_computer().style_engine().host(), &read, &application, element.style_node_id().value(), moved);
-}
-
-// The element took the moved environment, as did its synthetic pseudo-elements: its element-backed pseudo-elements that
-// held the environment it replaced take the moved one too, and it installs its record republished over the moved one.
-void StyleEngineFFI::web_css_republish_moved_environment(StyleReactionApplication* application, u32 style_node, u64 style_record, u64 replaced, void const* new_inheritable_data)
-{
- auto& style_engine = application->document->style_computer().style_engine();
- auto element = application->document->style_computer().element_for_lane_style_node(style_node);
- // A task running beside a flown transaction can remove the element, whose style node the engine's tree still holds
- // until the tree delta applies, and another element can have taken the style node's slot by then. Nothing is left
- // to republish then.
- if (!element)
- return;
- RefPtr new_inheritable = static_cast<CustomPropertyData const*>(new_inheritable_data);
- for (auto kind = 0; kind < to_underlying(PseudoElement::KnownPseudoElementCount); ++kind) {
- auto pseudo_element = static_cast<PseudoElement>(kind);
- if (is_synthetic_pseudo_element(pseudo_element))
- continue;
- auto pseudo_data = element->custom_property_data(pseudo_element);
- if (!pseudo_data)
- continue;
- if (pseudo_data->identity() == replaced)
- element->set_custom_property_data(pseudo_element, new_inheritable);
- else
- record_environment_move_recompute(style_engine, *element);
- }
- if (style_record != element->style_record_identity().value())
- element->refresh_computed_style({}, StyleRecordID { style_record });
-}
-
-// An element declaring custom properties of its own over the environment it inherits, whose declared values stand
-// because it reads nothing that changed: they are built again over the moved environment, and the move goes on below the
-// element.
-void StyleEngineFFI::web_css_rebuild_custom_property_environment(StyleReactionApplication* application, u32 style_node, void const* new_parent_inheritable_data)
-{
- auto const& read = application->read;
- auto& document = *application->document;
- auto element = document.style_computer().element_for_lane_style_node(style_node);
- // As above, the element can be gone, and its descendants with it.
- if (!element)
- return;
- auto existing_base = custom_property_environment_base(*element, element->custom_property_data({}));
- VERIFY(existing_base && existing_base->declared_count() > 0);
- if (existing_base->parent().ptr() == new_parent_inheritable_data)
- return;
- OrderedHashMap<Utf16FlyString, StyleProperty> own_values;
- size_t declared = 0;
- for (auto const& [name, property] : existing_base->own_values()) {
- if (declared++ >= existing_base->declared_count())
- break;
- own_values.set(name, property);
- }
- RefPtr<CustomPropertyData const> moved = CustomPropertyData::create(move(own_values), static_cast<CustomPropertyData const*>(new_parent_inheritable_data));
- auto existing_inheritable = existing_base->inheritable(read, document);
- move_pseudo_element_environments(read, document, *element, existing_base.ptr(), existing_inheritable.ptr(), moved);
- element->set_custom_property_data({}, moved);
- element->republish_style_record_environment(read);
- if (element->first_element_child() || element->shadow_root() || is<HTML::HTMLSlotElement>(*element))
- move_custom_property_environment_below(*application, *element, existing_base, moved);
-}
-
-static void propagate_custom_property_environment_move(StyleReactionApplication& application, DOM::Element& origin, RefPtr<CustomPropertyData const> old_origin_data)
-{
- // Nothing inherits from an element with nothing below it in the flat tree.
- if (!origin.first_element_child() && !origin.shadow_root() && !is<HTML::HTMLSlotElement>(origin))
- return;
- move_custom_property_environment_below(application, origin, old_origin_data, origin.custom_property_data({}));
-}
-
-void move_custom_property_environment_below_animated_element(Layout::BegunRead const& read, DOM::Element& element, RefPtr<CustomPropertyData const> old_data)
-{
- StyleReactionApplication application { read, element.document() };
- propagate_custom_property_environment_move(application, element, move(old_data));
-}
-
-// Install the record the engine settled for a row, and the pseudo-element records beside it. A C++ computation applied
-// the animation plan it decided beside the record it computed and collected the element's animations, those the plan
-// starts among them, into that record; the host composes them over the record the engine settled once it is installed,
-// and runs the transition step the row owes.
-static RequiredInvalidationAfterStyleChange install_engine_computed_records(Layout::BegunRead const& read, DOM::Element& element, StyleEngineFFI::FfiRecordInstallation const& installation, bool& did_change_custom_properties)
-{
- auto const& reaction = installation.delta;
- // The engine answered its records with what the moves from the records they name damage.
- DOM::Element::EnginePseudoElementRecords pseudo_element_records {};
- DOM::Element::EngineRecordDamages engine_record_damages;
- if (installation.damage != 0)
- engine_record_damages.element = DOM::Element::EngineRecordDamage { StyleRecordID { reaction.old_style_record }, StyleRecordID { reaction.new_style_record }, installation.damage };
- for (size_t kind = 0; kind < array_size(installation.pseudo_records); ++kind) {
- if (!((installation.pseudo_records_present >> kind) & 1))
- continue;
- pseudo_element_records[kind] = StyleRecordID { installation.pseudo_records[kind] };
- if (auto const& damage = installation.pseudo_damages[kind]; damage.damage != 0) {
- engine_record_damages.pseudo_elements[kind] = DOM::Element::EnginePseudoElementRecordDamage {
- .move = { StyleRecordID { damage.old_style_record }, StyleRecordID { damage.new_style_record }, damage.damage },
- .originating_style_record = StyleRecordID { reaction.new_style_record },
- };
- }
- }
- auto& document = element.document();
- auto& style_engine = document.style_computer().style_engine();
- // A C++ computation applies a change of the element's display once the record holds the element's animations and
- // its transition step has run, and refreshes its pseudo-elements after its own style; so does the installation of
- // the record the engine settled, below, from the style the element held.
- auto const old_computed_values = element.computed_style();
- // https://drafts.csswg.org/css-transitions-1/#starting
- // The transition step the row owes compares the record the element moved away from with the one it installs, so
- // the old record has to outlive its replacement until the step has read it.
- // NB: Earlier rows can replace the element's composition after this row was planned. Pin the record it holds now,
- // which is the before-change style for this installation, rather than the row's possibly reclaimed old record.
- bool const owes_a_transition_step = reaction.owes_a_transition_step || element.has_existing_transitions({});
- StyleRecordPin const before_change { document.style_computer(), (owes_a_transition_step || reaction.composed_by_the_host) ? element.style_record_identity() : StyleRecordID {} };
- // The record answers any style input the element owes, as the C++ computation it equals would: nothing is left for
- // a later transaction to plan.
- StyleEngineFFI::style_engine_consume_element_style_input(style_engine.host(), reaction.style_node);
- // The engine decided whether the host composes the row from the animations the element had as its transaction was
- // sealed. The pseudo-element records installed beside the element's can start animations of their own, which their
- // installation composes.
- // NB: Asserted before the record is installed, as the engine saw the element when it sealed the transaction.
- ASSERT(reaction.composed_by_the_host
- || !((element.has_relevant_animations() || element.has_associated_animations())
- && !style_engine.animations_changed_beside_flown_transaction(StyleNodeID { reaction.style_node })));
- auto invalidation = element.apply_engine_computed_style_record(read, StyleRecordID { reaction.new_style_record }, pseudo_element_records, reaction.uses_substitution, reaction.record_reads, reaction.explicitly_inherited_groups, did_change_custom_properties, DOM::Element::DisplayNoneChange::LeftToCaller, &engine_record_damages);
- if (installation.acknowledge)
- StyleEngineFFI::style_engine_acknowledge_engine_computed_record(style_engine.host(), StyleNodeID { reaction.style_node });
- // The engine asks for the element's children only after the host composed the record. Which rows the host composes
- // is the engine's to say, since it settles the pseudo-elements of every other row beside the record, and every
- // element with animations is among them.
- if (reaction.composed_by_the_host) {
- DOM::AbstractElement abstract_element { element };
- if (reaction.owes_an_animation_plan)
- document.style_computer().apply_settled_animation_plan(read, abstract_element);
- // https://drafts.csswg.org/css-transitions-2/#defining-before-change-style
- // Sampling the installed record can keep the epoch's before-change style, and the record the element holds by
- // then is the after-change one. A row that owes the step keeps the record it moved away from first.
- if (!!before_change.style_record() && document.is_in_style_stabilization_epoch())
- document.style_computer().record_transition_stabilization_baseline(abstract_element, before_change.style_record());
- if (element.has_relevant_animations() || element.has_associated_animations())
- sample_animations_for_installed_record(read, abstract_element);
- }
- if (owes_a_transition_step && !!before_change.style_record())
- invalidation |= document.style_computer().run_transition_step_for_installed_record(read, { element }, before_change.style_record());
- if (reaction.composed_by_the_host && !!before_change.style_record()) {
- // NB: Installing an uncomposed base can temporarily change an inherited value covered by an animation.
- // Descendants observe the final composition, and their transition selection also observes its base.
- // Compare both rather than propagating the intermediate base-to-overlay changes.
- auto old_record = style_engine.style_record_view(read, before_change.style_record());
- auto new_record = element.installed_style().view();
- auto changed_inherited_groups = StyleEngineFFI::style_engine_changed_style_groups(&old_record, &new_record, 0, ComputedValues::inherited_style_group_count);
- invalidation.set_inherited_style_groups_changed(static_cast<u8>(changed_inherited_groups & RequiredInvalidationAfterStyleChange::all_inherited_style_groups));
- }
- if (old_computed_values) {
- element.apply_display_none_change(read, DOM::Element::DisplayNoneState::of(*old_computed_values));
- // NB: The descendants of an element that stays display:none have no boxes, so their styles only serve a CSSOM
- // read or the subtree's reveal, both of which materialize them again. Where what they inherit moves, clear
- // them as entering display:none does rather than computing them all again. The SVG elements visible
- // content can reference keep their styles, and take what they inherit from styled ancestors.
- if (old_computed_values->display().is_none() && element.computed_style()->display().is_none()
- && invalidation.inherited_style_groups_changed() != 0 && !did_change_custom_properties
- && !element.has_referenceable_svg_descendant())
- element.clear_computed_styles_from_display_none_descendants(read);
- }
- // The pseudo-elements of a record the host composes inherit the composition, so the engine settles them only now.
- if (reaction.composed_by_the_host)
- invalidation |= element.refresh_pseudo_element_styles_over_composition(read, old_computed_values ? &*old_computed_values : nullptr, did_change_custom_properties);
- return invalidation;
-}
-
// What the style engine reads of an element it applies a reaction to.
static StyleEngineFFI::FfiReactionElement describe_reaction_element(DOM::Document const& document, DOM::Element* element)
{
@@ -565,7 +261,6 @@ static StyleEngineFFI::FfiReactionElement describe_reaction_element(DOM::Documen
.connected = element->is_connected() && &element->document() == &document,
.has_style = element->has_style(),
.style_record = element->style_record_identity().value(),
- .reads_environment = element->style_uses_var_css_function() || element->style_uses_inherit_css_function(),
.display_none = box_values && display_from_ffi_display(box_values->display).is_none(),
};
}
@@ -580,44 +275,139 @@ StyleEngineFFI::FfiReactionElement StyleEngineFFI::web_css_style_inheritance_par
return describe_reaction_element(*application->document, const_cast<DOM::Element*>(element->element_to_inherit_style_from({}).ptr()));
}
-void StyleEngineFFI::web_css_record_derived_element_style_input(StyleReactionApplication* application, u32 style_node, u8 reaction, u8 inherited_style_groups)
+// Swaps in the styles of a style installation, which the render side installed in the layout arena, and performs
+// the main-side effects of the elements whose styles move where they have any. Both are in tree order, and each
+// element's effects follow its swaps, which they name: an element's effects can clear the styles of its descendants,
+// whose swaps come after them.
+void StyleEngineFFI::web_css_install_styles(StyleReactionApplication* application, StyleSwap const* swaps, size_t swap_count, InstalledElementEffects const* effects, size_t effect_count, u32 document_damage)
{
- application->document->style_computer().style_engine().record_derived_element_style_input_change(StyleNodeID { style_node }, reaction, inherited_style_groups);
-}
+ auto const& read = application->read;
+ auto& document = *application->document;
+ auto& style_computer = document.style_computer();
+ auto element_for = [&](u32 style_node) -> DOM::Element* {
+ auto element = style_computer.element_for_style_node(StyleNodeID { style_node });
+ if (!element || !element->is_connected() || &element->document() != &document)
+ return nullptr;
+ return element.ptr();
+ };
+ style_computer.begin_style_installation();
+ ScopeGuard end_style_installation = [&] { style_computer.end_style_installation(); };
+
+ ReadonlySpan<StyleSwap> all_swaps { swaps, swap_count };
+ size_t next_swap = 0;
+ // Swaps in the styles up to the swap `end`, each element's at once.
+ auto swap_in_styles_until = [&](size_t end) {
+ VERIFY(end <= all_swaps.size());
+ while (next_swap < end) {
+ auto const style_node = all_swaps[next_swap].style_node;
+ auto* element = element_for(style_node);
+ auto const held_before = element && element->has_style() ? element->installed_style() : InstalledStyle {};
+ for (; next_swap < end && all_swaps[next_swap].style_node == style_node; ++next_swap) {
+ if (!element)
+ continue;
+ auto const& swap = all_swaps[next_swap];
+ Optional<PseudoElement> pseudo_element;
+ if (swap.slot != NumericLimits<u8>::max())
+ pseudo_element = static_cast<PseudoElement>(swap.slot);
+ // A pseudo-element's transitions may start in a later pass too.
+ if (pseudo_element.has_value()) {
+ DOM::AbstractElement abstract_element { *element, pseudo_element };
+ if (auto const held = abstract_element.installed_style())
+ style_computer.record_transition_baseline_for_later_passes(abstract_element, held);
+ }
+ element->swap_in_style_record(read, pseudo_element, swap.record);
+ }
+ // A later pass of this style update may start the element's transitions, against the style the element held
+ // before the update rather than this record.
+ if (held_before && held_before != element->installed_style())
+ style_computer.record_transition_baseline_for_later_passes({ *element }, held_before);
+ }
+ };
-// Applies a reaction the style engine decided to the element: installs the record it settled, if any, invalidates what
-// the move from the element's old style damages, moves the custom-property environment the element hands down, and
-// reports what the application did.
-void StyleEngineFFI::web_css_apply_style_reaction(StyleReactionApplication* application_pointer, DOM::Element* element_pointer, u8 reaction, StyleEngineFFI::FfiRecordInstallation const* installation)
-{
- auto& application = *application_pointer;
- auto& element = *element_pointer;
- auto const& read = application.read;
- auto old_custom_property_data = element.custom_property_data({});
- StyleBeforeReaction const before { element };
- auto const* previous_inherited_box_values = element.style_group<ComputedValues::InheritedBoxValues>();
- auto const previous_visibility = previous_inherited_box_values
- ? Optional<Visibility> { static_cast<Visibility>(previous_inherited_box_values->visibility) }
- : Optional<Visibility> {};
- bool did_change_custom_properties = false;
- RequiredInvalidationAfterStyleChange invalidation;
- if (installation)
- invalidation = install_engine_computed_records(read, element, *installation, did_change_custom_properties);
-
- auto const* current_inherited_box_values = element.style_group<ComputedValues::InheritedBoxValues>();
- if (previous_visibility.has_value() && current_inherited_box_values
- && *previous_visibility != static_cast<Visibility>(current_inherited_box_values->visibility)) {
- application.document->throttled_animation_visibility_changed();
- }
+ for (auto const& element_effects : ReadonlySpan<InstalledElementEffects> { effects, effect_count }) {
+ swap_in_styles_until(element_effects.swaps_begin);
+ auto* element = element_for(element_effects.style_node);
+ auto const main_effects = static_cast<CSS::MainEffects>(element_effects.effects);
+ // https://drafts.csswg.org/css-transitions-1/#starting
+ // The transition step compares the style the element held before its swaps with the record they install, so the
+ // record it held has to outlive its replacement until the step has read it. A step toward a record that declares
+ // no transitions still ends the ones the element runs. An element running transitions has animations, which the
+ // host composes.
+ bool const owes_a_transition_step = element && element->has_style() && has_flag(main_effects, CSS::MainEffects::Animated)
+ && (has_flag(main_effects, CSS::MainEffects::TransitionStep) || element->has_existing_transitions({}));
+ InstalledStyle const before_change = owes_a_transition_step ? element->installed_style() : InstalledStyle {};
+ // So does that of a pseudo-element.
+ Array<InstalledStyle, DOM::Element::computed_pseudo_elements.size()> pseudo_element_before_change {};
+ if (element) {
+ for (size_t i = 0; i < pseudo_element_before_change.size(); ++i) {
+ auto pseudo_element = DOM::Element::computed_pseudo_elements[i];
+ if ((element_effects.pseudo_element_transition_steps >> to_underlying(pseudo_element)) & 1)
+ pseudo_element_before_change[i] = element->installed_style(pseudo_element);
+ }
+ }
+ // The effects compare the record the element moves to with the one it moves from, which the installation pins
+ // while the host applies it.
+ InstalledStyle const old_style { element_effects.old_record };
+ swap_in_styles_until(element_effects.swaps_end);
- apply_element_style_invalidation_after_style_change(read, element, invalidation);
- application.invalidation |= invalidation;
+ if (!element || !element->has_style() || main_effects == CSS::MainEffects::None)
+ continue;
+ element->note_subtree_style_moved();
+ auto invalidation = decode_style_invalidation(element_effects.damage);
+ // A change of the element's display applies once the record holds the element's animations and its transition
+ // step has run.
+ Optional<DOM::Element::DisplayNoneState> display_none_before;
+ if (has_flag(main_effects, CSS::MainEffects::DisplayNoneFlip) && old_style)
+ display_none_before = DOM::Element::DisplayNoneState::of(*style_computer.computed_style_record_view(old_style), old_style);
+ element->apply_style_main_effects(read, main_effects, static_cast<CSS::LayoutTreeRebuildRoot>(element_effects.rebuild_root), invalidation, old_style);
+ if (has_flag(main_effects, CSS::MainEffects::HostBoxFacts))
+ apply_element_style_invalidation_after_style_change(read, *element, invalidation);
+ // https://drafts.csswg.org/css-transitions-2/#defining-before-change-style
+ // The host composes the element's animations over the record it installed, and its pseudo-elements, which
+ // inherit the composition, after it.
+ if (has_flag(main_effects, CSS::MainEffects::Animated)) {
+ DOM::AbstractElement abstract_element { *element };
+ if (has_flag(main_effects, CSS::MainEffects::AnimationPlan))
+ style_computer.apply_settled_animation_plan(read, abstract_element);
+ if (old_style && document.is_in_style_stabilization_epoch())
+ style_computer.record_transition_stabilization_baseline(abstract_element, old_style);
+ if (style_computer.has_animations_to_compose(abstract_element))
+ sample_animations_for_installed_record(abstract_element);
+ else
+ style_computer.stop_publishing_animated_custom_properties(abstract_element);
+ if (owes_a_transition_step && before_change) {
+ auto step_invalidation = style_computer.run_transition_step_for_installed_record(read, abstract_element, before_change);
+ apply_element_style_invalidation_after_style_change(read, *element, step_invalidation);
+ application->invalidation |= step_invalidation;
+ }
+ }
+ // The host composes the records swapped in for the element's pseudo-elements that owe the plan of their
+ // animations or the transition step, or whose element has animations, as it composes those it settles.
+ if (element_effects.pseudo_elements_composed != 0) {
+ application->invalidation |= element->compose_style_pseudo_element_records(read, element_effects.pseudo_elements_composed, element_effects.pseudo_element_transition_steps, pseudo_element_before_change);
+ }
+ if (display_none_before.has_value()) {
+ element->apply_display_none_change(*display_none_before);
+ // The animations and transitions the change terminated compose no more over the record.
+ if (element->installed_style().view().animated_overlay || element->custom_property_data_is_animation_overlay({}))
+ sample_animations_for_installed_record(DOM::AbstractElement { *element });
+ }
+ // The render side decided whether the element's descendants hold styles while it is hidden.
+ if (has_flag(main_effects, CSS::MainEffects::ClearHiddenDescendants))
+ element->clear_computed_styles_from_display_none_descendants(read);
+ if (has_flag(main_effects, CSS::MainEffects::VisibilityFlip))
+ document.throttled_animation_visibility_changed();
+ }
+ swap_in_styles_until(all_swaps.size());
- // The environment moved: the element's descendants take it here, and the ones that read a moved name are recorded
- // for their own computation. The engine derives no reactions for the move.
- if (did_change_custom_properties)
- propagate_custom_property_environment_move(application, element, old_custom_property_data);
- note_style_reaction_applied(read, element, reaction, before, invalidation);
+ auto invalidation = decode_style_invalidation(document_damage);
+ // The render side noted the boxes whose visual contexts the moves change, which the document updates ahead of
+ // its next paint.
+ if (invalidation.accumulated_visual_contexts() != AccumulatedVisualContextInvalidation::None || invalidation.needs_stacking_context_tree_rebuild())
+ document.set_needs_accumulated_visual_contexts_update(true);
+ if (invalidation.needs_repaint())
+ Painting::request_document_repaint(document, invalidation.invalidates_hit_test_display_list() ? InvalidateDisplayList::PaintCommandsAndHitTestList : InvalidateDisplayList::PaintCommands);
+ application->invalidation |= invalidation;
}
ContainerLayoutUpToDate lay_out_container_for_style_update(DOM::Document& document)
@@ -658,6 +448,11 @@ Optional<StyleUpdateInputs> begin_style_update_inputs(Layout::BegunRead const& r
// transaction only if the resulting inherited-style feedback requires one.
record_non_author_stylesheets(document);
document.style_invalidation_counters().style_update_submission_microseconds += microseconds_since(submission_started_at);
+ // Settle the counter-style registry of each tree scope that may have moved before the engine answers any row: a
+ // record naming a counter style names the registry it was computed against, and a shadow tree can define its own.
+ // None of it depends on layout.
+ if (document.counter_style_scopes_need_update())
+ document.settle_counter_style_scopes(read);
if (document.has_completed_style_update()
&& !document.style_computer().style_engine().has_pending_transaction(read)) {
if (!document.needs_animated_style_update())
@@ -667,21 +462,16 @@ Optional<StyleUpdateInputs> begin_style_update_inputs(Layout::BegunRead const& r
return {};
}
- // Settle each tree scope's counter-style registry before the engine answers any row: a record
- // naming a counter style names the registry it was computed against, and a shadow tree can
- // define its own. None of it depends on layout.
- (void)document.style_scope().counter_style_environment_identity(read);
- document.for_each_shadow_root([&read](DOM::ShadowRoot& shadow_root) {
- (void)shadow_root.style_scope().counter_style_environment_identity(read);
- });
return StyleUpdateInputs {};
}
+static bool document_has_style_work(Layout::BegunRead const&, DOM::Document const&);
+
template<typename FirstTransaction>
static void update_style(Layout::BegunRead const& read, DOM::Document& document, FirstTransaction first_transaction)
{
// NB: The style update of a read with no transaction in flight is compiled without the drain's steps.
- constexpr bool drains_flown_transaction = IsSame<FirstTransaction, FlownStyleTransaction>;
+ constexpr bool drains_flown_transaction = IsSame<FirstTransaction, FlownStyleUpdate>;
auto style_update_started_at = MonotonicTime::now();
auto& timing_counters = document.style_invalidation_counters();
auto const submission_before = timing_counters.style_update_submission_microseconds;
@@ -711,13 +501,28 @@ static void update_style(Layout::BegunRead const& read, DOM::Document& document,
// NOTE: If this is a document hosting <template> contents, style update is unnecessary.
if (document.created_for_appropriate_template_contents())
return;
+
+ // NB: A read of an element's style outside any transaction may have resolved fonts against an older table.
+ document.style_computer().style_engine().take_in_fonts_resolved_against_older_tables();
+ }
+
+ // A document that has no style work returns before anything below begins. Where LIBWEB_STYLE_SELFCHECK is set, it
+ // goes on, and the update must find that it has nothing to do: a source of style work that left no trace for the
+ // check is a missing flag.
+ bool has_no_style_work = false;
+ if constexpr (!drains_flown_transaction) {
+ has_no_style_work = !document_has_style_work(read, document);
+ if (has_no_style_work && !StyleEngineFFI::style_engine_self_check_is_enabled(document.style_computer().style_engine().host()))
+ return;
}
// What publishes by identity below (animations, the elements prepared for style) finds the nodes that connected
// since the last update under the identities they take here.
// NB: What connected beside the transaction that flew is the next transaction's.
- if constexpr (!drains_flown_transaction)
+ if constexpr (!drains_flown_transaction) {
take_in_pending_style_arrivals(document, HiddenChildArrivals::MayWait);
+ document.update_highlight_style_observability();
+ }
StyleUpdateScope style_update_scope { document.style_computer() };
document.begin_style_stabilization_epoch();
@@ -737,6 +542,10 @@ static void update_style(Layout::BegunRead const& read, DOM::Document& document,
}();
if (!inputs.has_value())
return;
+ if (has_no_style_work) {
+ dbgln("Style update found work its document said it had none of");
+ VERIFY_NOT_REACHED();
+ }
// The animations the update ticked are sampled before the transaction is taken, as they are ahead of the seal of
// one that flies: the records it computes inherit their values, and what they feed back joins the transaction.
@@ -744,8 +553,7 @@ static void update_style(Layout::BegunRead const& read, DOM::Document& document,
document.sample_animation_effects_needing_style_update();
// A style flush is a transaction boundary. Everything recorded since the last one crosses into StyleEngine as one
- // flat batch, is normalized there, and is routed into the region its transpose programs reach. A transaction that
- // could not be proven narrower publishes a complete document reaction batch.
+ // batch.
// What was written beside the transaction that flew reaches the engine once the drain of its reactions has ended,
// as the next transaction's input.
ScopeGuard end_flown_style_drain = [&] {
@@ -753,16 +561,13 @@ static void update_style(Layout::BegunRead const& read, DOM::Document& document,
document.style_computer().style_engine().end_flown_style_drain();
};
ScopeGuard discard_style_engine_transaction_outputs = [&] {
- document.style_computer().style_engine().discard_style_transaction_outputs(read);
+ document.style_computer().style_engine().discard_style_update_outputs();
};
StyleReactionApplication application { read, document };
- auto* root = document.document_element();
- auto applied = StyleEngineFFI::style_engine_update_style(document.style_computer().style_engine().host(), &read, &application, drains_flown_transaction, root ? root->style_node_id().value() : 0);
+ auto applied = StyleEngineFFI::style_engine_update_style(document.style_computer().style_engine().host(), &read, &application, drains_flown_transaction);
timing_counters.style_engine_reaction_batch_runs += applied.batch_runs;
timing_counters.style_engine_reaction_elements += applied.reaction_elements;
timing_counters.style_engine_published_reactions += applied.published_reactions;
- timing_counters.style_engine_materialized_gaps += applied.materialized_gaps;
- timing_counters.style_engine_record_deltas_applied += applied.record_deltas_applied;
timing_counters.style_update_pass_guard_hits += applied.pass_guard_hits;
timing_counters.style_update_apply_microseconds += applied.apply_microseconds;
if (!applied.had_reactions)
@@ -773,9 +578,18 @@ static void update_style(Layout::BegunRead const& read, DOM::Document& document,
document.sample_animation_effects_needing_style_update();
if (auto* arena = document.layout_node_arena_if_created())
Layout::RustFFI::render_state_refresh_first_letter_styles(arena->host());
+
+ // NB: Where LIBWEB_STYLE_SELFCHECK is set, what the style engine installed is checked against a cold pass once the
+ // update has settled. What was written beside a transaction that flew, such as the fonts that resolve
+ // differently since, reaches the engine only once its drain has ended, as the next update's input: that
+ // update checks.
+ if (!drains_flown_transaction && StyleEngineFFI::style_engine_self_check_is_enabled(document.style_computer().style_engine().host())) {
+ auto* root = document.document_element();
+ StyleEngineFFI::style_engine_self_check(document.style_computer().style_engine().host(), &read, root ? root->style_node_id().value() : 0);
+ }
}
-// Records what update_style() records before it takes the document's style transaction, and lets the transaction fly
+// Records what update_style() records before it runs the document's style update, and lets the update fly
// beside the event loop where `blocker` is none: the next update_style() takes its reactions in, once it has landed,
// against the inputs this answers.
static Optional<StyleUpdateInputs> let_style_update_fly(Layout::BegunRead const& read, DOM::Document& document, Layout::RustFFI::FfiFlightBlocker blocker)
@@ -800,34 +614,11 @@ static Optional<StyleUpdateInputs> let_style_update_fly(Layout::BegunRead const&
if (!style_computer.style_engine().has_pending_transaction(read))
return {};
prepare_for_style_engine_transaction(read, document);
- if (!style_computer.style_engine().let_style_transaction_fly(read, *inputs, root->style_node_id(), blocker))
+ if (!style_computer.style_engine().let_style_update_fly(*inputs, root->style_node_id(), blocker))
return {};
return inputs;
}
-// A targeted update of one element installs the record the style engine demanded for it, if any, and is reported to
-// the engine the way a reaction pass reports it, so the element's children get the same derived reactions either way.
-StyleEngineFFI::FfiTargetedStyleReaction StyleEngineFFI::web_css_apply_targeted_style_reaction(StyleReactionApplication* application, DOM::Element* element_pointer, StyleEngineFFI::FfiRecordInstallation const* installation, bool descendant_style_recompute_needed)
-{
- auto const& read = application->read;
- auto& element = *element_pointer;
- StyleBeforeReaction const before { element };
- bool did_change_custom_properties = false;
- RequiredInvalidationAfterStyleChange invalidation;
- if (installation)
- invalidation = install_engine_computed_records(read, element, *installation, did_change_custom_properties);
- apply_element_style_invalidation_after_style_change(read, element, invalidation);
- u8 reaction = StyleEngine::PublishedStyle | StyleEngine::RecomputeStyle;
- if (descendant_style_recompute_needed)
- reaction |= StyleEngine::RecomputeDescendantStyles;
- note_style_reaction_applied(read, element, reaction, before, invalidation, did_change_custom_properties ? u32 { StyleEngine::DidChangeCustomProperties } : 0);
- apply_document_style_invalidation_after_style_change(element.document(), invalidation);
- return {
- .descendants_need_recompute = did_change_custom_properties || invalidation.needs_layout_tree_rebuild(),
- .recompute_descendant_styles = invalidation.recompute_descendant_styles,
- };
-}
-
// The answer of the style engine to a read of an element's style.
static bool answer_style_read(DOM::AbstractElement const& abstract_element, StyleEngineFFI::FfiTargetedStyleAnswer answer)
{
@@ -844,18 +635,57 @@ static bool answer_style_read(DOM::AbstractElement const& abstract_element, Styl
VERIFY_NOT_REACHED();
}
-// A targeted style update has nothing to do when every source of style work in the document is settled: A full style
-// update has completed, no style engine transaction or recorded input is pending, no media rule evaluation is queued,
-// and no animated style refresh is due.
-static bool document_has_no_pending_style_work(Layout::BegunRead const& read, DOM::Document const& document)
+// Whether take_in_pending_style_arrivals() may find a subtree to take in: one connected since, or children waiting in a
+// display:none subtree that the keys they were looked at against moved for.
+static bool subtree_arrivals_may_be_due(Layout::BegunRead const& read, DOM::Document const& document)
{
- // A rootless flush drains the journal but preserves element style inputs for the first transaction with a document
- // root — so has_pending_transaction() alone would report a settled engine still owing an element its recomputation.
- return document.has_completed_style_update()
- && !document.style_computer().style_engine().has_pending_transaction(read)
- && !StyleEngineFFI::style_engine_has_deferred_element_style_inputs(document.style_computer().style_engine().host(), &read)
- && !document.needs_media_rule_evaluation()
- && !document.needs_animated_style_update();
+ if (!document.descendant_style_arrival_pending())
+ return false;
+ auto& style_engine = const_cast<DOM::Document&>(document).style_computer().style_engine();
+ return style_engine.has_pending_arrivals()
+ || style_engine.waiting_children_checked_against_keys_version() != style_engine.relational_arrival_keys(read).version;
+}
+
+// Whether anything is unsettled that a read of a style that an element holds has to wait for. That is all the sources
+// of style work in document_has_style_work() but two:
+// - What the host does not know the engine would answer, as this asks the engine instead.
+// - An element awaiting its first style work: on the chain of elements the read inherits through it holds no style,
+// which sends the read to a style update, and elsewhere it has not told the engine anything a held style could read.
+static bool document_has_style_work_a_read_waits_for(Layout::BegunRead const& read, DOM::Document const& document)
+{
+ auto const& style_computer = document.style_computer();
+ auto const& style_engine = style_computer.style_engine();
+ // A rootless flush drains the pending inputs but preserves element style inputs for the first transaction with a
+ // document root, so has_pending_transaction() alone would report a settled engine still owing an element its
+ // recomputation.
+ return !document.has_completed_style_update()
+ || style_engine.has_recorded_input()
+ || style_engine.has_flown_style_update()
+ || subtree_arrivals_may_be_due(read, document)
+ || document.has_dirty_style_attributes()
+ || document.has_unreported_style_attributes_to_report()
+ || document.needs_highlight_style_update()
+ || document.needs_media_rule_evaluation()
+ || document.needs_animated_style_update()
+ || document.counter_style_scopes_need_update()
+ || style_computer.viewport_rect_for_style_environment() != document.viewport_rect()
+ || !non_author_stylesheets_are_recorded(document)
+ || style_engine.has_pending_transaction(read)
+ || StyleEngineFFI::style_engine_has_deferred_element_style_inputs(style_engine.host(), &read);
+}
+
+// Whether anything the document's style depends on may have moved since its last style update. Every source of style
+// work leaves a flag, an entry in a set, or a fact the style engine reports as it is recorded, so the answer takes no
+// walk of the document and no job on its render state: a style update that finds none of them has nothing to do, and
+// returns before it begins.
+static bool document_has_style_work(Layout::BegunRead const& read, DOM::Document const& document)
+{
+ // NB: Writes queued since the last job may have moved what the engine answers of itself, which only a job on the
+ // render state finds out. They are style work as far as this check knows, and the update that follows asks.
+ auto const& style_engine = document.style_computer().style_engine();
+ return !StyleEngineFFI::style_engine_knows_engine_facts(style_engine.host())
+ || style_engine.has_elements_awaiting_initial_style_work()
+ || document_has_style_work_a_read_waits_for(read, document);
}
// Whether every embedding document up the container chain needs no style or layout work — so, bringing the embedding
@@ -870,7 +700,7 @@ static bool embedding_document_chain_has_no_pending_style_or_layout_work(DOM::Do
auto& embedding_document = container->document();
// The embedding document's state is that document's own read.
Layout::ForcedReadScope embedding_read { embedding_document };
- if (!document_has_no_pending_style_work(embedding_read, embedding_document)
+ if (document_has_style_work_a_read_waits_for(embedding_read, embedding_document)
|| !embedding_document.layout_is_up_to_date()
|| !container->has_style())
return false;
@@ -901,7 +731,7 @@ static bool update_style_for_element(Layout::BegunRead const& read, DOM::Documen
if (mode != StyleUpdateMode::Normal
&& !abstract_element.pseudo_element().has_value()
&& abstract_element.element().style_node_id() != 0
- && document_has_no_pending_style_work(read, document)
+ && !document_has_style_work_a_read_waits_for(read, document)
&& embedding_document_chain_has_no_pending_style_or_layout_work(document)) {
StyleReactionApplication application { read, document };
auto answer = StyleEngineFFI::style_engine_read_settled_inheritance_chain(document.style_computer().style_engine().host(), &read, &application, first_element_of_inheritance_chain(abstract_element), static_cast<StyleEngineFFI::FfiStyleUpdateMode>(mode));
@@ -914,6 +744,7 @@ static bool update_style_for_element(Layout::BegunRead const& read, DOM::Documen
auto read_may_need_waiting_children = document.descendant_style_arrival_pending()
&& read_element.has_inclusive_ancestor_with_display_none_ignoring_animations();
take_in_pending_style_arrivals(document, read_may_need_waiting_children ? HiddenChildArrivals::TakeIn : HiddenChildArrivals::MayWait);
+ document.update_highlight_style_observability();
StyleUpdateScope style_update_scope { document.style_computer() };
// Refresh computed properties for an abstract element. An ordinary read first consumes the complete exact
// reaction batch. A reentrant layout read leaves that transaction untouched and walks the flat-tree inheritance
@@ -927,10 +758,10 @@ static bool update_style_for_element(Layout::BegunRead const& read, DOM::Documen
&& !embedding_document_chain_has_no_pending_style_or_layout_work(document)) {
auto& container = *navigable->container();
auto& embedding_document = container.document();
- // The container's style is the embedding document's own read, in which the style transaction that flew for the
+ // The container's style is the embedding document's own read, in which the style update that flew for the
// embedding document lands first.
Layout::ForcedReadScope embedding_read { embedding_document };
- embedding_document.drain_flown_style_transaction(embedding_read);
+ embedding_document.drain_flown_style_update(embedding_read);
update_style_for_element(embedding_read, embedding_document, DOM::AbstractElement { container }, StyleUpdateMode::OnlyIfNeeded);
embedding_document_layout_was_stale = !embedding_document.layout_is_up_to_date();
embedding_document.update_layout(DOM::UpdateLayoutReason::ChildDocumentStyleUpdate);
@@ -962,16 +793,20 @@ static bool update_style_for_element(Layout::BegunRead const& read, DOM::Documen
auto const can_run_regular_style_update = !document.is_running_update_layout()
&& (!document.has_completed_style_update()
|| document.style_computer().style_engine().has_pending_transaction(read));
- if (can_run_regular_style_update) {
- update_style(read, document, RecordedStyleTransaction { DocumentWithoutBrowsingContext::Update });
- ran_regular_style_update = true;
- } else {
+ if (!can_run_regular_style_update)
document.sample_animation_effects_needing_style_update();
- if (!document.is_running_update_layout()
- && document.style_computer().style_engine().has_pending_transaction(read)) {
- update_style(read, document, RecordedStyleTransaction { DocumentWithoutBrowsingContext::Update });
- ran_regular_style_update = true;
- }
+ // NB: A style update stops after a number of passes with what they fed back still pending, as a chain of
+ // custom property animations does that moves one level per pass. The read wants them all.
+ auto const stopped_passes = [&] { return document.style_invalidation_counters().style_update_pass_guard_hits; };
+ auto stopped_before = stopped_passes();
+ bool update = !document.is_running_update_layout()
+ && (can_run_regular_style_update || document.style_computer().style_engine().has_pending_transaction(read));
+ while (update) {
+ update_style(read, document, RecordedStyleUpdate { DocumentWithoutBrowsingContext::Update });
+ ran_regular_style_update = true;
+ update = stopped_passes() != exchange(stopped_before, stopped_passes())
+ && document.style_computer().style_engine().has_pending_transaction(read)
+ && !document.is_at_style_stabilization_bound(read);
}
}
@@ -987,165 +822,31 @@ static bool update_style_for_element(Layout::BegunRead const& read, DOM::Documen
}
if (ran_regular_style_update && mode != StyleUpdateMode::OnlyIfNeeded) {
- auto style_record = abstract_element.style_record_identity();
- if (!!style_record
- && !has_flag(document.style_computer().style_engine().style_record_dependency_flags(read, style_record), StyleRecordDependencyFlag::InDisplayNoneSubtree))
+ auto const& style = abstract_element.installed_style();
+ // NB: An element moved below a display:none element holds the record it had where it stood.
+ if (style && !has_flag(style.dependency_flags(), StyleRecordDependencyFlag::InDisplayNoneSubtree)
+ && !abstract_element.element().has_inclusive_ancestor_with_display_none_ignoring_animations())
return true;
}
StyleReactionApplication application { read, document };
- return answer_style_read(abstract_element, StyleEngineFFI::style_engine_update_style_for_inheritance_chain(document.style_computer().style_engine().host(), &read, &application, first_element_of_inheritance_chain(abstract_element), static_cast<StyleEngineFFI::FfiStyleUpdateMode>(mode), embedding_document_layout_was_stale));
+ auto answer = StyleEngineFFI::style_engine_update_style_for_inheritance_chain(document.style_computer().style_engine().host(), &read, &application, first_element_of_inheritance_chain(abstract_element), static_cast<StyleEngineFFI::FfiStyleUpdateMode>(mode), embedding_document_layout_was_stale);
+ apply_document_style_invalidation_after_style_change(document, application.invalidation);
+ return answer_style_read(abstract_element, answer);
}
}
namespace Web::DOM {
-Document::HighlightStyleObservability& Document::highlight_style_observability(CSS::PseudoElement pseudo_element)
-{
- VERIFY(CSS::is_highlight_pseudo_element(pseudo_element));
- switch (pseudo_element) {
- case CSS::PseudoElement::Selection:
- return m_highlight_style_observability[0];
- case CSS::PseudoElement::SpellingError:
- return m_highlight_style_observability[2];
- default:
- return m_highlight_style_observability[1];
- }
-}
-
-bool Document::highlight_styles_are_observable(CSS::PseudoElement pseudo_element) const
-{
- return const_cast<Document&>(*this).highlight_style_observability(pseudo_element).observable;
-}
-
-void Document::set_needs_highlight_style_update(CSS::PseudoElement pseudo_element)
-{
- highlight_style_observability(pseudo_element).needs_update = true;
-}
-
-static void record_highlight_style_inputs(Document& document, Node& root, Range const* range)
-{
- auto record_element = [&](Node& node) {
- if (auto* element = as_if<Element>(node); element && element->has_style()) {
- document.style_computer().style_engine().record_derived_element_style_input_change(element->style_node_id(),
- CSS::StyleEngine::PseudoInputsMayHaveChanged);
- }
- };
-
- // NB: Ancestors supply inherited highlight styles, and text controls paint through
- // their internal shadow trees. Neither requires visiting unrelated subtrees.
- for (auto* ancestor = root.flat_tree_parent(); ancestor; ancestor = ancestor->flat_tree_parent())
- record_element(*ancestor);
- root.for_each_shadow_including_inclusive_descendant([&](Node& node) {
- if (range && &node.root() == &range->start_container()->root() && !range->intersects_node(node))
- return TraversalDecision::SkipChildrenAndContinue;
- record_element(node);
- return TraversalDecision::Continue;
- });
-}
-
-struct HighlightStyleInput {
- GC::Ref<Node> root;
- GC::Ptr<Range> range;
-};
-
-static GC::ConservativeVector<HighlightStyleInput, 2> selection_style_inputs(Document& document)
-{
- GC::ConservativeVector<HighlightStyleInput, 2> inputs;
- if (auto selection = document.get_selection(); selection && !selection->is_collapsed()) {
- auto range = selection->range();
- inputs.append({ range->common_ancestor_container(), range });
- }
- if (auto* text_control = as_if<HTML::FormAssociatedTextControlElement>(document.focused_area().ptr()); text_control && text_control->selection_start() != text_control->selection_end())
- inputs.append({ *document.focused_area(), nullptr });
- return inputs;
-}
-
-static GC::ConservativeVector<HighlightStyleInput, 2> search_text_style_inputs(Document& document)
-{
- GC::ConservativeVector<HighlightStyleInput, 2> inputs;
- if (auto active_match = document.find_in_page_active_match(); active_match && !active_match->collapsed())
- inputs.append({ active_match->common_ancestor_container(), active_match });
- GC::RootHashTable<Node*> highlighted_roots;
- for (auto const& match : document.find_in_page_highlighted_matches()) {
- if (match->collapsed())
- continue;
- auto root = match->common_ancestor_container();
- if (highlighted_roots.set(root.ptr()) == HashSetResult::InsertedNewEntry)
- inputs.append({ root, nullptr });
- }
- return inputs;
-}
-
-static GC::ConservativeVector<HighlightStyleInput, 2> spelling_error_style_inputs(Document& document)
-{
- GC::ConservativeVector<HighlightStyleInput, 2> inputs;
- if (!document.has_spelling_markers())
- return inputs;
- GC::RootHashTable<Node*> roots;
- document.spelling_markers().for_each_marked_text([&](Text& text, auto) {
- auto* parent = text.parent();
- if (parent && roots.set(parent) == HashSetResult::InsertedNewEntry)
- inputs.append({ *parent, nullptr });
- });
- // A root inside another root's subtree adds nothing, since the outer root's walk visits all of it.
- inputs.remove_all_matching([&](auto const& input) {
- for (auto* ancestor = input.root->parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
- if (roots.contains(ancestor))
- return true;
- }
- return false;
- });
- return inputs;
-}
-
-void Document::update_highlight_style_observability(CSS::PseudoElement pseudo_element)
-{
- // NB: Editing commands temporarily select content to restore its formatting. Style reads
- // during the action must not activate selection styles throughout the document for these
- // intermediate ranges. Observe the final selection after the action, including in input
- // event handlers. Explicit ::selection queries can still compute their style on demand.
- if (pseudo_element == CSS::PseudoElement::Selection && m_running_editing_command_action)
- return;
-
- auto inputs = [&] {
- switch (pseudo_element) {
- case CSS::PseudoElement::Selection:
- return selection_style_inputs(*this);
- case CSS::PseudoElement::SpellingError:
- return spelling_error_style_inputs(*this);
- default:
- return search_text_style_inputs(*this);
- }
- }();
- auto& state = highlight_style_observability(pseudo_element);
- bool observable = !inputs.is_empty();
- if (observable == state.observable && !state.needs_update)
- return;
- state = { .observable = observable, .needs_update = false };
- CSS::StyleEngineFFI::style_engine_set_pseudo_element_style_deferred(style_computer().style_engine().host(), to_underlying(pseudo_element), !observable);
- if (pseudo_element == CSS::PseudoElement::SearchText)
- CSS::StyleEngineFFI::style_engine_set_pseudo_element_style_deferred(style_computer().style_engine().host(), to_underlying(CSS::PseudoElement::SearchTextCurrent), !observable);
- for (auto const& input : inputs)
- record_highlight_style_inputs(*this, input.root, input.range.ptr());
-}
-
-void Document::update_highlight_style_observability()
-{
- update_highlight_style_observability(CSS::PseudoElement::Selection);
- update_highlight_style_observability(CSS::PseudoElement::SearchText);
- update_highlight_style_observability(CSS::PseudoElement::SpellingError);
-}
-
-void Document::drain_style_transaction_that_flew(Layout::BegunRead const& read)
+void Document::drain_style_update_that_flew(Layout::BegunRead const& read)
{
// The animations dirtied beside the transaction are the next style update's, as are the writes made beside it: the
// drain samples those its own reactions create.
auto effects_beside = exchange(m_effects_needing_animated_style_update, {});
bool needed_beside = exchange(m_needs_animated_style_update, false);
bool forced_beside = exchange(m_force_throttled_animation_style_update, false);
- CSS::update_style(read, *this, CSS::FlownStyleTransaction { m_flown_style_update_inputs.release_value() });
+ CSS::update_style(read, *this, CSS::FlownStyleUpdate { m_flown_style_update_inputs.release_value() });
for (auto& effect : effects_beside)
m_effects_needing_animated_style_update.set(effect);
m_needs_animated_style_update |= needed_beside;
@@ -1155,8 +856,7 @@ void Document::drain_style_transaction_that_flew(Layout::BegunRead const& read)
void Document::update_style()
{
Layout::ForcedReadScope read { style_computer().style_engine().render_document() };
- drain_flown_style_transaction(read);
- update_highlight_style_observability();
+ drain_flown_style_update(read);
CSS::update_style(read, *this);
}
@@ -1178,7 +878,7 @@ bool Document::update_style_for_element(AbstractElement const& abstract_element)
bool Document::update_style_for_element(AbstractElement const& abstract_element, StyleUpdateMode mode)
{
Layout::ForcedReadScope read { style_computer().style_engine().render_document() };
- drain_flown_style_transaction(read);
+ drain_flown_style_update(read);
update_highlight_style_observability();
flush_throttled_animation_style_update_for_node(abstract_element.element());
return CSS::update_style_for_element(read, *this, abstract_element, mode);
diff --git a/Libraries/LibWeb/CSS/Zoom.cpp b/Libraries/LibWeb/CSS/Zoom.cpp
index b8e556bc810..29ef20c154b 100644
--- a/Libraries/LibWeb/CSS/Zoom.cpp
+++ b/Libraries/LibWeb/CSS/Zoom.cpp
@@ -42,13 +42,13 @@ CSSPixels unscaled(CSSPixels value, double effective_zoom)
// https://drafts.csswg.org/css-viewport/#effective-zoom
double effective_zoom(DOM::Element const& element)
{
- auto const* inherited_box_values = element.style_group<ComputedValues::InheritedBoxValues>();
- return inherited_box_values ? inherited_box_values->effective_zoom_value() : 1;
+ auto const* inherited_values = element.style_inherited_set_values();
+ return inherited_values ? effective_zoom_of(*inherited_values) : 1;
}
double effective_zoom(Layout::NodeWithStyle const& layout_node)
{
- return layout_node.style_group<ComputedValues::InheritedBoxValues>().effective_zoom_value();
+ return effective_zoom_of(layout_node.inherited_set_values());
}
}
diff --git a/Libraries/LibWeb/DOM/AbstractElement.cpp b/Libraries/LibWeb/DOM/AbstractElement.cpp
index f79db3d2f45..4481a152fb0 100644
--- a/Libraries/LibWeb/DOM/AbstractElement.cpp
+++ b/Libraries/LibWeb/DOM/AbstractElement.cpp
@@ -112,24 +112,6 @@ Optional<AbstractElement> AbstractElement::element_to_inherit_style_from() const
return AbstractElement { const_cast<DOM::Element&>(*element) };
}
-// https://drafts.csswg.org/css-pseudo-4/#highlight-cascade
-// When any supported property is not given a value by the cascade, or given a value of inherit or unset, its
-// specified value is determined by inheritance from the corresponding highlight pseudo-element of its originating
-// element's parent element.
-Optional<AbstractElement> AbstractElement::highlight_inheritance_parent() const
-{
- if (!m_pseudo_element.has_value() || !CSS::is_highlight_pseudo_element(*m_pseudo_element))
- return OptionalNone {};
-
- // An ancestor without a record for this pseudo-element has no declarations for it, so the nearest record is
- // what its own would have inherited anyway.
- for (auto ancestor = m_element->element_to_inherit_style_from({}); ancestor; ancestor = ancestor->element_to_inherit_style_from({})) {
- if (!!ancestor->style_record_identity(*m_pseudo_element))
- return AbstractElement { *ancestor, m_pseudo_element };
- }
- return OptionalNone {};
-}
-
GC::Ptr<Node> AbstractElement::root()
{
if (m_pseudo_element.has_value()) {
@@ -157,9 +139,9 @@ CSS::InstalledStyle const& AbstractElement::installed_style() const
return m_element->installed_style(m_pseudo_element);
}
-void const* AbstractElement::style_record_payloads() const
+void const* AbstractElement::style_record_groups() const
{
- return m_element->style_record_payloads(m_pseudo_element);
+ return m_element->style_record_groups(m_pseudo_element);
}
GC::Ptr<CSS::CSSStyleProperties const> AbstractElement::inline_style() const
@@ -188,9 +170,14 @@ void AbstractElement::set_custom_property_data(RefPtr<CSS::CustomPropertyData co
m_element->set_custom_property_data(m_pseudo_element, move(data));
}
-void AbstractElement::replace_custom_property_data(Badge<CSS::StyleComputer>, RefPtr<CSS::CustomPropertyData const> data)
+void AbstractElement::replace_custom_property_data(Badge<CSS::StyleComputer>, RefPtr<CSS::CustomPropertyData const> data, CSS::IsAnimationOverlay is_animation_overlay)
+{
+ m_element->replace_custom_property_data(m_pseudo_element, move(data), is_animation_overlay);
+}
+
+bool AbstractElement::custom_property_data_is_animation_overlay() const
{
- m_element->replace_custom_property_data(m_pseudo_element, move(data));
+ return m_element->custom_property_data_is_animation_overlay(m_pseudo_element);
}
RefPtr<CSS::StyleValue const> AbstractElement::get_custom_property(Utf16FlyString const& name) const
@@ -198,7 +185,7 @@ RefPtr<CSS::StyleValue const> AbstractElement::get_custom_property(Utf16FlyStrin
auto data = custom_property_data();
if (!data)
return nullptr;
- if (auto const* property = data->get(name))
+ if (auto property = data->get(name); property.has_value())
return property->value;
return nullptr;
}
diff --git a/Libraries/LibWeb/DOM/AbstractElement.h b/Libraries/LibWeb/DOM/AbstractElement.h
index 9edbc80db57..d60d7aa2596 100644
--- a/Libraries/LibWeb/DOM/AbstractElement.h
+++ b/Libraries/LibWeb/DOM/AbstractElement.h
@@ -15,6 +15,9 @@ namespace Web::CSS {
class InstalledStyle;
+template<typename StyleGroup>
+StyleGroup const& style_record_group(void const* record);
+
}
namespace Web::DOM {
@@ -47,29 +50,30 @@ public:
GC::Ptr<Element const> parent_element() const;
Element* flat_tree_parent_element() const;
Optional<AbstractElement> element_to_inherit_style_from() const;
- Optional<AbstractElement> highlight_inheritance_parent() const;
GC::Ptr<Node> root();
[[nodiscard]] CSS::ComputedStyleRecordView computed_style() const;
[[nodiscard]] CSS::StyleRecordID style_record_identity() const;
[[nodiscard]] CSS::InstalledStyle const& installed_style() const;
[[nodiscard]] bool has_style() const { return !!style_record_identity(); }
- [[nodiscard]] void const* style_record_payloads() const;
+ [[nodiscard]] void const* style_record_groups() const;
template<typename StyleGroup>
StyleGroup const* style_group() const
{
- auto const* payloads = static_cast<void const* const*>(style_record_payloads());
- if (!payloads)
+ auto const* groups = style_record_groups();
+ if (!groups)
return nullptr;
- auto const* payload = payloads[StyleGroup::style_group_index];
- VERIFY(payload);
- return static_cast<StyleGroup const*>(payload);
+ return &CSS::style_record_group<StyleGroup>(groups);
}
GC::Ptr<CSS::CSSStyleProperties const> inline_style() const;
void set_custom_property_data(RefPtr<CSS::CustomPropertyData const>);
- void replace_custom_property_data(Badge<CSS::StyleComputer>, RefPtr<CSS::CustomPropertyData const>);
+ void replace_custom_property_data(Badge<CSS::StyleComputer>, RefPtr<CSS::CustomPropertyData const>, CSS::IsAnimationOverlay);
[[nodiscard]] RefPtr<CSS::CustomPropertyData const> custom_property_data() const;
+ // Whether the environment `custom_property_data()` answers is the overlay of what this element's own animations
+ // sample. A child that inherits all of its parent's custom properties holds its parent's overlay itself, which is
+ // not an animation of the child's.
+ [[nodiscard]] bool custom_property_data_is_animation_overlay() const;
RefPtr<CSS::StyleValue const> get_custom_property(Utf16FlyString const& name) const;
Vector<GC::Ref<CSS::CSSAnimation>> const* css_defined_animations() const;
diff --git a/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp b/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp
index 3a33a84c47d..2daf2d5f737 100644
--- a/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp
+++ b/Libraries/LibWeb/DOM/AccessibilityTreeNode.cpp
@@ -612,7 +612,7 @@ void AccessibilityTreeNode::serialize_tree_as_node_data(Vector<WebView::Accessib
auto fg = text_values->color_value();
node_data.color = MUST(String::from_byte_string(fg.to_byte_string_without_alpha()));
- auto bg = background_values ? background_values->background_color_value() : Color::Transparent;
+ auto bg = background_values ? background_values->background_color_value(fg) : Color::Transparent;
if (bg.alpha() > 0)
node_data.background_color = MUST(String::from_byte_string(bg.to_byte_string_without_alpha()));
diff --git a/Libraries/LibWeb/DOM/CharacterData.cpp b/Libraries/LibWeb/DOM/CharacterData.cpp
index 31c6850a25d..9f7492af317 100644
--- a/Libraries/LibWeb/DOM/CharacterData.cpp
+++ b/Libraries/LibWeb/DOM/CharacterData.cpp
@@ -63,15 +63,15 @@ static bool whitespace_text_may_follow(Node const& node)
if (auto const* text = as_if<Text>(*sibling))
return text->data().is_ascii_whitespace();
auto const* element = as_if<Element>(*sibling);
- auto const* box_values = element ? element->style_group<CSS::ComputedValues::BoxValues>() : nullptr;
- if (!box_values)
+ if (!element || !element->has_style())
continue;
- auto display = box_values->display_value();
+ CSS::ComputedStyleRecordView values { element->installed_style() };
+ auto display = values->display();
// The children of a display: contents element continue the boxes before it.
if (display.is_contents())
return true;
- auto is_out_of_flow = box_values->float_value() != CSS::Float::None
- || first_is_one_of(box_values->position_value(), CSS::Positioning::Absolute, CSS::Positioning::Fixed);
+ auto is_out_of_flow = values->float_() != CSS::Float::None
+ || first_is_one_of(values->position(), CSS::Positioning::Absolute, CSS::Positioning::Fixed);
if (!display.is_none() && !is_out_of_flow)
return false;
}
diff --git a/Libraries/LibWeb/DOM/Comment.cpp b/Libraries/LibWeb/DOM/Comment.cpp
index 991eeeaa508..221c348d202 100644
--- a/Libraries/LibWeb/DOM/Comment.cpp
+++ b/Libraries/LibWeb/DOM/Comment.cpp
@@ -12,7 +12,7 @@
namespace Web::DOM {
#if ARCH(X86_64) && !defined(AK_OS_WINDOWS)
-static_assert(sizeof(Comment) == 112);
+static_assert(sizeof(Comment) == 104);
#endif
GC_DEFINE_ALLOCATOR(Comment);
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index da5df620cc6..ee979cf53d0 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -779,6 +779,7 @@ Document::~Document() = default;
void Document::create_style_computer()
{
m_style_computer = GC::Heap::the().allocate<CSS::StyleComputer>(*this);
+ CSS::StyleScope::prepare_user_agent_rules(*this);
// NB: A quirks mode set before the style computer existed told no engine about it.
if (in_quirks_mode())
CSS::StyleEngineFFI::style_engine_set_fold_id_and_class_name_case(m_style_computer->style_engine().host(), true);
@@ -796,6 +797,8 @@ void Document::synchronize_dirty_style_attributes()
// only for the selectors and attr()s of the style engine. Where none reads the attribute, it is
// synchronized as the DOM reads it, which tells the engine then, and the elements left out are
// synchronized at the first style update that something of the engine reads it at.
+ if (m_elements_with_dirty_style_attributes.is_empty() && m_elements_with_unreported_style_attributes.is_empty())
+ return;
auto& style_engine = style_computer().style_engine();
if (style_engine.attribute_is_known_unread(style_engine.intern_attribute_name(HTML::AttributeNames::style, {}))) {
for (auto& element : m_elements_with_dirty_style_attributes)
@@ -813,6 +816,14 @@ void Document::synchronize_dirty_style_attributes()
}
}
+bool Document::has_unreported_style_attributes_to_report() const
+{
+ if (m_elements_with_unreported_style_attributes.is_empty())
+ return false;
+ auto& style_engine = const_cast<Document&>(*this).style_computer().style_engine();
+ return !style_engine.attribute_is_known_unread(style_engine.intern_attribute_name(HTML::AttributeNames::style, {}));
+}
+
Layout::NodeArena& Document::layout_node_arena()
{
// Created on first layout node so documents that never build a layout tree (e.g. temporary
@@ -869,6 +880,8 @@ void Document::reset_style_invalidation_counters(Layout::BegunRead const& read)
{
m_style_invalidation_counters = {};
(void)CSS::StyleEngineFFI::style_engine_size_query_container_scan_visits(style_computer().style_engine().host(), &read, true);
+ (void)CSS::StyleEngineFFI::style_engine_animated_style_samples(style_computer().style_engine().host(), &read, false, true);
+ (void)CSS::StyleEngineFFI::style_engine_animated_style_samples(style_computer().style_engine().host(), &read, true, true);
if (m_layout_node_arena) {
Layout::RustFFI::render_state_scrollable_overflow_recalculation_count(m_layout_node_arena->host(), true);
}
@@ -2243,11 +2256,13 @@ void Document::begin_style_stabilization_epoch()
if (m_style_stabilization_epoch_depth++ != 0)
return;
+ HTML::main_thread_event_loop().defer_microtask_checkpoints();
VERIFY(m_provisional_animation_event_queue.is_empty());
VERIFY(m_animations_created_in_stabilization_epoch.is_empty());
style_computer().begin_transition_stabilization_epoch();
m_style_stabilization_pass_count = 0;
m_style_stabilization_has_style_reactions = false;
+ m_animated_custom_property_changes_in_stabilization_epoch.clear();
++m_style_invalidation_counters.style_stabilization_epochs;
++m_transition_generation;
}
@@ -2278,6 +2293,19 @@ void Document::record_style_stabilization_pass(Layout::BegunRead const& read)
}
}
+u64 Document::note_animated_custom_properties_moved_in_stabilization_epoch(CSS::StyleNodeID style_node)
+{
+ return ++m_animated_custom_property_changes_in_stabilization_epoch.ensure(style_node);
+}
+
+bool Document::is_at_style_stabilization_bound(Layout::BegunRead const& read) const
+{
+ // NB: A style update runs at most this many passes.
+ constexpr u64 passes_of_a_style_update = 9;
+ constexpr u64 ordinary_stabilization_round_limit = 8;
+ return m_style_stabilization_pass_count + passes_of_a_style_update > ordinary_stabilization_round_limit + static_cast<u64>(CSS::StyleEngineFFI::style_engine_connected_element_count(style_computer().style_engine().host(), &read));
+}
+
void Document::end_style_stabilization_epoch()
{
VERIFY(m_style_stabilization_epoch_depth > 0);
@@ -2301,6 +2329,7 @@ void Document::end_style_stabilization_epoch()
}
m_provisional_animation_event_queue.clear();
m_animations_created_in_stabilization_epoch.clear();
+ HTML::main_thread_event_loop().resume_microtask_checkpoints();
}
// Refreshes every structure derived from committed layout results, shared by the partial and
@@ -2362,10 +2391,10 @@ void Document::update_layout_if_needed_for_node(Node const& node, UpdateLayoutRe
if (!node.is_connected())
return;
- // NB: Whether the read finds style or layout pending is asked behind the style transaction that flew, which lands
+ // NB: Whether the read finds style or layout pending is asked behind the style update that flew, which lands
// for the read.
Layout::ForcedReadScope read { style_computer().style_engine().render_document() };
- drain_flown_style_transaction(read);
+ drain_flown_style_update(read);
if (reason != UpdateLayoutReason::HTMLEventLoopRenderingUpdate)
flush_throttled_animation_style_update_for_node(node);
@@ -2409,13 +2438,17 @@ void Document::update_layout_if_needed_for_node(Node const& node, UpdateLayoutRe
&& !may_have_style_query_dependencies) {
if (embedding_document_chain_is_clean()) {
synchronize_dirty_style_attributes();
- if (!style_computer().style_engine().pending_transaction_may_affect_layout_geometry(read)) {
+ auto& style_engine = style_computer().style_engine();
+ // NB: Asking gives the nodes waiting to arrive their identities, whose layout tree update marks can make the
+ // layout stale that was up to date above. An element that holds a mark no build answers, as a child of a
+ // shadow host outside the flat tree does, did not pass the mark of a new child on when the child connected.
+ auto transaction_may_affect_layout_geometry = style_engine.pending_transaction_may_affect_layout_geometry(read);
+ if (!transaction_may_affect_layout_geometry && layout_is_up_to_date()) {
// A later inline transition declaration still needs the pending style as its
// before-change style, even though this geometry read can reuse the current layout.
- if (!style_computer().style_engine().has_pending_transaction(read)
- || style_computer().style_engine().defer_pending_transaction_for_geometry_read(read)) {
- return;
- }
+ if (style_engine.has_pending_transaction(read))
+ style_engine.defer_pending_transaction_for_geometry_read(read);
+ return;
}
}
}
@@ -2555,7 +2588,7 @@ bool Document::layout_is_up_to_date() const
// A frame in flight, or a round that flew and is not paid yet, brings layout the host waits for, which the host
// knows without reading the render state. So does style that flew, which is pending until a read of the document
// drains it: a read of a document it embeds asks here, and lays the document out to drain it.
- if (has_flown_style_transaction() || (m_layout_node_arena && m_layout_node_arena->render_document().waits_for_frame()))
+ if (has_flown_style_update() || (m_layout_node_arena && m_layout_node_arena->render_document().waits_for_frame()))
return false;
// Without an arena there is no layout root either, so there is a tree to build.
if (!m_layout_node_arena)
@@ -2570,7 +2603,7 @@ bool Document::layout_is_known_stale() const
return false;
if (m_reads_layout_as_it_flew)
return false;
- if (has_flown_style_transaction() || (m_layout_node_arena && m_layout_node_arena->render_document().waits_for_frame()))
+ if (has_flown_style_update() || (m_layout_node_arena && m_layout_node_arena->render_document().waits_for_frame()))
return true;
if (!m_layout_node_arena)
return true;
@@ -2604,7 +2637,7 @@ void Document::set_quirks_mode(QuirksMode mode)
for_each_shadow_root([](auto& shadow_root) {
shadow_root.style_scope().invalidate_style_cache();
});
- record_style_environment_change();
+ record_style_environment_change(StyleEnvironmentChange::Everything);
}
void Document::set_needs_mathml_and_svg_user_agent_style_sheets()
@@ -2622,37 +2655,54 @@ void Document::set_needs_mathml_and_svg_user_agent_style_sheets()
});
}
-void Document::invalidate_style_for_viewport_change()
+void Document::record_style_environment_change(StyleEnvironmentChange changes)
{
- bool registered_initial_value_depends_on_viewport_metrics = false;
+ bump_style_environment_version();
+ // NB: An engine created later starts from the environment as it is then.
+ if (auto* style_computer = style_computer_if_created())
+ CSS::StyleEngineFFI::style_engine_record_environment_change(style_computer->style_engine().host(), to_underlying(changes));
+}
+
+void Document::invalidate_style_for_viewport_change(CSSPixelSize previous_viewport_size)
+{
+ Vector<Utf16FlyString> registrations_reading_viewport;
auto invalidate_registered_initial_values = [&](auto& registrations) {
- for (auto& [_, registration] : registrations) {
+ for (auto& [name, registration] : registrations) {
if (!registration.computed_initial_value_depends_on_viewport_metrics)
continue;
registration.computed_initial_value = nullptr;
registration.computed_initial_value_depends_on_viewport_metrics = false;
- registered_initial_value_depends_on_viewport_metrics = true;
+ registrations_reading_viewport.append(name);
}
};
invalidate_registered_initial_values(m_registered_property_set);
invalidate_registered_initial_values(m_cached_registered_properties_from_css_property_rules);
- if (registered_initial_value_depends_on_viewport_metrics) {
+ Layout::ForcedReadScope read { *this };
+ auto& style_engine = style_computer().style_engine();
+
+ if (!registrations_reading_viewport.is_empty()) {
// The custom-property registry holds the initial values just dropped, so the next style
- // update has to publish the recomputed ones before it reads them.
+ // update has to publish the recomputed ones before it reads them. A registered initial value
+ // moving is a change to its registration, which restyles the elements declaring, holding or
+ // substituting its name.
m_rust_custom_property_registry_synced = false;
- // A registered initial value is shared by every element that does not specify the custom
- // property, so its consumers cannot be identified from their computed styles.
- record_style_environment_change();
- return;
+ ++m_custom_property_registration_generation;
+ m_custom_property_environments_need_republishing = true;
+ for (auto const& name : registrations_reading_viewport)
+ CSS::StyleEngineFFI::style_engine_record_custom_property_registration_change(style_engine.host(), style_engine.intern_atom(name));
}
// The viewport is one of the document's published inputs, and the style engine drives a record
// that read it again once it moves, so the readers are rows the engine settles. They are still
// named here: what moved is in none of their winners.
- Layout::ForcedReadScope read { *this };
- auto& style_engine = style_computer().style_engine();
- for (auto style_node : style_engine.viewport_dependent_style_nodes(read)) {
+ auto viewport_size = viewport_rect().size();
+ StyleEnvironmentChange moved_axes {};
+ if (viewport_size.width() != previous_viewport_size.width())
+ moved_axes |= StyleEnvironmentChange::ViewportWidth;
+ if (viewport_size.height() != previous_viewport_size.height())
+ moved_axes |= StyleEnvironmentChange::ViewportHeight;
+ for (auto style_node : style_engine.viewport_dependent_style_nodes(read, to_underlying(moved_axes))) {
auto element = style_computer().element_for_style_node(style_node.value());
if (!element || !element->is_connected() || &element->document() != this)
continue;
@@ -2674,9 +2724,9 @@ void Document::invalidate_style_for_viewport_change()
void Document::sample_animation_effects_needing_style_update()
{
- Layout::ForcedReadScope read { *this };
if (!m_needs_animated_style_update)
return;
+ Layout::ForcedReadScope read { *this };
VERIFY(!m_is_updating_animated_style);
m_is_updating_animated_style = true;
@@ -2808,6 +2858,13 @@ void Document::flush_throttled_animation_style_update_for_node(Node const& node)
if (!animation->effect() || !is<Animations::KeyframeEffect>(*animation->effect()))
continue;
auto& effect = static_cast<Animations::KeyframeEffect&>(*animation->effect());
+ // NB: An effect that changed since it was last sampled, such as one script seeked after an earlier read in
+ // this task, is sampled for the read whether or not it can skip per-frame style updates now: the sample
+ // decides that again, from a layout that may have moved since.
+ if (!m_is_updating_animated_style && m_effects_needing_animated_style_update.contains(effect)) {
+ effect.request_observation_sample();
+ continue;
+ }
if (!effect.can_skip_per_frame_style_update())
continue;
if (m_is_updating_animated_style) {
@@ -3024,7 +3081,7 @@ void Document::set_supported_color_schemes(Optional<Vector<Utf16FlyString>> supp
m_supported_color_schemes = move(supported_color_schemes);
m_supported_color_schemes_are_only = only;
- record_style_environment_change();
+ record_style_environment_change(StyleEnvironmentChange::ColorScheme);
set_needs_media_query_evaluation();
}
@@ -8291,6 +8348,53 @@ void Document::disassociate_with_timeline(GC::Ref<Animations::AnimationTimeline>
m_associated_animation_timelines.remove(timeline);
}
+int Document::compare_elements_in_tree_order_for_composite_order(Element& first, Element& second)
+{
+ // NB: Comparisons cost less than a walk of the document until enough of them have gone by at one version of the
+ // tree, which is more of them the more elements the last walk found.
+ static constexpr u32 minimum_compares_before_tree_positions = 256;
+ auto compares_before_tree_positions = max(minimum_compares_before_tree_positions, m_element_count_at_last_tree_positions_walk / 8);
+
+ auto compare_in_tree = [&] {
+ ++style_invalidation_counters().composite_order_document_position_compares;
+ auto position = first.compare_document_position(second);
+ if (position & Node::DOCUMENT_POSITION_FOLLOWING)
+ return -1;
+ if (position & Node::DOCUMENT_POSITION_PRECEDING)
+ return 1;
+ return 0;
+ };
+
+ if (m_element_tree_positions_dom_tree_version != dom_tree_version()) {
+ m_element_tree_positions_dom_tree_version = dom_tree_version();
+ m_element_tree_positions.clear();
+ m_tree_order_compares_at_dom_tree_version = 0;
+ }
+ if (m_element_tree_positions.is_empty()) {
+ if (++m_tree_order_compares_at_dom_tree_version <= compares_before_tree_positions)
+ return compare_in_tree();
+ u32 position = 0;
+ for_each_in_subtree_of_type<Element>([&](Element const& element) {
+ m_element_tree_positions.set(element.unique_id(), position++);
+ return TraversalDecision::Continue;
+ });
+ m_element_count_at_last_tree_positions_walk = position;
+ }
+
+ // NB: An element of another tree, as of a shadow tree, has no position here.
+ auto first_position = m_element_tree_positions.get(first.unique_id());
+ auto second_position = m_element_tree_positions.get(second.unique_id());
+ if (!first_position.has_value() || !second_position.has_value())
+ return compare_in_tree();
+ return *first_position < *second_position ? -1 : 1;
+}
+
+void Document::keep_element_tree_positions_across_attribute_change(u64 version_before)
+{
+ if (m_element_tree_positions_dom_tree_version == version_before)
+ m_element_tree_positions_dom_tree_version = dom_tree_version();
+}
+
void Document::associate_with_animation(GC::Ref<Animations::Animation> animation)
{
m_associated_animations.set(animation);
@@ -8808,7 +8912,7 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)
if (ancestor->overflow_x() == CSS::Overflow::Visible || ancestor->overflow_y() == CSS::Overflow::Visible)
continue;
if (ancestor->overflow_x() == CSS::Overflow::Clip || ancestor->overflow_y() == CSS::Overflow::Clip) {
- auto const& margin = ancestor->style_group<CSS::ComputedValues::MiscResetValues>().overflow_clip_margin;
+ auto const& margin = ancestor->style_group<CSS::ComputedValues::MiscLayoutValues>().overflow_clip_margin;
if (margin.top.offset != 0 || margin.right.offset != 0 || margin.bottom.offset != 0 || margin.left.offset != 0)
continue;
}
@@ -9380,43 +9484,45 @@ void Document::update_animations_and_send_events(double timestamp)
m_pending_animation_event_queue.clear();
// 6. Perform a stable sort of the animation events in events to dispatch as follows:
- auto sort_events_by_composite_order = [](auto const& a, auto const& b) {
- if (!a.animation->effect())
- return true;
- if (!b.animation->effect())
- return false;
+ auto compare_events_by_composite_order = [](auto const& a, auto const& b) -> int {
+ if (!a.animation->effect() || !b.animation->effect())
+ return static_cast<int>(static_cast<bool>(a.animation->effect())) - static_cast<int>(static_cast<bool>(b.animation->effect()));
auto& a_effect = as<Animations::KeyframeEffect>(*a.animation->effect());
auto& b_effect = as<Animations::KeyframeEffect>(*b.animation->effect());
- return Animations::KeyframeEffect::composite_order(a_effect, b_effect) < 0;
+ return Animations::KeyframeEffect::composite_order(a_effect, b_effect);
};
-
- insertion_sort(events_to_dispatch, [&](auto const& a, auto const& b) {
+ auto compare_events = [&](auto const& a, auto const& b) -> int {
// Sort the events by their scheduled event time such that events that were scheduled to occur earlier, sort
// before events scheduled to occur later and events whose scheduled event time is unresolved sort before events
// with a resolved scheduled event time.
//
// Within events with equal scheduled event times, sort by their composite order.
- if (b.scheduled_event_time.has_value()) {
- if (!a.scheduled_event_time.has_value())
- return true;
-
- auto a_time = a.scheduled_event_time.value();
- auto b_time = b.scheduled_event_time.value();
- if (a_time == b_time)
- return sort_events_by_composite_order(a, b);
-
- return a.scheduled_event_time.value() < b.scheduled_event_time.value();
- }
-
- if (a.scheduled_event_time.has_value())
- return false;
+ if (a.scheduled_event_time.has_value() != b.scheduled_event_time.has_value())
+ return a.scheduled_event_time.has_value() ? 1 : -1;
+ if (a.scheduled_event_time != b.scheduled_event_time)
+ return a.scheduled_event_time.value() < b.scheduled_event_time.value() ? -1 : 1;
+ return compare_events_by_composite_order(a, b);
+ };
- return sort_events_by_composite_order(a, b);
+ // NB: The events of a frame come in the unspecified order of the document's animations, so sorting them is not
+ // close to a no-op. Their positions in the queue keep the sort stable.
+ Vector<u32> event_order;
+ event_order.ensure_capacity(events_to_dispatch.size());
+ for (u32 index = 0; index < events_to_dispatch.size(); ++index)
+ event_order.unchecked_append(index);
+ quick_sort(event_order, [&](u32 a, u32 b) {
+ if (auto order = compare_events(events_to_dispatch[a], events_to_dispatch[b]); order != 0)
+ return order < 0;
+ return a < b;
});
+ GC::ConservativeVector<PendingAnimationEvent> sorted_events;
+ sorted_events.ensure_capacity(events_to_dispatch.size());
+ for (auto index : event_order)
+ sorted_events.unchecked_append(events_to_dispatch[index]);
// 7. Dispatch each of the events in events to dispatch at their corresponding target using the order established in
// the previous step.
- for (auto const& event : events_to_dispatch)
+ for (auto const& event : sorted_events)
event.target->dispatch_event(event.event);
// AD-HOC: Nothing else re-requests a rendering update while time-driven animations are running, since
@@ -10296,21 +10402,43 @@ void Document::register_shadow_root(Badge<DOM::ShadowRoot>, DOM::ShadowRoot& sha
{
m_shadow_roots.append(shadow_root);
note_style_sheet_set_change();
+ // A new root settles and publishes its counter style registry in the next style update.
+ note_counter_style_scope_to_settle(shadow_root);
+}
+
+void Document::note_counter_style_scope_to_settle(ShadowRoot& shadow_root)
+{
+ m_counter_style_scopes_need_update = true;
+ if (!m_shadow_roots_with_counter_styles_to_settle.contains(shadow_root))
+ m_shadow_roots_with_counter_styles_to_settle.append(shadow_root);
+}
+
+// Settles the counter style registry of the document's style scope and of each shadow root noted since the last style
+// update, publishing each scope's registry where it, or the scope its names pass on to, changed.
+void Document::settle_counter_style_scopes(Layout::BegunRead const& read)
+{
+ (void)style_scope().counter_style_environment_identity(read);
+ while (auto* shadow_root = m_shadow_roots_with_counter_styles_to_settle.first()) {
+ m_shadow_roots_with_counter_styles_to_settle.remove(*shadow_root);
+ (void)shadow_root->style_scope().counter_style_environment_identity(read);
+ }
+ m_counter_style_scopes_need_update = false;
}
void Document::unregister_shadow_root(Badge<DOM::ShadowRoot>, DOM::ShadowRoot& shadow_root)
{
m_shadow_roots.remove(shadow_root);
+ m_shadow_roots_with_counter_styles_to_settle.remove(shadow_root);
note_style_sheet_set_change();
// The style engine names the keyframe sets of the root's `@keyframes` by pointer. The root may be leaving from a
// garbage collection's finalizer, which must not reach into the engine, so its row is given up before the next
- // style transaction, and the sets stay alive until then.
+ // style update, and the sets stay alive until then.
if (auto departed = shadow_root.style_scope().take_published_animation_keyframes(); departed.has_value())
m_departed_animation_keyframes.append(departed.release_value());
}
// Resolving an animation's `@keyframes` is a lookup in what each style scope published to the style engine, which a
-// scope does whenever its rule cache is built. So before a style transaction, the rows of the shadow roots that left
+// scope does whenever its rule cache is built. So before a style update, the rows of the shadow roots that left
// are given up and every scope's rule cache is built. A rule cache is invalidated only with a change of the style sheet
// set, as is a shadow root's departure, so without one since the last transaction every row is current.
void Document::publish_animation_keyframes_for_style_update()
@@ -10321,7 +10449,7 @@ void Document::publish_animation_keyframes_for_style_update()
m_animation_keyframes_published_generation = m_style_sheet_set_generation;
auto* host = style_computer().style_engine().host();
for (auto const& departed : m_departed_animation_keyframes) {
- CSS::StyleEngineFFI::style_engine_set_tree_scope_animation_keyframes(host, departed.tree_scope.value(), departed.shadow_root_identity, {}, {}, {});
+ CSS::StyleEngineFFI::style_engine_set_tree_scope_animation_keyframes(host, departed.tree_scope.value(), {}, {}, {});
if (departed.has_position_try_rules)
CSS::StyleEngineFFI::style_engine_set_tree_scope_position_try_rules(host, departed.tree_scope.value(), {}, {}, {});
}
@@ -12105,7 +12233,7 @@ void Document::sync_custom_property_registrations_to_rust()
.document_base_url = document_base_url.bytes().data(),
.document_base_url_length = document_base_url.bytes().size(),
};
- // A style transaction may still read the registry this replaces, so the registry is made anew.
+ // A style update may still read the registry this replaces, so the registry is made anew.
m_rust_custom_property_registry = CSS::ComputedValuesFFI::rust_custom_property_registry_update(
m_rust_custom_property_registry, &context, registrations.data(), registrations.size());
}
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index 71289bb4065..5cd440ca36c 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -11,6 +11,7 @@
#pragma once
#include <AK/Array.h>
+#include <AK/EnumBits.h>
#include <AK/Function.h>
#include <AK/HashMap.h>
#include <AK/HashTable.h>
@@ -35,6 +36,7 @@
#include <LibWeb/Bindings/NavigationType.h>
#include <LibWeb/CSS/CustomPropertyRegistration.h>
#include <LibWeb/CSS/ImageStyleValueResourceKey.h>
+#include <LibWeb/CSS/RustInlineStyleBlocks.h>
#include <LibWeb/CSS/ScrollStateContainerQuery.h>
#include <LibWeb/CSS/StyleScope.h>
#include <LibWeb/CSS/StyleUpdateInputs.h>
@@ -116,6 +118,23 @@ enum class QuirksMode {
Yes
};
+// The parts of the document's environment a style change moves, as the style engine's StyleEnvironment bits. Each
+// restyles the elements whose computation read it.
+enum class StyleEnvironmentChange : u8 {
+ // The user's preferred color scheme or the schemes the document supports.
+ ColorScheme = 1 << 0,
+ DevicePixelRatio = 1 << 1,
+ // The media features a value's if() or custom function may test.
+ MediaFeatures = 1 << 2,
+ // The axes of the viewport, which viewport-relative lengths resolve against.
+ ViewportWidth = 1 << 3,
+ ViewportHeight = 1 << 4,
+ // What every element may compute from: the quirks mode, which only the parser and document.open() move, before
+ // the document holds an element.
+ Everything = 1 << 7,
+};
+AK_ENUM_BITWISE_OPERATORS(StyleEnvironmentChange);
+
#define ENUMERATE_INVALIDATE_LAYOUT_TREE_REASONS(X) \
X(InternalsFullRebuildComparison) \
X(TopLayerElementStillRenderedAfterRemoval)
@@ -337,8 +356,9 @@ public:
WebIDL::ExceptionOr<void> populate_with_html_head_and_body();
GC::Ptr<Selection::Selection> get_selection() const;
- bool highlight_styles_are_observable(CSS::PseudoElement) const;
void set_needs_highlight_style_update(CSS::PseudoElement);
+ [[nodiscard]] bool needs_highlight_style_update() const;
+ void update_highlight_style_observability();
GC::Ptr<Range> find_in_page_active_match() const { return m_find_in_page_active_match; }
void set_find_in_page_active_match(GC::Ptr<Range>);
@@ -534,22 +554,20 @@ public:
Color theme_color(Layout::BegunRead const& read);
void update_style();
- // A style update, or a read of style or layout, joins the style transaction that flew beside the event loop first,
+ // update_style(), or a read of style or layout, joins the style update that flew beside the event loop first,
// and drains its reactions against the inputs it was sealed with: what was written beside it is the next
// transaction's. Where none flew, that is one test.
- void drain_flown_style_transaction(Layout::BegunRead const& read)
+ void drain_flown_style_update(Layout::BegunRead const& read)
{
if (m_flown_style_update_inputs.has_value()) [[unlikely]]
- drain_style_transaction_that_flew(read);
+ drain_style_update_that_flew(read);
}
- // Whether a style transaction flew whose reactions no style update has drained yet.
- bool has_flown_style_transaction() const { return m_flown_style_update_inputs.has_value(); }
- // Records what a style update records before it takes the document's style transaction, and lets the transaction
- // fly beside the event loop where `blocker` is none. The next style update takes its reactions in. Answers whether
- // the transaction flies.
+ // Whether a style update flew whose reactions have not been drained yet.
+ bool has_flown_style_update() const { return m_flown_style_update_inputs.has_value(); }
+ // Records what update_style() records before it runs the document's style update, and lets the update fly
+ // beside the event loop where `blocker` is none. The next update_style() takes its reactions in. Answers whether
+ // the update flies.
bool let_style_update_fly(Layout::RustFFI::FfiFlightBlocker blocker);
- // Seals the first round of a rendering update's layout for the frame its style flies in.
- void seal_first_layout_round(Layout::BegunRead const&);
// Brings the style up to date, and lets the first round of the rendering update's layout fly beside the event loop
// where `blocker` is none and the layout is not up to date. The next layout update takes it in. Answers whether the
// round flies.
@@ -584,7 +602,10 @@ public:
bool compositor_animation_wakeup_timer_is_active() const;
bool compositor_animation_observation_timer_is_active() const;
void throttled_animation_visibility_changed();
- void invalidate_style_for_viewport_change();
+ // Restyle the elements whose style read an axis of the viewport that moved from previous_viewport_size.
+ void invalidate_style_for_viewport_change(CSSPixelSize previous_viewport_size);
+ // Restyle the elements whose style computed from what `changes` names of the document's environment.
+ void record_style_environment_change(StyleEnvironmentChange changes);
void add_element_with_viewport_dependent_style(Element& element) { m_elements_with_viewport_dependent_style.set(element); }
bool suppresses_attribute_style_invalidation() const { return m_suppresses_attribute_style_invalidation; }
void set_suppresses_attribute_style_invalidation(bool suppresses) { m_suppresses_attribute_style_invalidation = suppresses; }
@@ -722,6 +743,8 @@ public:
QuirksMode mode() const { return m_quirks_mode; }
bool in_quirks_mode() const { return m_quirks_mode == QuirksMode::Yes; }
+
+ CSS::RustInlineStyleBlocks& inline_style_blocks() { return m_inline_style_blocks; }
bool in_limited_quirks_mode() const { return m_quirks_mode == QuirksMode::Limited; }
void set_quirks_mode(QuirksMode);
@@ -1034,6 +1057,14 @@ public:
}
bool has_completed_style_update() const { return m_has_completed_style_update; }
+ bool has_dirty_style_attributes() const { return !m_elements_with_dirty_style_attributes.is_empty(); }
+ // Whether a style update would report the style attributes it left out while nothing read them.
+ bool has_unreported_style_attributes_to_report() const;
+ // Whether a tree scope's counter styles may have moved since a style update last settled every scope's.
+ bool counter_style_scopes_need_update() const { return m_counter_style_scopes_need_update; }
+ void set_counter_style_scopes_need_update(bool value) { m_counter_style_scopes_need_update = value; }
+ void note_counter_style_scope_to_settle(ShadowRoot&);
+ void settle_counter_style_scopes(Layout::BegunRead const&);
void set_has_completed_style_update() { m_has_completed_style_update = true; }
void mark_style_attribute_dirty(Element&);
void synchronize_dirty_style_attributes();
@@ -1274,6 +1305,13 @@ public:
void disassociate_with_animation(GC::Ref<Animations::Animation>);
size_t associated_animation_count() const;
bool has_associated_animations() const { return !m_associated_animations.is_empty(); }
+ // Negative where `first` comes before `second` in tree order and positive where it comes after, for sorting
+ // animations by composite order. Two distinct elements of this document take no walk of their siblings once a tree
+ // has been asked about often enough, so that sorting many sibling elements is not quadratic in them per comparison.
+ int compare_elements_in_tree_order_for_composite_order(Element& first, Element& second);
+ // An attribute moves the DOM tree version, from `version_before`, but no element: the tree positions held at that
+ // version stand.
+ void keep_element_tree_positions_across_attribute_change(u64 version_before);
struct PendingAnimationEvent {
GC::Ref<DOM::Event> event;
@@ -1336,32 +1374,9 @@ public:
u64 style_engine_reaction_batch_runs { 0 };
u64 style_engine_reaction_elements { 0 };
u64 style_engine_published_reactions { 0 };
- u64 style_engine_record_deltas_applied { 0 };
u64 layout_style_record_publications { 0 };
- u64 style_engine_materialized_gaps { 0 };
- u64 element_style_recomputations { 0 };
- u64 element_style_noop_recomputations { 0 };
- u64 unchanged_style_record_deltas { 0 };
- u64 style_record_property_diffs_skipped { 0 };
- u64 style_record_property_damage_cache_hits { 0 };
- // Semantic output cardinalities, distinct from how many elements entered recomputation.
- u64 element_computed_style_changes { 0 };
- u64 committed_style_observer_consequences { 0 };
- u64 element_style_shared_computations { 0 };
- // Whether a recomputation could have been answered from what its last one read. The record
- // is the sharing key minus the style being replaced, so a recomputation whose input is
- // unchanged is one the engine could keep the existing style for outright.
- u64 element_style_input_changed_by_parent_style { 0 };
- u64 element_style_input_changed_by_parent_custom_properties { 0 };
- u64 element_style_input_reused { 0 };
- // Reactions whose new record the style engine computed itself, applied without a style
- // computation.
- u64 engine_computed_style_records { 0 };
// Animation frames that rebuilt only the groups the animated properties write, against
// frames that had to rebuild the whole style.
- u64 animated_style_reconstruction_fallbacks { 0 };
- u64 animated_style_overlay_builds { 0 };
- u64 animated_style_full_builds { 0 };
u64 animation_frame_pump_requests { 0 };
u64 animation_style_skip_cache_hits { 0 };
u64 animation_style_skip_cache_misses { 0 };
@@ -1370,15 +1385,13 @@ public:
u64 compositor_visual_animation_updates { 0 };
u64 compositor_visual_animation_timing_anchor_updates { 0 };
u64 compositor_keyframe_value_resolutions { 0 };
- u64 base_style_partial_builds { 0 };
- u64 base_style_full_builds { 0 };
- u64 computed_longhand_evaluations { 0 };
- u64 computed_longhand_drives_started { 0 };
u64 style_stabilization_epochs { 0 };
u64 style_stabilization_feedback_epochs { 0 };
u64 provisional_style_passes { 0 };
u64 style_stabilization_round_guard_hits { 0 };
u64 style_update_pass_guard_hits { 0 };
+ // What sorting animations in tree order asked of the tree itself, rather than of the document's tree positions.
+ u64 composite_order_document_position_compares { 0 };
u64 exact_stabilization_passes { 0 };
u64 style_stabilization_bound_failures { 0 };
u64 provisional_animation_events { 0 };
@@ -1399,17 +1412,6 @@ public:
u64 style_update_remainder_microseconds { 0 };
u64 relayouts_performed { 0 };
u64 style_update_microseconds { 0 };
- u64 custom_property_resolutions { 0 };
- u64 custom_property_elements { 0 };
- // What resolving those declared values actually walked: every entry into computing one
- // custom property's value, however reached. A value referenced by three others is entered
- // for each of them unless something remembers the answer, so this exceeding
- // custom_property_resolutions is repeated work made visible.
- u64 custom_property_value_computations { 0 };
- u64 custom_property_overlay_hits { 0 };
- u64 custom_property_cycle_participants { 0 };
- u64 style_cascade_microseconds { 0 };
- u64 style_values_microseconds { 0 };
};
StyleInvalidationCounters& style_invalidation_counters() const { return m_style_invalidation_counters; }
void reset_style_invalidation_counters(Layout::BegunRead const& read) const;
@@ -1531,6 +1533,9 @@ public:
size_t transition_generation() const { return m_transition_generation; }
void begin_style_stabilization_epoch();
void record_style_stabilization_pass(Layout::BegunRead const& read);
+ [[nodiscard]] bool is_at_style_stabilization_bound(Layout::BegunRead const& read) const;
+ // How many times an element's animated custom properties moved in this style stabilization epoch, counting this one.
+ [[nodiscard]] u64 note_animated_custom_properties_moved_in_stabilization_epoch(CSS::StyleNodeID);
void end_style_stabilization_epoch();
void note_style_stabilization_has_style_reactions()
{
@@ -1798,7 +1803,6 @@ private:
// Whether the first round of a rendering update's layout may be sealed: list items that wait to be renumbered and top
// layer work are the layout update's to do first.
- bool may_seal_first_layout_round() const;
Layout::RustFFI::FfiLayoutUpdateInputs first_layout_round_inputs() const;
// Whether nothing this document has pending could change layout geometry: style, layout and every input
// that feeds them are settled.
@@ -1812,7 +1816,7 @@ private:
void finish_animated_style_update();
void service_compositor_animation_wakeup(double timestamp);
- void drain_style_transaction_that_flew(Layout::BegunRead const&);
+ void drain_style_update_that_flew(Layout::BegunRead const&);
GC::Ref<WebIDL::ObservableArray> adopted_style_sheets() const;
@@ -1966,6 +1970,9 @@ private:
QuirksMode m_quirks_mode { QuirksMode::No };
+ // The declaration blocks of the document's style attributes, by their text.
+ CSS::RustInlineStyleBlocks m_inline_style_blocks;
+
// The MathML and SVG user-agent sheets decide nothing until the document holds an element in one
// of those namespaces, so they are attached the first time one arrives. Once attached they stay:
// a document that held one is likely to again, and every element pays for the flip.
@@ -2005,6 +2012,7 @@ private:
// https://html.spec.whatwg.org/multipage/interaction.html#autofocus-processed-flag
bool m_autofocus_processed_flag { false };
+ HashMap<CSS::StyleNodeID, u64> m_animated_custom_property_changes_in_stabilization_epoch;
bool m_created_for_appropriate_template_contents { false };
GC::Ptr<Document> m_associated_inert_template_document;
GC::Ptr<Document> m_appropriate_template_contents_owner_document;
@@ -2091,6 +2099,7 @@ private:
Vector<GC::Weak<CSS::MediaQueryList>> m_media_query_lists;
bool m_has_completed_style_update { false };
+ bool m_counter_style_scopes_need_update { true };
bool m_style_engine_tracks_tree { false };
CSS::StyleNodeID m_style_node_id;
GC::WeakHashSet<Element> m_elements_with_dirty_style_attributes;
@@ -2112,7 +2121,7 @@ private:
bool m_needs_throttled_animation_style_update_check { false };
bool m_force_throttled_animation_style_update { false };
Optional<u64> m_last_forced_throttled_animation_style_update_task_generation;
- // The inputs the style transaction that flew was sealed with, which its drain takes its reactions in against.
+ // The inputs the style update that flew was sealed with, which its drain takes its reactions in against.
Optional<CSS::StyleUpdateInputs> m_flown_style_update_inputs;
HashTable<GC::Ptr<NodeIterator>> m_node_iterators;
@@ -2230,7 +2239,6 @@ private:
Array<HighlightStyleObservability, 3> m_highlight_style_observability;
HighlightStyleObservability& highlight_style_observability(CSS::PseudoElement);
void update_highlight_style_observability(CSS::PseudoElement);
- void update_highlight_style_observability();
// NOTE: This is a cache to make finding the first <base href> or <base target> element O(1).
GC::Ptr<HTML::HTMLBaseElement> m_first_base_element_with_href_in_tree_order;
@@ -2296,6 +2304,12 @@ private:
// NB: Weak so the document does not unnecessarily keep animations alive. Note that this also includes animations
// associated with elements in shadow trees so differs from getAnimations()
GC::WeakHashSet<Animations::Animation> m_associated_animations;
+ // The tree position of every element of the document by its unique ID, valid for one DOM tree version. Sorting
+ // animations fills it once it asked the tree enough at that version.
+ HashMap<UniqueNodeID, u32> m_element_tree_positions;
+ u64 m_element_tree_positions_dom_tree_version { 0 };
+ u32 m_tree_order_compares_at_dom_tree_version { 0 };
+ u32 m_element_count_at_last_tree_positions_walk { 0 };
// https://www.w3.org/TR/web-animations-1/#document-default-document-timeline
GC::Ptr<Animations::DocumentTimeline> m_default_timeline;
@@ -2367,6 +2381,8 @@ private:
// Document should not visit ShadowRoot list to avoid leaks.
// It's responsibility of object that allocated ShadowRoot to keep it alive.
ShadowRoot::DocumentShadowRootList m_shadow_roots;
+ // The shadow roots whose counter style registry may resolve or publish differently since the last style update.
+ ShadowRoot::DocumentCounterStyleSettleList m_shadow_roots_with_counter_styles_to_settle;
u64 m_style_sheet_set_generation { 0 };
// The `@keyframes` rows the style engine still holds for shadow roots that left this document.
Vector<CSS::StyleScope::DepartedAnimationKeyframes> m_departed_animation_keyframes;
diff --git a/Libraries/LibWeb/DOM/DocumentHighlightStyles.cpp b/Libraries/LibWeb/DOM/DocumentHighlightStyles.cpp
new file mode 100644
index 00000000000..124cd406194
--- /dev/null
+++ b/Libraries/LibWeb/DOM/DocumentHighlightStyles.cpp
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/AnyOf.h>
+#include <AK/Format.h>
+#include <AK/HashTable.h>
+#include <AK/ScopeGuard.h>
+#include <LibWeb/Animations/AnimationEffect.h>
+#include <LibWeb/CSS/ComputedValues.h>
+#include <LibWeb/CSS/CustomPropertyData.h>
+#include <LibWeb/CSS/MainEffects.h>
+#include <LibWeb/CSS/StyleComputer.h>
+#include <LibWeb/CSS/StyleEngineInput.h>
+#include <LibWeb/CSS/StyleInvalidation.h>
+#include <LibWeb/CSS/StyleUpdateInputs.h>
+#include <LibWeb/DOM/AbstractElement.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/Element.h>
+#include <LibWeb/DOM/Node.h>
+#include <LibWeb/DOM/PseudoElement.h>
+#include <LibWeb/DOM/Range.h>
+#include <LibWeb/DOM/ShadowRoot.h>
+#include <LibWeb/DOM/Text.h>
+#include <LibWeb/Editing/SpellingMarkers.h>
+#include <LibWeb/HTML/FormAssociatedElement.h>
+#include <LibWeb/HTML/HTMLSlotElement.h>
+#include <LibWeb/HTML/LocalNavigable.h>
+#include <LibWeb/HTML/NavigableContainer.h>
+#include <LibWeb/Layout/Box.h>
+#include <LibWeb/Layout/NodeArena.h>
+#include <LibWeb/Painting/BoxViews.h>
+#include <LibWeb/Selection/Selection.h>
+
+namespace Web::DOM {
+
+Document::HighlightStyleObservability& Document::highlight_style_observability(CSS::PseudoElement pseudo_element)
+{
+ VERIFY(CSS::is_highlight_pseudo_element(pseudo_element));
+ switch (pseudo_element) {
+ case CSS::PseudoElement::Selection:
+ return m_highlight_style_observability[0];
+ case CSS::PseudoElement::SpellingError:
+ return m_highlight_style_observability[2];
+ default:
+ return m_highlight_style_observability[1];
+ }
+}
+
+void Document::set_needs_highlight_style_update(CSS::PseudoElement pseudo_element)
+{
+ highlight_style_observability(pseudo_element).needs_update = true;
+}
+
+bool Document::needs_highlight_style_update() const
+{
+ return any_of(m_highlight_style_observability, [](auto const& state) { return state.needs_update; });
+}
+
+static void collect_highlight_observing_elements(Vector<CSS::StyleNodeID>& style_nodes, Node& root, Range const* range)
+{
+ auto record_element = [&](Node& node) {
+ if (auto* element = as_if<Element>(node); element && element->style_node_id() != CSS::StyleNodeID {})
+ style_nodes.append(element->style_node_id());
+ };
+
+ // NB: Ancestors supply inherited highlight styles, and text controls paint through
+ // their internal shadow trees. Neither requires visiting unrelated subtrees.
+ for (auto* ancestor = root.flat_tree_parent(); ancestor; ancestor = ancestor->flat_tree_parent())
+ record_element(*ancestor);
+ root.for_each_shadow_including_inclusive_descendant([&](Node& node) {
+ if (range && &node.root() == &range->start_container()->root() && !range->intersects_node(node))
+ return TraversalDecision::SkipChildrenAndContinue;
+ record_element(node);
+ return TraversalDecision::Continue;
+ });
+}
+
+struct HighlightStyleInput {
+ GC::Ref<Node> root;
+ GC::Ptr<Range> range;
+};
+
+static GC::ConservativeVector<HighlightStyleInput, 2> selection_style_inputs(Document& document)
+{
+ GC::ConservativeVector<HighlightStyleInput, 2> inputs;
+ if (auto selection = document.get_selection(); selection && !selection->is_collapsed()) {
+ auto range = selection->range();
+ inputs.append({ range->common_ancestor_container(), range });
+ }
+ if (auto* text_control = as_if<HTML::FormAssociatedTextControlElement>(document.focused_area().ptr()); text_control && text_control->selection_start() != text_control->selection_end())
+ inputs.append({ *document.focused_area(), nullptr });
+ return inputs;
+}
+
+static GC::ConservativeVector<HighlightStyleInput, 2> search_text_style_inputs(Document& document)
+{
+ GC::ConservativeVector<HighlightStyleInput, 2> inputs;
+ if (auto active_match = document.find_in_page_active_match(); active_match && !active_match->collapsed())
+ inputs.append({ active_match->common_ancestor_container(), active_match });
+ GC::RootHashTable<Node*> highlighted_roots;
+ for (auto const& match : document.find_in_page_highlighted_matches()) {
+ if (match->collapsed())
+ continue;
+ auto root = match->common_ancestor_container();
+ if (highlighted_roots.set(root.ptr()) == HashSetResult::InsertedNewEntry)
+ inputs.append({ root, nullptr });
+ }
+ return inputs;
+}
+
+static GC::ConservativeVector<HighlightStyleInput, 2> spelling_error_style_inputs(Document& document)
+{
+ GC::ConservativeVector<HighlightStyleInput, 2> inputs;
+ if (!document.has_spelling_markers())
+ return inputs;
+ GC::RootHashTable<Node*> roots;
+ document.spelling_markers().for_each_marked_text([&](Text& text, auto) {
+ auto* parent = text.parent();
+ if (parent && roots.set(parent) == HashSetResult::InsertedNewEntry)
+ inputs.append({ *parent, nullptr });
+ });
+ // A root inside another root's subtree adds nothing, since the outer root's walk visits all of it.
+ inputs.remove_all_matching([&](auto const& input) {
+ for (auto* ancestor = input.root->parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
+ if (roots.contains(ancestor))
+ return true;
+ }
+ return false;
+ });
+ return inputs;
+}
+
+void Document::update_highlight_style_observability(CSS::PseudoElement pseudo_element)
+{
+ // NB: Editing commands temporarily select content to restore its formatting. Style reads
+ // during the action must not activate selection styles throughout the document for these
+ // intermediate ranges. Observe the final selection after the action, including in input
+ // event handlers. Explicit ::selection queries can still compute their style on demand.
+ if (pseudo_element == CSS::PseudoElement::Selection && m_running_editing_command_action)
+ return;
+
+ // OPTIMIZATION: Whatever moves what shows a highlight notes that it needs an update, so one that needs none has
+ // nothing to collect.
+ auto& state = highlight_style_observability(pseudo_element);
+ if (!state.needs_update)
+ return;
+
+ auto inputs = [&] {
+ switch (pseudo_element) {
+ case CSS::PseudoElement::Selection:
+ return selection_style_inputs(*this);
+ case CSS::PseudoElement::SpellingError:
+ return spelling_error_style_inputs(*this);
+ default:
+ return search_text_style_inputs(*this);
+ }
+ }();
+ bool observable = !inputs.is_empty();
+ state = { .observable = observable, .needs_update = false };
+ // NB: The style engine restyles the elements that start or stop showing the highlight, which
+ // are the only ones whose highlight styles a style update keeps.
+ Vector<CSS::StyleNodeID> style_nodes;
+ for (auto const& input : inputs)
+ collect_highlight_observing_elements(style_nodes, input.root, input.range.ptr());
+ auto& style_engine = style_computer().style_engine();
+ style_engine.set_highlight_observing_elements(pseudo_element, style_nodes);
+ if (pseudo_element == CSS::PseudoElement::SearchText)
+ style_engine.set_highlight_observing_elements(CSS::PseudoElement::SearchTextCurrent, style_nodes);
+}
+
+void Document::update_highlight_style_observability()
+{
+ update_highlight_style_observability(CSS::PseudoElement::Selection);
+ update_highlight_style_observability(CSS::PseudoElement::SearchText);
+ update_highlight_style_observability(CSS::PseudoElement::SpellingError);
+}
+
+}
diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cpp
index 6e9c4938641..239a6252efc 100644
--- a/Libraries/LibWeb/DOM/Element.cpp
+++ b/Libraries/LibWeb/DOM/Element.cpp
@@ -46,6 +46,7 @@
#include <LibWeb/CSS/Invalidation/LanguageInvalidator.h>
#include <LibWeb/CSS/Invalidation/PartInvalidator.h>
#include <LibWeb/CSS/Invalidation/PseudoClassInvalidator.h>
+#include <LibWeb/CSS/MainEffects.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/CSS/PropertyID.h>
#include <LibWeb/CSS/SelectorMatching.h>
@@ -173,7 +174,7 @@
namespace Web::DOM {
#if ARCH(X86_64) && !defined(AK_OS_WINDOWS)
-static_assert(sizeof(Element) == 400);
+static_assert(sizeof(Element) == 304);
#endif
Element::RareData::~RareData() = default;
@@ -381,7 +382,7 @@ void Element::finalize()
void Element::append_to_attribute_list(QualifiedName name, Utf16String value)
{
- add_to_subtree_attribute_name_filter(attribute_name_filter_bit(name.local_name()));
+ add_to_subtree_name_filter(name_filter_bit(name.local_name()));
if (!m_attributes)
m_attributes = AttributeList::create(1);
else
@@ -389,11 +390,11 @@ void Element::append_to_attribute_list(QualifiedName name, Utf16String value)
m_attributes->unchecked_append(move(name), move(value));
}
-void Element::add_to_subtree_attribute_name_filter(u64 bits)
+void Element::add_to_subtree_name_filter(u64 bits)
{
// An element's filter holds those of its children, so the walk up ends at the first that has the bits.
- for (auto* element = this; element && (element->m_subtree_attribute_name_filter & bits) != bits; element = element->parent_element().ptr())
- element->m_subtree_attribute_name_filter |= bits;
+ for (auto* element = this; element && (element->m_subtree_name_filter & bits) != bits; element = element->parent_element().ptr())
+ element->m_subtree_name_filter |= bits;
}
void Element::ensure_attribute_capacity(size_t capacity)
@@ -1468,55 +1469,10 @@ void Element::run_attribute_change_steps(Utf16FlyString const& local_name, Optio
auto html_collection_invalidation_types = document().html_collection_attribute_invalidation_types_for_attribute(local_name, namespace_);
if (html_collection_invalidation_types != 0)
invalidate_html_collection_caches_in_ancestors_for_attribute_change(html_collection_invalidation_types);
- bump_dom_tree_version();
+ bump_dom_tree_version_for_attribute_change();
}
}
-static CSS::StyleComputer::ComputedStyleInvalidation decode_style_record_invalidation(u32 packed)
-{
- CSS::StyleComputer::ComputedStyleInvalidation result;
- result.invalidation = CSS::decode_style_invalidation(packed);
- result.any_computed_value_changed = packed & to_underlying(CSS::StyleEngineFFI::FfiStyleInvalidationField::AnyComputedValueChanged);
- return result;
-}
-// Whether the counter styles the element's generated content names now differ from the ones the box built for it
-// renders from. The build resolves them from the published record and the tree scope's registered counter styles, and
-// the arena keeps what each box was built with.
-static bool content_counter_styles_changed(Layout::BegunRead const& read, DOM::AbstractElement const& abstract_element, CSS::ComputedValues const& new_computed_values)
-{
- auto* arena = abstract_element.element().document().layout_node_arena_if_created();
- if (!arena)
- return false;
- // Only a pseudo-element's box renders generated content.
- auto const pseudo_element = abstract_element.pseudo_element();
- if (!pseudo_element.has_value())
- return false;
- // A box whose `content` changes is rebuilt for that alone, so only content naming a registered counter style can
- // render one that changed beneath it. A marker whose `content` is `normal` renders its list item's counter style.
- if (*pseudo_element != CSS::PseudoElement::Marker
- && !CSS::ComputedValuesFFI::rust_content_reads_counter_style_environment(new_computed_values.computed_content()->rust_style_value_data()))
- return false;
- abstract_element.style_scope().publish_counter_style_lookup_chain(read);
- return Layout::RustFFI::render_state_content_counter_styles_changed(arena->host(), &read, abstract_element.element().style_node_id().value(), Layout::Node::encode_generated_for(*pseudo_element));
-}
-
-static void add_element_dependent_invalidation(Layout::BegunRead const& read, CSS::RequiredInvalidationAfterStyleChange& invalidation, CSS::ComputedValues const& new_computed_values, bool had_layout_node, DOM::AbstractElement& abstract_element)
-{
- // NB: Even if the computed value hasn't changed the resolved counter style may have (e.g. if the relevant
- // @counter-style rule was modified, or a new rule with the same name took precedence over the old one).
- // A list item's marker is a pseudo-element of its own, which answers for the list item's counter style.
- // Generated content and the marker live inside the element's own layout subtree, so, like a
- // 'content' change, they rebuild from the element rather than its parent. The rebuild moves no
- // style, so the element's children do not react to it.
- if (had_layout_node && content_counter_styles_changed(read, abstract_element, new_computed_values))
- invalidation |= CSS::RequiredInvalidationAfterStyleChange::rebuild_layout_tree_for_counter_styles_from(CSS::LayoutTreeRebuildRoot::Self);
-}
-
-static bool style_record_is_unchanged(CSS::StyleEngine::StyleRecordDelta const& delta)
-{
- return !!delta.old_style_record && delta.old_style_record == delta.new_style_record;
-}
-
// https://drafts.csswg.org/css-overflow-3/#overflow-propagation
// https://drafts.csswg.org/css-writing-modes-4/#principal-flow
// The root element and, for an html root, its first body child are the elements whose overflow, writing mode, and
@@ -1532,269 +1488,6 @@ bool Element::is_viewport_propagation_source() const
&& document_element->first_child_of_type<HTML::HTMLBodyElement>() == this;
}
-static CSS::StyleComputer::ComputedStyleInvalidation compute_required_invalidation_with_cache(Layout::BegunRead const& read, CSS::StyleComputer& style_computer, CSS::ComputedValues const& new_computed_values, bool had_layout_node, DOM::AbstractElement& abstract_element, CSS::StyleEngine::StyleRecordDelta const& style_record_delta, Optional<u32> answered_damage = {})
-{
- CSS::StyleComputer::ComputedStyleInvalidation result;
- if (style_record_is_unchanged(style_record_delta)) {
- ++abstract_element.document().style_invalidation_counters().style_record_property_diffs_skipped;
- return result;
- }
- // The engine reads what the move damages from the two records and its own facts of the element,
- // and answers a record it computed with it.
- VERIFY(!abstract_element.pseudo_element().has_value());
- auto packed = answered_damage.value_or_lazy_evaluated([&] {
- return CSS::StyleEngineFFI::style_engine_element_record_damage(style_computer.style_engine().host(), &read, abstract_element.element().style_node_id().value(), style_record_delta.old_style_record.value(), style_record_delta.new_style_record.value());
- });
- if (packed & to_underlying(CSS::StyleEngineFFI::FfiStyleInvalidationField::CacheHit))
- ++abstract_element.document().style_invalidation_counters().style_record_property_damage_cache_hits;
- result = decode_style_record_invalidation(packed);
- add_element_dependent_invalidation(read, result.invalidation, new_computed_values, had_layout_node, abstract_element);
- return result;
-}
-
-// An element-backed pseudo-element is the element in the host's shadow tree that backs it, which
-// its own row styles: a host computed again drives those elements again, rather than computing
-// them beside itself.
-static void record_element_reference_pseudo_element_inputs(Element& element)
-{
- auto& style_engine = element.document().style_computer().style_engine();
- for (auto i = to_underlying(CSS::first_element_reference_pseudo_element); i <= to_underlying(CSS::last_element_reference_pseudo_element); ++i) {
- if (auto pseudo_element = element.get_pseudo_element(static_cast<CSS::PseudoElement>(i)); pseudo_element.has_value()) {
- auto& referenced_element = as<ElementReferencePseudoElement>(*pseudo_element).referenced_element();
- style_engine.record_derived_element_style_input_change(referenced_element->style_node_id(), CSS::StyleEngine::RecomputeStyle);
- }
- }
-}
-
-static void record_engine_container_query_effects(Layout::BegunRead const&, Element&);
-
-CSS::RequiredInvalidationAfterStyleChange Element::recompute_pseudo_element_styles(Layout::BegunRead const& read, bool&, bool had_list_marker, CSS::ComputedValues const* old_originating_style, EnginePseudoElementRecords const* engine_pseudo_element_records, EngineRecordDamages const* engine_record_damages)
-{
- CSS::RequiredInvalidationAfterStyleChange invalidation;
-
- if (auto* rare_data = element_rare_data(); rare_data && rare_data->custom_property_consumer_data)
- rare_data->custom_property_consumer_data->pseudo_element_style_query_references.clear_with_capacity();
-
- auto& style_computer = document().style_computer();
- auto originating_style = computed_style();
- // The engine settles the synthetic pseudo-elements of an element against the record the host
- // just installed or composed, as it settles them beside a record of its own, and the host
- // installs the engine's records.
- EnginePseudoElementRecords records_settled_after_host_record {};
- bool const settled_after_host_record = [&] {
- if (engine_pseudo_element_records || style_node_id() == 0 || !originating_style)
- return false;
- // A reused originating record keeps the pseudo-element inventory it was computed with; the
- // style engine's answer says which pseudo-elements have rules now.
- auto const engine_pseudo_element_styles = CSS::StyleEngineFFI::style_engine_published_pseudo_style_mask(style_computer.style_engine().host(), &read, style_node_id().value());
- // The transaction whose row composes the element answers which kinds with rules no settle generates or
- // changes, as `*::before` rules styling nothing but `box-sizing` are.
- auto const inert_pseudo_elements = CSS::StyleEngineFFI::style_engine_inert_pseudo_kinds(style_computer.style_engine().host(), style_node_id().value());
- // Most elements have no style for any of the kinds the engine settles. A marker is
- // refreshed for a list item only.
- auto may_have_style = [&](CSS::PseudoElement pseudo_element) {
- if ((inert_pseudo_elements >> to_underlying(pseudo_element)) & 1)
- return false;
- return ((engine_pseudo_element_styles >> to_underlying(pseudo_element)) & 1)
- || !!style_record_identity(pseudo_element)
- || (old_originating_style && old_originating_style->has_pseudo_element_style(pseudo_element))
- || originating_style->has_pseudo_element_style(pseudo_element);
- };
- auto highlight_may_have_style = [&](CSS::PseudoElement pseudo_element) {
- return document().highlight_styles_are_observable(pseudo_element)
- && (may_have_style(pseudo_element)
- || AbstractElement { *this, pseudo_element }.highlight_inheritance_parent().has_value());
- };
- if (!had_list_marker && !originating_style->display().is_list_item()
- && !may_have_style(CSS::PseudoElement::Before)
- && !may_have_style(CSS::PseudoElement::After)
- && !may_have_style(CSS::PseudoElement::FirstLetter)
- && !(m_rendered_in_top_layer && may_have_style(CSS::PseudoElement::Backdrop))
- && !highlight_may_have_style(CSS::PseudoElement::Selection)
- && !highlight_may_have_style(CSS::PseudoElement::SearchText)
- && !highlight_may_have_style(CSS::PseudoElement::SearchTextCurrent)
- && !highlight_may_have_style(CSS::PseudoElement::SpellingError))
- return false;
- auto settled = CSS::StyleEngineFFI::style_engine_settle_pseudo_records_after_host_record(style_computer.style_engine().host(), &read, style_node_id().value(), had_list_marker);
- // What the settled pseudo-elements' container-relative lengths read of the element's containers.
- record_engine_container_query_effects(read, *this);
- // The engine leaves the pseudo-elements alone where it cannot compute one of them: they
- // keep the records they hold.
- if (settled.refused)
- return false;
- for (size_t kind = 0; kind < array_size(settled.pseudo_records); ++kind) {
- if (!((settled.pseudo_records_present >> kind) & 1))
- continue;
- CSS::StyleRecordID record { settled.pseudo_records[kind] };
- records_settled_after_host_record[kind] = record;
- // What the element's dependencies record for a pseudo-element's computation.
- if (!!record && has_flag(style_computer.style_engine().style_record_dependency_flags(read, record), CSS::StyleRecordDependencyFlag::DependsOnViewportMetrics))
- set_style_depends_on_viewport_metrics();
- }
- if (settled.uses_substitution)
- set_style_uses_var_css_function();
- if (settled.record_reads & to_underlying(CSS::StyleEngineFFI::FfiNodeRecordReads::Attributes))
- set_style_uses_attr_css_function();
- if (settled.record_reads & to_underlying(CSS::StyleEngineFFI::FfiNodeRecordReads::SiblingPosition))
- set_style_uses_tree_counting_function();
- if (settled.record_reads & to_underlying(CSS::StyleEngineFFI::FfiNodeRecordReads::InheritFunction))
- set_style_uses_inherit_css_function();
- if (settled.record_reads & to_underlying(CSS::StyleEngineFFI::FfiNodeRecordReads::IfFunction))
- set_style_uses_if_css_function();
- if (settled.record_reads & to_underlying(CSS::StyleEngineFFI::FfiNodeRecordReads::CustomFunction))
- set_style_uses_custom_function();
- // What C++ marks the parent with when a pseudo-element it computes explicitly inherits a
- // non-inherited property.
- if (settled.explicitly_inherited_groups != 0 && parent())
- parent()->add_children_explicitly_inherited_non_inherited_style_groups(settled.explicitly_inherited_groups == NumericLimits<u32>::max() ? CSS::ComputedValues::all_style_groups : settled.explicitly_inherited_groups);
- return true;
- }();
- if (settled_after_host_record)
- engine_pseudo_element_records = &records_settled_after_host_record;
-
- // Any document change that can cause this element's style to change, could also affect its pseudo-elements.
- auto recompute_pseudo_element_style = [&](CSS::PseudoElement pseudo_element) {
- // A pseudo-element the style engine settled beside the element's record takes the engine's answer. One the
- // engine left alone is unchanged, as is every pseudo-element when the engine settled none of them. Whether
- // highlight styles are observable at all stays the host's decision.
- // An unobservable highlight pseudo-element holds no record, whatever the engine left standing, and neither
- // does the ::backdrop of an element outside the top layer.
- auto old_style_record = style_record_identity(pseudo_element);
- if ((CSS::is_highlight_pseudo_element(pseudo_element) && !document().highlight_styles_are_observable(pseudo_element))
- || (pseudo_element == CSS::PseudoElement::Backdrop && !m_rendered_in_top_layer)) {
- if (!!old_style_record) {
- auto delta = style_computer.style_engine().remove_computed_pseudo(read, style_node_id(), to_underlying(pseudo_element));
- set_computed_style(pseudo_element, delta.new_style_record);
- }
- return;
- }
- if (!engine_pseudo_element_records)
- return;
- auto engine_record = engine_pseudo_element_records->at(to_underlying(pseudo_element));
- if (!engine_record.has_value())
- return;
- auto pseudo_element_style = computed_style(pseudo_element);
- auto const* pseudo_element_values = pseudo_element_style ? &*pseudo_element_style : nullptr;
- bool const had_layout_node = !!pseudo_element_unsafe_layout_node(read, pseudo_element);
- RefPtr<CSS::ComputedValues const> style_to_preserve_for_detachment;
- if (had_layout_node && pseudo_element_values && pseudo_element_values->animated_properties())
- style_to_preserve_for_detachment = CSS::ComputedValues::Builder { *pseudo_element_values }.build();
-
- CSS::StyleEngine::StyleRecordDelta style_record_delta {};
- style_record_delta.new_style_record = *engine_record;
- auto engine_pseudo_element_style = !!*engine_record ? style_computer.computed_style_record_view(read, *engine_record) : CSS::ComputedStyleRecordView {};
- CSS::ComputedValues const* new_pseudo_element_style = engine_pseudo_element_style ? &*engine_pseudo_element_style : nullptr;
- style_record_delta.old_style_record = old_style_record;
- if (style_record_is_unchanged(style_record_delta))
- ++document().style_invalidation_counters().unchanged_style_record_deltas;
-
- // The engine decides what the move damages from the two records and the originating element's, including a
- // box that appears or goes away. What the pseudo-element's box was built with is the host's to compare: the
- // counter styles it resolved.
- bool counter_styles_changed = false;
- if (!CSS::is_highlight_pseudo_element(pseudo_element) && pseudo_element_values && new_pseudo_element_style) {
- if (style_record_is_unchanged(style_record_delta)) {
- ++document().style_invalidation_counters().style_record_property_diffs_skipped;
- } else {
- DOM::AbstractElement abstract_element { *this, pseudo_element };
- CSS::RequiredInvalidationAfterStyleChange counter_style_invalidation;
- add_element_dependent_invalidation(read, counter_style_invalidation, *new_pseudo_element_style, had_layout_node, abstract_element);
- counter_styles_changed = !counter_style_invalidation.is_none();
- }
- }
- auto record_damage = [&](bool with_counter_style_rebuild) {
- return CSS::StyleEngineFFI::style_engine_pseudo_element_record_damage(
- style_computer.style_engine().host(), &read, style_node_id().value(),
- to_underlying(pseudo_element),
- style_record_delta.old_style_record.value(),
- style_record_delta.new_style_record.value(),
- style_record_identity().value(),
- with_counter_style_rebuild);
- };
- // The engine answered its record with what the move from the pseudo-element record it names
- // damages, decided against the originating record it names.
- Optional<u32> answered_damage;
- if (engine_record_damages) {
- if (auto const& answer = engine_record_damages->pseudo_elements[to_underlying(pseudo_element)];
- answer.has_value()
- && answer->move.answers(style_record_delta.old_style_record, style_record_delta.new_style_record)
- && answer->originating_style_record == style_record_identity())
- answered_damage = answer->move.packed;
- }
- auto packed = answered_damage.value_or_lazy_evaluated([&] { return record_damage(false); });
- if (packed & to_underlying(CSS::StyleEngineFFI::FfiStyleInvalidationField::CacheHit))
- ++document().style_invalidation_counters().style_record_property_damage_cache_hits;
- auto result = decode_style_record_invalidation(packed);
- if (result.any_computed_value_changed)
- document().style_invalidation_counters().element_computed_style_changes++;
- invalidation |= result.invalidation;
- // The box rebuilt with its new counter styles is rebuilt from wherever the engine places it, but the rebuild
- // moves no style the element's children react to.
- if (counter_styles_changed) {
- auto rebuild = CSS::decode_style_invalidation(record_damage(true));
- if (rebuild.needs_layout_tree_rebuild())
- invalidation |= CSS::RequiredInvalidationAfterStyleChange::rebuild_layout_tree_for_counter_styles_from(rebuild.layout_tree_rebuild_root());
- }
-
- if (new_pseudo_element_style) {
- // The transition step of a pseudo-element runs where its record is installed, against the record it moved
- // away from.
- CSS::StyleRecordPin const before_change { style_computer, old_style_record };
- set_computed_style(pseudo_element, style_record_delta.new_style_record);
- install_engine_pseudo_element_custom_property_data(read, pseudo_element, style_computer.style_engine().style_record_custom_property_environment(read, *engine_record));
- style_computer.compose_installed_engine_record(read, { *this, pseudo_element }, before_change.style_record());
- if (!!before_change.style_record())
- invalidation |= style_computer.run_transition_step_for_installed_record(read, { *this, pseudo_element }, before_change.style_record());
- } else if (auto existing_pseudo_element = get_synthetic_pseudo_element(pseudo_element); existing_pseudo_element.has_value())
- existing_pseudo_element->clear_computed_style(move(style_to_preserve_for_detachment));
-
- // Descendants' highlight pseudo-elements inherit from this one, and nothing else names it as their input.
- if (CSS::is_highlight_pseudo_element(pseudo_element) && !style_record_is_unchanged(style_record_delta)) {
- style_computer.style_engine().record_flat_tree_descendant_style_input_changes(style_node_id(),
- CSS::StyleEngine::RecomputeStyle | CSS::StyleEngine::PseudoInputsMayHaveChanged);
- }
- };
-
- recompute_pseudo_element_style(CSS::PseudoElement::Before);
- recompute_pseudo_element_style(CSS::PseudoElement::After);
- recompute_pseudo_element_style(CSS::PseudoElement::FirstLetter);
- recompute_pseudo_element_style(CSS::PseudoElement::Selection);
- recompute_pseudo_element_style(CSS::PseudoElement::SearchText);
- recompute_pseudo_element_style(CSS::PseudoElement::SearchTextCurrent);
- recompute_pseudo_element_style(CSS::PseudoElement::SpellingError);
- // An element that left the top layer drops the ::backdrop it held.
- if (m_rendered_in_top_layer || !!style_record_identity(CSS::PseudoElement::Backdrop))
- recompute_pseudo_element_style(CSS::PseudoElement::Backdrop);
- recompute_pseudo_element_style(CSS::PseudoElement::Marker);
- if (settled_after_host_record)
- CSS::StyleEngineFFI::style_engine_acknowledge_engine_computed_record(style_computer.style_engine().host(), style_node_id());
-
- return invalidation;
-}
-
-CSS::RequiredInvalidationAfterStyleChange Element::refresh_pseudo_element_styles_over_composition(Layout::BegunRead const& read, CSS::ComputedValues const* old_computed_values, bool& did_change_custom_properties)
-{
- auto invalidation = recompute_pseudo_element_styles(read, did_change_custom_properties, old_computed_values && old_computed_values->display().is_list_item(), old_computed_values);
- publish_custom_property_names();
- apply_computed_pseudo_element_styles_to_layout_nodes_if_needed(read, invalidation);
- return invalidation;
-}
-
-CSS::RequiredInvalidationAfterStyleChange Element::recompute_pseudo_element_styles(Layout::BegunRead const& read)
-{
- auto computed_values = this->computed_style();
- VERIFY(computed_values);
-
- bool did_change_custom_properties = false;
- record_element_reference_pseudo_element_inputs(*this);
- auto invalidation = recompute_pseudo_element_styles(read, did_change_custom_properties, computed_values->display().is_list_item(), nullptr);
- publish_custom_property_names();
- if (!invalidation.is_none())
- document().style_invalidation_counters().committed_style_observer_consequences++;
- apply_computed_pseudo_element_styles_to_layout_nodes_if_needed(read, invalidation);
- return invalidation;
-}
-
void Element::set_needs_layout_tree_rebuild(Layout::BegunRead const& read, SetNeedsLayoutTreeUpdateReason reason, CSS::LayoutTreeRebuildRoot rebuild_root)
{
// A self-scoped style invalidation can replace the element's principal box in place. Anonymous-parent escalation
@@ -1872,7 +1565,7 @@ static bool element_displays_a_list_item_counter_value(Element const& element)
}
if (!CSS::display_from_ffi_display(element.style_group<CSS::ComputedValues::BoxValues>()->display).is_list_item())
return false;
- return element.style_scope().list_style_type_depends_on_counter_value(element.style_group<CSS::ComputedValues::InheritedListValues>()->list_style_type.pointer);
+ return element.style_scope().list_style_type_depends_on_counter_value(element.style_group<CSS::ComputedValues::InheritedListTableValues>()->list_style_type.pointer);
}
// A list item box that appears or disappears renumbers the list-item counter for everything after
@@ -2008,6 +1701,19 @@ bool Element::apply_box_presence_change_in_place(Layout::BegunRead const& read,
return true;
}
+// Repaints the box of `layout_node` as a style change with `invalidation` asks. The render side repainted a box it
+// installed the record of itself, which leaves the document to record its display list again.
+static void repaint_layout_node_after_style_change(Layout::NodeWithStyle const& layout_node, CSS::RequiredInvalidationAfterStyleChange const& invalidation)
+{
+ if (Layout::style_record_installed_by_render_state(layout_node, layout_node.style_record_identity())) {
+ if (invalidation.needs_repaint())
+ Painting::request_document_repaint(layout_node.document(), invalidation.invalidates_hit_test_display_list() ? InvalidateDisplayList::PaintCommandsAndHitTestList : InvalidateDisplayList::PaintCommands);
+ return;
+ }
+ if (Painting::has_committed_box(layout_node))
+ Painting::repaint_after_style_change(layout_node, invalidation);
+}
+
static void apply_display_contents_style_to_text_boxes(Element& element, CSS::RequiredInvalidationAfterStyleChange const& invalidation)
{
if (invalidation.is_none())
@@ -2034,8 +1740,7 @@ void Element::apply_computed_style_to_layout_node_if_needed(Layout::BegunRead co
// If we're keeping the layout tree, we can just apply the new style to the existing layout tree.
VERIFY(has_style());
layout_node->apply_style(style_record_identity());
- if (Painting::has_committed_box(*layout_node))
- Painting::repaint_after_style_change(*layout_node, invalidation);
+ repaint_layout_node_after_style_change(*layout_node, invalidation);
apply_computed_pseudo_element_styles_to_layout_nodes_if_needed(read, invalidation);
}
@@ -2063,49 +1768,17 @@ void Element::apply_computed_pseudo_element_styles_to_layout_nodes_if_needed(Lay
if (auto node_with_style = pseudo_element.unsafe_layout_node(read)) {
node_with_style->apply_style(style_record_identity(pseudo_element_type));
- if (Painting::has_committed_box(*node_with_style))
- Painting::repaint_after_style_change(*node_with_style, invalidation);
+ repaint_layout_node_after_style_change(*node_with_style, invalidation);
}
});
}
-void Element::record_style_query_custom_property_reference(Optional<CSS::PseudoElement> pseudo_element, Utf16FlyString const& name)
-{
- auto& rare_data = ensure_element_rare_data();
- if (!rare_data.custom_property_consumer_data)
- rare_data.custom_property_consumer_data = make<RareData::CustomPropertyConsumerData>();
- auto& consumer_data = *rare_data.custom_property_consumer_data;
-
- // A record the style engine installs adds its references to the ones the element holds, so
- // each name is held once.
- if (pseudo_element.has_value()) {
- for (auto& entry : consumer_data.pseudo_element_style_query_references) {
- if (entry.pseudo_element == *pseudo_element) {
- if (!entry.references.contains_slow(name))
- entry.references.append(name);
- return;
- }
- }
- consumer_data.pseudo_element_style_query_references.append({
- .pseudo_element = *pseudo_element,
- .references = {},
- });
- consumer_data.pseudo_element_style_query_references.last().references.append(name);
- return;
- }
- if (!consumer_data.style_query_references.contains_slow(name))
- consumer_data.style_query_references.append(name);
-}
-
void Element::set_style_uses_if_css_function()
{
if (m_style_uses_if_css_function)
return;
- bool const publishes = !style_recomputes_on_environment_move();
m_style_uses_if_css_function = true;
document().add_element_with_viewport_dependent_style(*this);
- if (publishes)
- publish_style_recomputes_on_environment_move();
}
// A custom function's declarations may be gated by @media conditions, which a viewport change
@@ -2114,19 +1787,8 @@ void Element::set_style_uses_custom_function()
{
if (m_style_uses_custom_function)
return;
- bool const publishes = !style_recomputes_on_environment_move();
m_style_uses_custom_function = true;
document().add_element_with_viewport_dependent_style(*this);
- if (publishes)
- publish_style_recomputes_on_environment_move();
-}
-
-void Element::publish_style_recomputes_on_environment_move()
-{
- auto style_node = style_node_id();
- if (style_node == 0)
- return;
- CSS::StyleEngineFFI::style_engine_set_element_recomputes_on_environment_move(document().style_computer().style_engine().host(), style_node, style_recomputes_on_environment_move());
}
void Element::publish_size_container_query_facts()
@@ -2145,71 +1807,6 @@ void Element::set_style_depends_on_viewport_metrics()
document().add_element_with_viewport_dependent_style(*this);
}
-void Element::publish_custom_property_names()
-{
- PublishedCustomPropertyNames published_names {
- .data = custom_property_data({}),
- .uses_var_css_function = m_style_uses_var_css_function,
- .uses_custom_function = m_style_uses_custom_function,
- };
- Vector<RefPtr<CSS::CustomPropertyData const>> published_pseudo_element_data;
- // NB: The engine names the synthetic pseudo-elements that hold an environment in one answer.
- auto const synthetic_pseudo_elements_with_data = CSS::StyleEngineFFI::style_engine_pseudo_elements_with_custom_property_data(document().style_computer().style_engine().host(), style_node_id().value());
- for (auto i = 0; i < to_underlying(CSS::PseudoElement::KnownPseudoElementCount); ++i) {
- auto pseudo_element = static_cast<CSS::PseudoElement>(i);
- if (is_synthetic_pseudo_element(pseudo_element) && !((synthetic_pseudo_elements_with_data >> i) & 1))
- continue;
- if (auto data = custom_property_data(pseudo_element))
- published_pseudo_element_data.append(move(data));
- }
- Vector<Utf16FlyString> published_references;
- RareData::CustomPropertyConsumerData* consumer_data = nullptr;
- if (auto* rare_data = element_rare_data())
- consumer_data = rare_data->custom_property_consumer_data.ptr();
- if (consumer_data) {
- published_references = consumer_data->style_query_references;
- for (auto const& entry : consumer_data->pseudo_element_style_query_references)
- published_references.append(entry.references.data(), entry.references.size());
- }
- if (published_references.size() > 1) {
- quick_sort(published_references);
- size_t unique_count = 0;
- for (size_t index = 0; index < published_references.size(); ++index) {
- if (index == 0 || published_references[index] != published_references[unique_count - 1])
- published_references[unique_count++] = published_references[index];
- }
- published_references.shrink(unique_count);
- }
- auto published_extra_names_match = consumer_data
- ? published_pseudo_element_data == consumer_data->published_pseudo_element_data
- && published_references == consumer_data->published_references
- : published_pseudo_element_data.is_empty() && published_references.is_empty();
- if (published_names == m_published_custom_property_names && published_extra_names_match)
- return;
- // An environment that declares the same names as the published one, with other values, is the
- // same index entry: a root whose declarations moved value hands out its names again otherwise.
- if (published_extra_names_match
- && published_names.data && m_published_custom_property_names.data
- && published_names.uses_var_css_function == m_published_custom_property_names.uses_var_css_function
- && published_names.uses_custom_function == m_published_custom_property_names.uses_custom_function
- && published_names.data->declares_same_names(*m_published_custom_property_names.data)) {
- m_published_custom_property_names = move(published_names);
- return;
- }
- CSS::record_element_custom_property_names(*this, published_names.data.ptr(), published_pseudo_element_data, published_references, m_style_uses_var_css_function, m_style_uses_custom_function);
- m_published_custom_property_names = move(published_names);
- if (!published_pseudo_element_data.is_empty() || !published_references.is_empty()) {
- auto& rare_data = ensure_element_rare_data();
- if (!rare_data.custom_property_consumer_data)
- rare_data.custom_property_consumer_data = make<RareData::CustomPropertyConsumerData>();
- rare_data.custom_property_consumer_data->published_pseudo_element_data = move(published_pseudo_element_data);
- rare_data.custom_property_consumer_data->published_references = move(published_references);
- } else if (consumer_data) {
- consumer_data->published_pseudo_element_data.clear();
- consumer_data->published_references.clear();
- }
-}
-
// The anchor names of one tree scope, and the identity the layout arena names that scope by: the
// shadow host of the scope's root, or nothing for the document tree.
struct AnchorNameScope {
@@ -2265,7 +1862,7 @@ void Element::update_anchor_name_registry(CSS::ComputedValues const* old_compute
document().record_partial_relayout_escape(PartialRelayoutEscapeReason::AnchorNamesUnregisteredByStyleChange);
}
-RefPtr<CSS::CustomPropertyData const> Element::custom_property_environment_of_engine_record(Layout::BegunRead const& read, CSS::StyleRecordID style_record, bool& installable) const
+RefPtr<CSS::CustomPropertyData const> Element::custom_property_environment_of_engine_record(Layout::BegunRead const& read, u64 identity, bool& installable) const
{
auto& style_computer = document().style_computer();
RefPtr<CSS::CustomPropertyData const> inherited_data;
@@ -2273,7 +1870,6 @@ RefPtr<CSS::CustomPropertyData const> Element::custom_property_environment_of_en
if (auto parent_data = parent->custom_property_data())
inherited_data = parent_data->inheritable(read, document());
}
- auto identity = style_computer.style_engine().style_record_custom_property_environment(read, style_record);
installable = true;
if (identity == (inherited_data ? inherited_data->identity() : 0))
return inherited_data;
@@ -2282,8 +1878,7 @@ RefPtr<CSS::CustomPropertyData const> Element::custom_property_environment_of_en
return data;
}
-// What the container conditions the style engine decided for the record read of the containers,
-// recorded as a C++ evaluation of the same conditions records it.
+// What the container conditions the style engine decided for the record read of the containers.
static void record_engine_container_query_effects(Layout::BegunRead const& read, Element& element)
{
auto& style_computer = element.document().style_computer();
@@ -2325,160 +1920,187 @@ static void record_engine_container_query_effects(Layout::BegunRead const& read,
element.set_style_depends_on_size_container_query();
if (taken.depends_on_style)
element.set_style_depends_on_style_container_query();
- CSS::ComputedValuesFFI::rust_style_query_dependencies_take(taken.style_query_references, &element, [](void* context, CSS::ComputedValuesFFI::FfiUtf16View name) {
- static_cast<Element*>(context)->record_style_query_custom_property_reference({}, Utf16FlyString::from_utf16({ reinterpret_cast<char16_t const*>(name.utf16), name.length }));
- });
}
-// Which animations an element references is an index StyleEngine keeps, in the same shape as the anchor-name registry:
-// nothing about selector matching can say it, and without it a `@keyframes` rule cannot find the elements running the
-// animation it describes.
-static void update_animation_name_index(Element& element, CSS::ComputedValues const* old_style, CSS::ComputedValues const& new_style)
+// NB: The render side noted that the element holds the record as it published it, so the swap tells it nothing, but
+// where the installation cleared the element's styles before, which the render side learns after the swap. The
+// generations of the element's ancestors move with its main-side effects, as only those move what an animation
+// reads of the subtree beside its own element.
+void Element::note_subtree_style_moved()
{
- auto animation_names = new_style.animation_names();
- if (old_style ? old_style->animation_names() != animation_names : !animation_names.is_empty())
- CSS::record_element_animation_names(element, animation_names);
+ // NB: Within an installation, an ancestor that holds its generation already had its own ancestors take it too.
+ auto const generation = document().style_computer().subtree_style_generation_for_move();
+ for (auto* element = this; element && element->m_animation_subtree_style_generation != generation; element = element->parent_or_shadow_host_element())
+ element->m_animation_subtree_style_generation = generation;
}
-CSS::RequiredInvalidationAfterStyleChange Element::apply_engine_computed_style_record(Layout::BegunRead const& read, CSS::StyleRecordID new_style_record, EnginePseudoElementRecords const& pseudo_element_records, bool uses_substitution, u8 record_reads, u32 explicitly_inherited_non_inherited_style_groups, bool& did_change_custom_properties, DisplayNoneChange display_none_change, EngineRecordDamages const* engine_record_damages)
+void Element::swap_in_style_record(Layout::BegunRead const& read, Optional<CSS::PseudoElement> pseudo_element, void const* record)
{
- VERIFY(parent());
- auto old_style_record = style_record_identity();
- auto& counters = document().style_invalidation_counters();
+ if (pseudo_element.has_value()) {
+ VERIFY(is_synthetic_pseudo_element(*pseudo_element));
+ if (record)
+ ensure_synthetic_pseudo_element(*pseudo_element).swap_in_style_record(read, record);
+ else if (auto existing_pseudo_element = get_synthetic_pseudo_element(*pseudo_element); existing_pseudo_element.has_value())
+ existing_pseudo_element->clear_computed_style();
+ return;
+ }
+ ++m_animation_style_generation;
+ VERIFY(record);
+ m_installed_style = CSS::InstalledStyle { record };
+ auto const style_record = m_installed_style.record();
+ // NB: The render side installed the record in a box it styles itself, which the box adopts.
+ if (auto* layout_node = unsafe_layout_node(read))
+ layout_node->set_style_record_identity(style_record);
+}
+
+// The custom-property environment of a style record: what the element inherits, or its own custom declarations over
+// that.
+RefPtr<CSS::CustomPropertyData const> Element::style_custom_property_environment(Layout::BegunRead const& read, CSS::InstalledStyle const& style) const
+{
+ auto const identity = style.custom_property_environment();
+ bool installable = false;
+ auto data = custom_property_environment_of_engine_record(read, identity, installable);
+ if (installable)
+ return data;
+ // NB: Where the animations of the element's parent sample custom properties, the parent holds their composition
+ // over the environment the style engine resolved the element's over. The element inherits the composition, and
+ // its own declarations stand over it, as when the animations move the parent's environment.
+ auto parent = DOM::AbstractElement { const_cast<Element&>(*this) }.element_to_inherit_style_from();
+ VERIFY(parent.has_value());
auto& style_computer = document().style_computer();
- ++counters.engine_computed_style_records;
-
- // The engine substituted custom properties into the record's winners the way a C++
- // computation notes it read them, even if the custom-property environment stayed the same.
- if (uses_substitution)
- m_style_uses_var_css_function = true;
- // A tree-counting function in the record's winners reads the element's place among its
- // siblings, so a change among them has to reach the element again.
- if (record_reads & to_underlying(CSS::StyleEngineFFI::FfiNodeRecordReads::SiblingPosition))
- set_style_uses_tree_counting_function();
- // An inherit() reads the parent's custom-property environment, so a move of it has to reach
- // the element again.
- if (record_reads & to_underlying(CSS::StyleEngineFFI::FfiNodeRecordReads::InheritFunction))
- set_style_uses_inherit_css_function();
- // An if() reads the media features and the element's custom-property environment, so a change
- // of either has to reach the element again.
- if (record_reads & to_underlying(CSS::StyleEngineFFI::FfiNodeRecordReads::IfFunction))
- set_style_uses_if_css_function();
- // A custom function call reads the definitions its scope sees and whatever their declarations
- // read, so a change of either has to reach the element again.
- if (record_reads & to_underlying(CSS::StyleEngineFFI::FfiNodeRecordReads::CustomFunction))
- set_style_uses_custom_function();
- // An attr() in the record's winners, or in the custom properties the element declares, reads
- // the element's attributes, so an attribute change has to reach the element again. An engine
- // record only ever sets the flag: one that stops reading attributes leaves it set, and the
- // element's attribute changes keep reaching it until C++ computes its style and clears the flag.
- if (record_reads & to_underlying(CSS::StyleEngineFFI::FfiNodeRecordReads::Attributes)) {
- m_style_uses_attr_css_function = true;
- // An element standing for its shadow host's pseudo-element reads the host's attributes.
- if (associated_shadow_host_pseudo_element().has_value()) {
- if (auto host = root().parent_or_shadow_host_element())
- host->set_style_uses_attr_css_function();
- }
+ auto& style_engine = style_computer.style_engine();
+ RefPtr<CSS::CustomPropertyData const> inherited_data;
+ if (auto parent_data = parent->custom_property_data())
+ inherited_data = parent_data->inheritable(read, document());
+ auto const parent_identity = parent->installed_style().custom_property_environment();
+ if (identity == CSS::StyleEngineFFI::style_engine_inheritable_custom_property_environment(style_engine.host(), &read, parent_identity))
+ return inherited_data;
+ auto declarations = style_computer.engine_custom_property_declarations_over(read, identity, inherited_data);
+ VERIFY(declarations);
+ return declarations;
+}
+
+CSS::RequiredInvalidationAfterStyleChange Element::compose_style_pseudo_element_records(Layout::BegunRead const& read, u16 composed, u16 transition_steps, Array<CSS::InstalledStyle, computed_pseudo_elements.size()> const& before_change_styles)
+{
+ auto& style_computer = document().style_computer();
+ CSS::RequiredInvalidationAfterStyleChange invalidation;
+ for (size_t i = 0; i < computed_pseudo_elements.size(); ++i) {
+ auto pseudo_element = computed_pseudo_elements[i];
+ auto bit = static_cast<u16>(1 << to_underlying(pseudo_element));
+ if (!(composed & bit) || !has_style(pseudo_element))
+ continue;
+ // The transition step of a pseudo-element runs where its record is installed, against the record it moved
+ // away from.
+ auto const& before_change = before_change_styles[i];
+ style_computer.compose_installed_engine_record(read, { *this, pseudo_element }, before_change);
+ if ((transition_steps & bit) && before_change)
+ invalidation |= style_computer.run_transition_step_for_installed_record(read, { *this, pseudo_element }, before_change);
}
+ apply_computed_pseudo_element_styles_to_layout_nodes_if_needed(read, invalidation);
+ return invalidation;
+}
- // The parent's groups the record read through an explicit `inherit`, marked the way a C++
- // computation marks them, so that a later change to them reaches this element again.
- if (explicitly_inherited_non_inherited_style_groups != 0)
- parent()->add_children_explicitly_inherited_non_inherited_style_groups(explicitly_inherited_non_inherited_style_groups == NumericLimits<u32>::max() ? CSS::ComputedValues::all_style_groups : explicitly_inherited_non_inherited_style_groups);
+void Element::apply_style_main_effects(Layout::BegunRead const& read, CSS::MainEffects effects, CSS::LayoutTreeRebuildRoot rebuild_root, CSS::RequiredInvalidationAfterStyleChange const& invalidation, CSS::InstalledStyle const& old_style)
+{
+ auto& style_computer = document().style_computer();
+ auto new_computed_values = computed_style();
+ VERIFY(new_computed_values);
+ auto old_computed_values = old_style ? style_computer.computed_style_record_view(old_style) : CSS::ComputedStyleRecordView {};
+ CSS::ComputedValues const* old_values = old_computed_values ? &*old_computed_values : nullptr;
- record_engine_container_query_effects(read, *this);
+ if (has_flag(effects, CSS::MainEffects::ContainerEffects))
+ record_engine_container_query_effects(read, *this);
- // The environment the record was published with: what the element inherits, or what the
- // engine resolved its own custom declarations to over that.
- auto install_custom_property_environment = [&] {
- bool installable = false;
- auto data = custom_property_environment_of_engine_record(read, new_style_record, installable);
- VERIFY(installable);
- set_custom_property_data({}, data);
- };
- auto old_computed_values = computed_style();
- if (!old_computed_values) {
- // The element's first style: what a C++ first computation installs beside the record,
- // with the pseudo-element styles it still computes.
- install_custom_property_environment();
- set_computed_style({}, new_style_record);
- auto new_computed_values = computed_style();
- update_anchor_name_registry(nullptr, *new_computed_values);
- update_animation_name_index(*this, nullptr, *new_computed_values);
- if (is_document_element())
- style_computer.update_root_element_font_metrics(*new_computed_values);
- counters.element_computed_style_changes++;
- auto invalidation = CSS::RequiredInvalidationAfterStyleChange::full();
- invalidation |= recompute_pseudo_element_styles(read, did_change_custom_properties, false, nullptr, &pseudo_element_records, engine_record_damages);
- publish_custom_property_names();
- apply_computed_style_to_layout_node_if_needed(read, invalidation);
- return invalidation;
- }
- // A later pass of this style update may start the element's transitions in C++, against the
- // style the element held before the update rather than this record, as a C++ computation of
- // this pass would have recorded.
- if (old_style_record != new_style_record)
- style_computer.record_transition_baseline_for_later_passes({ *this }, old_style_record);
- // What is left to decide is what the layout tree and paint need, and the anchor and animation
- // names the record registers; the animation plan the record decides is the host's to apply once
- // the batch is installed. The record itself may be the one the element holds, when the reaction
- // moved only its pseudo-elements. Its custom properties may have moved with it: the engine
- // resolves the element's own declarations, and a moved environment is what its descendants
- // react to.
- CSS::StyleComputer::ComputedStyleInvalidation result;
- if (new_style_record != old_style_record) {
+ // The environment the record was published with: what the element inherits, or what the engine resolved its own
+ // custom declarations to over that, and those of the pseudo-elements over the element's.
+ if (has_flag(effects, CSS::MainEffects::CustomProperties)) {
auto current_environment = custom_property_data({});
- if (current_environment && current_environment->is_animation_overlay_for({ *this }))
+ if (current_environment && custom_property_data_is_animation_overlay({}))
current_environment = current_environment->parent();
auto const current_identity = current_environment ? current_environment->identity() : 0;
- if (current_identity != style_computer.style_engine().style_record_custom_property_environment(read, new_style_record)) {
- install_custom_property_environment();
- did_change_custom_properties = true;
+ if (!old_values || current_identity != installed_style().custom_property_environment())
+ set_custom_property_data({}, style_custom_property_environment(read, installed_style()));
+ for (auto pseudo_element : computed_pseudo_elements) {
+ if (auto const& pseudo_style = installed_style(pseudo_element); pseudo_style)
+ install_engine_pseudo_element_custom_property_data(read, pseudo_element, pseudo_style.custom_property_environment());
}
- auto new_computed_values = style_computer.computed_style_record_view(read, new_style_record);
- VERIFY(new_computed_values);
- bool const had_layout_node = !!unsafe_layout_node(read);
- DOM::AbstractElement abstract_element { *this };
- CSS::StyleEngine::StyleRecordDelta style_record_delta {
- .old_style_record = old_style_record,
- .new_style_record = new_style_record,
- };
- Optional<u32> answered_damage;
- if (engine_record_damages && engine_record_damages->element.has_value() && engine_record_damages->element->answers(old_style_record, new_style_record))
- answered_damage = engine_record_damages->element->packed;
- result = compute_required_invalidation_with_cache(read, style_computer, *new_computed_values, had_layout_node, abstract_element, style_record_delta, answered_damage);
- if (result.any_computed_value_changed)
- counters.element_computed_style_changes++;
- set_computed_style({}, new_style_record);
- update_anchor_name_registry(&*old_computed_values, *new_computed_values);
- update_animation_name_index(*this, &*old_computed_values, *new_computed_values);
- if (is_document_element()) {
- // Root-relative units read document-global font metrics rather than inherited style.
- // Every descendant must recompute when they move.
- auto const root_font_metrics_before = style_computer.root_element_font_metrics();
- auto const root_font_metrics_depended_on_viewport_before = style_computer.root_element_font_metrics_depend_on_viewport_metrics();
- style_computer.update_root_element_font_metrics(*new_computed_values);
- if (root_font_metrics_before != style_computer.root_element_font_metrics()
- || root_font_metrics_depended_on_viewport_before != style_computer.root_element_font_metrics_depend_on_viewport_metrics()) {
- document().bump_style_environment_version();
- result.invalidation.recompute_descendant_styles = true;
+ }
+
+ if (has_flag(effects, CSS::MainEffects::AnchorNames))
+ update_anchor_name_registry(old_values, *new_computed_values);
+
+ if (has_flag(effects, CSS::MainEffects::RootFontMetrics) && is_document_element()) {
+ // Root-relative units read document-global font metrics rather than inherited style.
+ auto const root_font_metrics_before = style_computer.root_element_font_metrics();
+ auto const root_font_metrics_depended_on_viewport_before = style_computer.root_element_font_metrics_depend_on_viewport_metrics();
+ style_computer.update_root_element_font_metrics(*new_computed_values);
+ if (old_values
+ && (root_font_metrics_before != style_computer.root_element_font_metrics()
+ || root_font_metrics_depended_on_viewport_before != style_computer.root_element_font_metrics_depend_on_viewport_metrics()))
+ document().bump_style_environment_version();
+ }
+
+ // Children that wait to arrive in a display:none subtree may be revealed as the element stops being display:none.
+ if (has_flag(effects, CSS::MainEffects::RevealWaiting) && (child_style_arrivals_wait() || descendant_style_arrival_pending())
+ && !m_installed_style.display_is_none())
+ CSS::record_waiting_children_may_be_revealed(*this);
+
+ if (has_flag(effects, CSS::MainEffects::SvgReferences)) {
+ // The resources an SVG graphics element's `mask`, `clip-path`, `fill` and `stroke` name are published beside its
+ // attributes for the layout tree build to resolve, so they follow every record the element takes.
+ if (is<SVG::SVGGraphicsElement>(*this)) {
+ Layout::publish_svg_style_references(*this);
+ if (old_style && Layout::svg_style_references_differ(old_style, m_installed_style))
+ set_needs_layout_tree_rebuild(read, SetNeedsLayoutTreeUpdateReason::SVGResourceReferenceChange, CSS::LayoutTreeRebuildRoot::Self);
+ }
+ if (auto* svg_element = as_if<SVG::SVGElement>(*this))
+ svg_element->note_svg_paint_resource_description_may_have_changed();
+ }
+
+ // https://drafts.csswg.org/scroll-animations-1/#timeline-scoping
+ if (has_flag(effects, CSS::MainEffects::Timelines))
+ document().did_change_timeline_declarations();
+
+ if (has_flag(effects, CSS::MainEffects::FormControl))
+ computed_properties_changed();
+
+ // The host styles the boxes of the element and its pseudo-elements the render side left to it.
+ if (has_flag(effects, CSS::MainEffects::HostBoxFacts)) {
+ apply_computed_style_to_layout_node_if_needed(read, invalidation);
+ return;
+ }
+
+ if (has_flag(effects, CSS::MainEffects::ScrollSnap) && invalidation.needs_scroll_container_resnap)
+ document().schedule_scroll_container_resnap();
+
+ if (has_flag(effects, CSS::MainEffects::Rebuild))
+ set_needs_layout_tree_rebuild(read, SetNeedsLayoutTreeUpdateReason::StyleChange, rebuild_root);
+
+ if (has_flag(effects, CSS::MainEffects::Images)) {
+ if (auto* layout_node = unsafe_layout_node(read))
+ layout_node->attach_style_resources();
+ for_each_synthetic_pseudo_element([&](CSS::PseudoElement, SyntheticPseudoElement const& pseudo_element) {
+ if (auto* layout_node = pseudo_element.unsafe_layout_node(read))
+ layout_node->attach_style_resources();
+ });
+ }
+
+ if (has_flag(effects, CSS::MainEffects::Highlights) && invalidation.repaint_highlights && !invalidation.needs_layout_tree_rebuild()) {
+ Painting::push_highlight_pseudo_styles(*this);
+ // NB: A display:contents element has no box of its own. Invalidate the nearest painted ancestor's subtree so
+ // cached text commands take the new highlight.
+ for (Node const* node = this; node; node = node->parent_or_shadow_host()) {
+ if (auto* layout_node = node->unsafe_layout_node(read); layout_node && Painting::has_committed_box(*layout_node)) {
+ Painting::set_needs_repaint_in_subtree(*layout_node);
+ break;
}
}
- if (display_none_change == DisplayNoneChange::Apply)
- apply_display_none_change(read, DisplayNoneState::of(*old_computed_values));
}
- // The pseudo-element records the engine settled beside this one install with it.
- result.invalidation |= recompute_pseudo_element_styles(read, did_change_custom_properties, old_computed_values->display().is_list_item(), &*old_computed_values, &pseudo_element_records, engine_record_damages);
- publish_custom_property_names();
- if (new_style_record != old_style_record || did_change_custom_properties)
- invalidate_descendant_styles_depending_on_style_container_query();
- apply_computed_style_to_layout_node_if_needed(read, result.invalidation);
- return result.invalidation;
}
-Element::DisplayNoneState Element::DisplayNoneState::of(CSS::ComputedValues const& computed_values)
+Element::DisplayNoneState Element::DisplayNoneState::of(CSS::ComputedValues const& computed_values, CSS::InstalledStyle const& style)
{
- return { computed_values.display().is_none(), computed_values.base_values().display().is_none() };
+ return { computed_values.display().is_none(), style.display_is_none_ignoring_animations() };
}
Optional<Element::DisplayNoneState> Element::display_none_state() const
@@ -2486,10 +2108,10 @@ Optional<Element::DisplayNoneState> Element::display_none_state() const
auto computed_values = computed_style();
if (!computed_values)
return {};
- return DisplayNoneState::of(*computed_values);
+ return DisplayNoneState::of(*computed_values, installed_style());
}
-void Element::apply_display_none_change(Layout::BegunRead const& read, DisplayNoneState before)
+void Element::apply_display_none_change(DisplayNoneState before)
{
auto after = display_none_state();
VERIFY(after.has_value());
@@ -2502,31 +2124,6 @@ void Element::apply_display_none_change(Layout::BegunRead const& read, DisplayNo
return TraversalDecision::Continue;
});
}
- // NB: Clear hidden descendant styles so they cannot become transition before-change styles.
- // Descendants needed by SVG resources are scheduled for recomputation; other descendants
- // rematerialize on a CSSOM read or when the subtree becomes visible again.
- if (!before.display_is_none && after->display_is_none)
- clear_computed_styles_from_display_none_descendants(read);
-}
-
-bool Element::has_referenceable_svg_descendant() const
-{
- bool found = false;
- // NB: The traversal only reads the subtree.
- const_cast<Element&>(*this).for_each_shadow_including_descendant([&found](auto const& node) {
- auto const* element = as_if<Element>(node);
- if (!element)
- return TraversalDecision::Continue;
- // NB: A resource keeps its style, and so do the elements it inherits from, so an unstyled subtree holds none.
- if (!element->has_style())
- return TraversalDecision::SkipChildrenAndContinue;
- if (auto const* svg_element = as_if<SVG::SVGElement>(*element); svg_element && svg_element->is_referenceable_in_display_none_subtree()) {
- found = true;
- return TraversalDecision::Break;
- }
- return TraversalDecision::Continue;
- });
- return found;
}
void Element::clear_computed_styles_from_display_none_descendants(Layout::BegunRead const& read)
@@ -2543,12 +2140,11 @@ void Element::clear_computed_styles_from_display_none_descendants(Layout::BegunR
if (element->is_connected() && unregister_current_anchor_names(*element, element->root()))
element->document().record_partial_relayout_escape(PartialRelayoutEscapeReason::AnchorNamesUnregisteredByStyleChange);
- // The layout tree is torn down after the style transaction. Keep its style alive until then without
+ // The layout tree is torn down after the style update. Keep its style alive until then without
// retaining the record as the descendant's current computed style.
if (auto* layout_node = element->unsafe_layout_node(read))
layout_node->pin_style_record_for_detachment();
element->m_installed_style = {};
- CSS::StyleEngineFFI::style_engine_set_held_style_record(element->document().style_computer().style_engine().host(), element->style_node_id(), {});
// NB: SVG resources can still affect rendering when a DOM ancestor has display:none.
// Restore their styles in this style update, so painting never needs to materialize
@@ -3066,12 +2662,19 @@ void Element::did_update_inline_style()
document().mark_style_attribute_dirty(*this);
m_style_attribute_is_dirty = true;
// The style attribute is appended when it is next synchronized, but a selector query may skip this subtree before.
- add_to_subtree_attribute_name_filter(attribute_name_filter_bit(HTML::AttributeNames::style));
+ add_to_subtree_name_filter(name_filter_bit(HTML::AttributeNames::style));
queue_mutation_record(MutationType::attributes, HTML::AttributeNames::style, {}, old_value, {}, {}, nullptr, nullptr);
if (!document().suppresses_attribute_style_invalidation())
CSS::record_element_declarations_changed(*this, CSS::ElementDeclarationKind::InlineStyle, had_style_attribute, true);
+ bump_dom_tree_version_for_attribute_change();
+}
+
+void Element::bump_dom_tree_version_for_attribute_change()
+{
+ auto version_before = dom_tree_version();
bump_dom_tree_version();
+ document().keep_element_tree_positions_across_attribute_change(version_before);
}
void Element::synchronize_style_attribute() const
@@ -3216,7 +2819,8 @@ int Element::client_top() const
// 2. Return the computed value of the border-top-width property
// plus the height of any scrollbar rendered between the top padding edge and the top border edge,
// ignoring any transforms that apply to the element and its ancestors.
- auto const& border_top = style_group<CSS::ComputedValues::BorderValues>()->border_top_value();
+ // NB: Only the side's style and width are read, so its color resolves against nothing.
+ auto const border_top = style_group<CSS::ComputedValues::BorderValues>()->border_top_value(Color::Transparent);
if (border_top.line_style == CSS::LineStyle::None || border_top.line_style == CSS::LineStyle::Hidden)
return 0;
return CSS::unscaled(border_top.width, CSS::effective_zoom(*this)).to_int();
@@ -3241,7 +2845,8 @@ int Element::client_left() const
// 2. Return the computed value of the border-left-width property
// plus the width of any scrollbar rendered between the left padding edge and the left border edge,
// ignoring any transforms that apply to the element and its ancestors.
- auto const& border_left = style_group<CSS::ComputedValues::BorderValues>()->border_left_value();
+ // NB: Only the side's style and width are read, so its color resolves against nothing.
+ auto const border_left = style_group<CSS::ComputedValues::BorderValues>()->border_left_value(Color::Transparent);
if (border_left.line_style == CSS::LineStyle::None || border_left.line_style == CSS::LineStyle::Hidden)
return 0;
return CSS::unscaled(border_left.width, CSS::effective_zoom(*this)).to_int();
@@ -3376,6 +2981,10 @@ void Element::inserted()
}
play_or_cancel_animations_after_display_property_change();
+
+ // A shadow root's counter style names pass on to the scope its host is in, which a move of the host can change.
+ if (m_shadow_root)
+ document().note_counter_style_scope_to_settle(*m_shadow_root);
}
void Element::removed_from(IsSubtreeRoot is_subtree_root, Node* old_ancestor, Node& old_root)
@@ -3408,10 +3017,18 @@ void Element::removed_from(IsSubtreeRoot is_subtree_root, Node* old_ancestor, No
play_or_cancel_animations_after_display_property_change();
exit_fullscreen_on_element_removal();
- replace_style_record(0);
- for_each_synthetic_pseudo_element([&](CSS::PseudoElement pseudo_element_type, SyntheticPseudoElement&) {
- set_computed_style(pseudo_element_type, 0);
+ if (has_style()) {
+ Layout::ForcedReadScope read { document() };
+ replace_installed_style(read, {});
+ }
+ for_each_synthetic_pseudo_element([&](CSS::PseudoElement, SyntheticPseudoElement& pseudo_element) {
+ note_subtree_style_moved();
+ pseudo_element.clear_computed_style();
});
+
+ // A shadow root's counter style names pass on to the scope its host is in, which a move of the host can change.
+ if (m_shadow_root)
+ document().note_counter_style_scope_to_settle(*m_shadow_root);
}
void Element::unregister_anchor_names_before_leaving_tree_scope(Badge<Node>, Node& tree_root)
@@ -3440,15 +3057,19 @@ void Element::moved_from(IsSubtreeRoot is_subtree_root, GC::Ptr<Node> old_ancest
if (is_subtree_root == IsSubtreeRoot::Yes)
HTML::FormAssociatedElement::reposition_associated_elements_after_move({}, *this);
+
+ // A shadow root's counter style names pass on to the scope its host is in, which a move of the host can change.
+ if (m_shadow_root)
+ document().note_counter_style_scope_to_settle(*m_shadow_root);
}
void Element::children_changed(ChildrenChangedMetadata const& metadata)
{
Node::children_changed(metadata);
- // NB: The style transaction that flew counted the children as they were when it was sealed, and a child whose
+ // NB: The style update that flew counted the children as they were when it was sealed, and a child whose
// style it found to read its place among them is known to only once its drain installs that style.
- if (document().has_flown_style_transaction()) [[unlikely]]
+ if (document().has_flown_style_update()) [[unlikely]]
document().style_computer().style_engine().note_children_changed_beside_flown_transaction(style_node_id());
if (child_style_uses_tree_counting_function())
document().style_computer().style_engine().restyle_children_reading_sibling_position(*this);
@@ -3460,6 +3081,17 @@ void Element::children_changed(ChildrenChangedMetadata const& metadata)
}
}
+void Element::record_style_environment_change()
+{
+ document().bump_style_environment_version();
+
+ // An element names its own environment input; StyleEngine routes any consequences of its changed facts
+ // separately. The environment version this bumped is a published document input, so what the element's row
+ // needs is a drive against the new one, which the engine can do for itself. What the host knows that the engine
+ // does not is only WHICH nodes to drive, and that is what the reaction carries.
+ document().style_computer().style_engine().record_derived_element_style_input_change(style_node_id(), CSS::StyleEngine::PublishedStyle | CSS::StyleEngine::RecomputeStyle);
+}
+
void Element::set_style_node_id(CSS::StyleNodeID style_node_id)
{
if (m_style_node_id == style_node_id)
@@ -3487,17 +3119,8 @@ void Element::set_style_node_id(CSS::StyleNodeID style_node_id)
pseudo_element.publish_scroll_offset();
});
}
- // A newly minted identity holds none of what the element and its pseudo-elements held under its previous one.
- if (style_node_id != 0) {
- if (!!m_installed_style.record())
- CSS::StyleEngineFFI::style_engine_set_held_style_record(style_engine.host(), style_node_id, m_installed_style.record().value());
- for_each_synthetic_pseudo_element([&](CSS::PseudoElement type, SyntheticPseudoElement const& pseudo_element) {
- if (auto style_record = pseudo_element.style_record_identity(); !!style_record)
- CSS::StyleEngineFFI::style_engine_set_held_pseudo_style_record(style_engine.host(), style_node_id, to_underlying(type), style_record.value());
- });
- }
- if (style_node_id != 0)
- publish_children_explicitly_inherit_mark();
+ // NB: A newly minted identity holds no style on the render side, whatever the element and its pseudo-elements
+ // still hold: the render side styles the element as it arrives, and swaps in what it computed.
}
// The top layer is one of the few element facts the tree build reads that moves during the element's lifetime, so the
@@ -3825,10 +3448,10 @@ bool Element::is_potentially_scrollable(TreatOverflowClipOnBodyParentAsOverflowH
return false;
// - body’s parent element’s computed value of the overflow-x or overflow-y properties is neither visible nor clip.
- auto const* parent_box_values = parent_element()->style_group<CSS::ComputedValues::BoxValues>();
- VERIFY(parent_box_values);
- auto parent_overflow_x = static_cast<CSS::Overflow>(parent_box_values->overflow_x);
- auto parent_overflow_y = static_cast<CSS::Overflow>(parent_box_values->overflow_y);
+ auto parent_reset_bits = parent_element()->style_reset_bits();
+ VERIFY(parent_reset_bits.has_value());
+ auto parent_overflow_x = CSS::overflow_x_from_reset_bits(*parent_reset_bits);
+ auto parent_overflow_y = CSS::overflow_y_from_reset_bits(*parent_reset_bits);
if (parent_overflow_x == CSS::Overflow::Visible || parent_overflow_y == CSS::Overflow::Visible)
return false;
// NOTE: When treating 'overflow:clip' as 'overflow:hidden', we can never fail this condition
@@ -3836,9 +3459,9 @@ bool Element::is_potentially_scrollable(TreatOverflowClipOnBodyParentAsOverflowH
return false;
// - body’s computed value of the overflow-x or overflow-y properties is neither visible nor clip.
- auto const* box_values = style_group<CSS::ComputedValues::BoxValues>();
- VERIFY(box_values);
- if (first_is_one_of(static_cast<CSS::Overflow>(box_values->overflow_x), CSS::Overflow::Visible, CSS::Overflow::Clip) || first_is_one_of(static_cast<CSS::Overflow>(box_values->overflow_y), CSS::Overflow::Visible, CSS::Overflow::Clip))
+ auto reset_bits = style_reset_bits();
+ VERIFY(reset_bits.has_value());
+ if (first_is_one_of(CSS::overflow_x_from_reset_bits(*reset_bits), CSS::Overflow::Visible, CSS::Overflow::Clip) || first_is_one_of(CSS::overflow_y_from_reset_bits(*reset_bits), CSS::Overflow::Visible, CSS::Overflow::Clip))
return false;
return true;
@@ -3847,14 +3470,14 @@ bool Element::is_potentially_scrollable(TreatOverflowClipOnBodyParentAsOverflowH
bool Element::is_scroll_container() const
{
// NB: We should only call this if we know that computed_properties has already been computed
- auto const* box_values = style_group<CSS::ComputedValues::BoxValues>();
- VERIFY(box_values);
+ auto reset_bits = style_reset_bits();
+ VERIFY(reset_bits.has_value());
if (is_document_element())
return true;
- return Layout::overflow_value_makes_box_a_scroll_container(static_cast<CSS::Overflow>(box_values->overflow_x))
- || Layout::overflow_value_makes_box_a_scroll_container(static_cast<CSS::Overflow>(box_values->overflow_y));
+ return Layout::overflow_value_makes_box_a_scroll_container(CSS::overflow_x_from_reset_bits(*reset_bits))
+ || Layout::overflow_value_makes_box_a_scroll_container(CSS::overflow_y_from_reset_bits(*reset_bits));
}
// https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
@@ -5019,10 +4642,11 @@ bool Element::is_hidden(Layout::BegunRead const& read) const
// The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes and text sequences as normal.
if (!layout_node(read) && !has_display_contents())
return true;
- auto const* inherited_box_values = style_group<CSS::ComputedValues::InheritedBoxValues>();
- if (inherited_box_values
- && (static_cast<CSS::Visibility>(inherited_box_values->visibility) != CSS::Visibility::Visible
- || static_cast<CSS::ContentVisibility>(inherited_box_values->content_visibility) == CSS::ContentVisibility::Hidden))
+ auto const* inherited_values = style_inherited_set_values();
+ if (inherited_values && CSS::visibility_from_inherited_bits(inherited_values->bits) != CSS::Visibility::Visible)
+ return true;
+ auto const* misc_layout_values = style_group<CSS::ComputedValues::MiscLayoutValues>();
+ if (misc_layout_values && static_cast<CSS::ContentVisibility>(misc_layout_values->content_visibility) == CSS::ContentVisibility::Hidden)
return true;
for (ParentNode const* self_or_ancestor = this; self_or_ancestor; self_or_ancestor = self_or_ancestor->parent_or_shadow_host()) {
if (self_or_ancestor->is_element()) {
@@ -5031,9 +4655,9 @@ bool Element::is_hidden(Layout::BegunRead const& read) const
auto const* box_values = element.style_group<CSS::ComputedValues::BoxValues>();
if (box_values && CSS::display_from_ffi_display(box_values->display).is_none())
return true;
- auto const* ancestor_inherited_box_values = element.style_group<CSS::ComputedValues::InheritedBoxValues>();
- if (ancestor_inherited_box_values
- && static_cast<CSS::ContentVisibility>(ancestor_inherited_box_values->content_visibility) == CSS::ContentVisibility::Hidden)
+ auto const* ancestor_misc_layout_values = element.style_group<CSS::ComputedValues::MiscLayoutValues>();
+ if (ancestor_misc_layout_values
+ && static_cast<CSS::ContentVisibility>(ancestor_misc_layout_values->content_visibility) == CSS::ContentVisibility::Hidden)
return true;
auto aria_hidden = element.aria_hidden();
if (aria_hidden.has_value() && aria_hidden->utf16_view() == u"true"sv)
@@ -5093,8 +4717,8 @@ bool Element::exclude_from_accessibility_tree() const
return true;
// visibility:hidden
- if (auto const* box_values = style_group<CSS::ComputedValues::InheritedBoxValues>();
- box_values && static_cast<CSS::Visibility>(box_values->visibility) != CSS::Visibility::Visible)
+ if (auto const* inherited_values = style_inherited_set_values();
+ inherited_values && CSS::visibility_from_inherited_bits(inherited_values->bits) != CSS::Visibility::Visible)
return true;
// Elements with none or presentation as the first role in the role attribute. However, their exclusion is conditional. In addition, the element's descendants and text content are generally included. These exceptions and conditions are documented in the presentation (role) section.
@@ -5404,8 +5028,8 @@ void Element::set_custom_element_state(CustomElementState state)
if (m_custom_element_state == state)
return;
// Several custom element states are `:defined` and several are not, so the state moving is not
- // the same as `:defined` moving. Saying it moved when it did not has the engine journal a change
- // from a value the element never held, and the real change later cancels against it.
+ // the same as `:defined` moving. Saying it moved when it did not has the engine note a change
+ // from a value the element never held.
auto was_defined = is_defined();
m_custom_element_state = state;
if (was_defined == is_defined())
@@ -5571,10 +5195,10 @@ CSS::ComputedStyleRecordView Element::computed_style(Optional<CSS::PseudoElement
CSS::InstalledStyle const& Element::installed_style(Optional<CSS::PseudoElement> pseudo_element_type) const
{
if (pseudo_element_type.has_value()) {
- static CSS::InstalledStyle const none;
+ static NeverDestroyed<CSS::InstalledStyle const> none;
if (auto pseudo_element = get_pseudo_element(*pseudo_element_type); pseudo_element.has_value())
return pseudo_element->installed_style();
- return none;
+ return *none;
}
return m_installed_style;
}
@@ -5601,10 +5225,10 @@ void Element::update_animated_properties_for_abstract_element(Badge<Web::Animati
// The animation style group of an installed style, which holds the timelines it declares by name.
static CSS::ComputedValues::AnimationValues const* installed_animation_values(CSS::InstalledStyle const& style)
{
- auto const* payloads = static_cast<void const* const*>(style.payloads());
- if (!payloads)
+ auto const* groups = style.groups();
+ if (!groups)
return nullptr;
- return static_cast<CSS::ComputedValues::AnimationValues const*>(payloads[CSS::ComputedValues::AnimationValues::style_group_index]);
+ return &CSS::style_record_group<CSS::ComputedValues::AnimationValues>(groups);
}
// Whether two installed styles differ in the timelines they declare by name, or the timeline names they scope.
@@ -5621,23 +5245,23 @@ static bool timeline_declarations_differ(CSS::InstalledStyle const& old_style, C
return old_values != new_values && !CSS::ComputedValuesFFI::rust_animation_values_timeline_declarations_equal(old_values, new_values);
}
-void Element::replace_style_record(CSS::StyleRecordID style_record_identity)
+void Element::replace_installed_style(Layout::BegunRead const& read, CSS::InstalledStyle style)
{
+ auto const style_record_identity = style.record();
VERIFY(!style_record_identity || style_node_id() != 0);
if (m_installed_style.record() == style_record_identity)
return;
- Layout::ForcedReadScope read { document() };
- auto held_before = exchange(m_installed_style, document().style_computer().install_style(read, style_record_identity));
+ auto held_before = exchange(m_installed_style, move(style));
// The element holds the record it installed before until the engine takes the new one in, so the layout node reads
// what it moves from, and everything below that compares against the old record is read from it, before the
- // element lets go of it. The engine may free the old record's payloads as soon as it is no longer held.
+ // element lets go of it. The engine keeps the old record until it takes the new one in.
if (auto* layout_node = unsafe_layout_node(read))
layout_node->set_style_record_identity(m_installed_style.record());
bool const was_display_none = !held_before || held_before.display_is_none();
// https://drafts.csswg.org/scroll-animations-1/#timeline-scoping
bool const timeline_declarations_changed = timeline_declarations_differ(held_before, m_installed_style);
if (style_node_id() != 0)
- CSS::StyleEngineFFI::style_engine_set_held_style_record(document().style_computer().style_engine().host(), style_node_id(), style_record_identity.value());
+ CSS::StyleEngineFFI::style_engine_set_held_style_record(document().style_computer().style_engine().host(), style_node_id(), m_installed_style.record_pointer());
// Children that wait to arrive in a display:none subtree may be revealed as the subtree's root, or an element
// between it and them, stops being display:none.
if ((child_style_arrivals_wait() || descendant_style_arrival_pending()) && m_installed_style && !m_installed_style.display_is_none()
@@ -5662,47 +5286,50 @@ void Element::install_engine_pseudo_element_custom_property_data(Layout::BegunRe
auto element_data = custom_property_data({});
auto inherited = element_data ? element_data->inheritable(read, document()) : nullptr;
auto data = inherited;
- if (CSS::StyleEngine::is_engine_custom_property_environment(environment) && environment != (inherited ? inherited->identity() : 0))
+ if (style_computer.style_engine().is_engine_custom_property_environment(read, environment) && environment != (inherited ? inherited->identity() : 0)) {
data = style_computer.engine_custom_property_environment(read, environment, inherited);
+ // NB: Where the engine resolved the environment over another one than the pseudo-element inherits now, as a
+ // store shared with an element under another parent names the one it was resolved over last, its
+ // declarations stand over what the pseudo-element inherits, as for an element.
+ if (!data)
+ data = style_computer.engine_custom_property_declarations_over(read, environment, inherited);
+ }
set_custom_property_data(pseudo_element, move(data));
}
-void Element::set_computed_style(Optional<CSS::PseudoElement> pseudo_element_type, CSS::StyleRecordID style_record_identity)
+void Element::set_computed_style(Layout::BegunRead const& read, Optional<CSS::PseudoElement> pseudo_element_type, CSS::InstalledStyle style)
{
- for (auto* element = this; element; element = element->parent_or_shadow_host_element())
- ++element->m_animation_subtree_style_generation;
+ note_subtree_style_moved();
if (pseudo_element_type.has_value()) {
VERIFY(is_synthetic_pseudo_element(*pseudo_element_type));
- if (!!style_record_identity)
- ensure_synthetic_pseudo_element(*pseudo_element_type).set_computed_style(style_record_identity);
+ if (style)
+ ensure_synthetic_pseudo_element(*pseudo_element_type).set_computed_style(read, move(style));
else if (auto existing_pseudo_element = get_synthetic_pseudo_element(*pseudo_element_type); existing_pseudo_element.has_value())
- existing_pseudo_element->set_computed_style(0);
+ existing_pseudo_element->set_computed_style(read, {});
return;
}
++m_animation_style_generation;
- replace_style_record(style_record_identity);
+ replace_installed_style(read, move(style));
computed_properties_changed();
}
-void Element::refresh_computed_style(Optional<CSS::PseudoElement> pseudo_element_type, CSS::StyleRecordID style_record_identity)
+void Element::refresh_computed_style(Layout::BegunRead const& read, Optional<CSS::PseudoElement> pseudo_element_type, CSS::InstalledStyle style)
{
- VERIFY(style_node_id() == 0 || !!style_record_identity);
+ VERIFY(style);
if (pseudo_element_type.has_value()) {
if (CSS::is_element_reference_pseudo_element(*pseudo_element_type)) {
auto pseudo_element = get_pseudo_element(*pseudo_element_type);
VERIFY(pseudo_element.has_value());
auto& referenced_element = as<ElementReferencePseudoElement>(*pseudo_element).referenced_element();
- referenced_element->refresh_computed_style({}, style_record_identity);
+ referenced_element->refresh_computed_style(read, {}, move(style));
return;
}
auto pseudo_element = get_synthetic_pseudo_element(*pseudo_element_type);
VERIFY(pseudo_element.has_value());
- pseudo_element->refresh_computed_style(style_record_identity);
+ pseudo_element->replace_installed_style(read, move(style));
return;
}
-
- replace_style_record(style_record_identity);
- VERIFY(has_style());
+ replace_installed_style(read, move(style));
}
void Element::set_associated_shadow_host_pseudo_element(CSS::PseudoElement type)
@@ -5800,30 +5427,36 @@ SyntheticPseudoElement& Element::ensure_synthetic_pseudo_element(CSS::PseudoElem
void Element::set_custom_property_data(Optional<CSS::PseudoElement> pseudo_element, RefPtr<CSS::CustomPropertyData const> data)
{
Layout::ForcedReadScope read { document() };
- AbstractElement const abstract_element { *this, pseudo_element };
- if (!data || !data->is_animation_overlay_for(abstract_element)) {
- if (auto current = custom_property_data(pseudo_element); current && current->is_animation_overlay_for(abstract_element)) {
- if (current->parent() == data)
- return;
- OrderedHashMap<Utf16FlyString, CSS::StyleProperty> animated_values;
- for (auto const& [name, property] : current->own_values())
- animated_values.set(name, property);
- data = CSS::CustomPropertyData::create_animation_overlay(move(animated_values), move(data), abstract_element);
+ // The element's animations keep sampling their values over whatever its style resolves to.
+ if (custom_property_data_is_animation_overlay(pseudo_element)) {
+ auto current = custom_property_data(pseudo_element);
+ if (current == data) {
+ install_custom_property_data(read, pseudo_element, move(data), CSS::IsAnimationOverlay::Yes);
+ return;
}
+ if (current->parent() == data)
+ return;
+ OrderedHashMap<Utf16FlyString, CSS::StyleProperty> animated_values;
+ current->for_each_declared_value([&](Utf16FlyString const& name, CSS::StyleProperty const& property) {
+ animated_values.set(name, property);
+ });
+ install_custom_property_data(read, pseudo_element, CSS::CustomPropertyData::create_animation_overlay(move(animated_values), move(data)), CSS::IsAnimationOverlay::Yes);
+ return;
}
- install_custom_property_data(read, pseudo_element, move(data));
+ install_custom_property_data(read, pseudo_element, move(data), CSS::IsAnimationOverlay::No);
}
-void Element::replace_custom_property_data(Optional<CSS::PseudoElement> pseudo_element, RefPtr<CSS::CustomPropertyData const> data)
+void Element::replace_custom_property_data(Optional<CSS::PseudoElement> pseudo_element, RefPtr<CSS::CustomPropertyData const> data, CSS::IsAnimationOverlay is_animation_overlay)
{
Layout::ForcedReadScope read { document() };
- install_custom_property_data(read, pseudo_element, move(data));
+ install_custom_property_data(read, pseudo_element, move(data), is_animation_overlay);
}
// The style engine keeps the custom-property environments an element and its synthetic pseudo-elements hold; the
// element keeps no copy of its own. This is the only place they move.
-void Element::install_custom_property_data(Layout::BegunRead const& read, Optional<CSS::PseudoElement> pseudo_element, RefPtr<CSS::CustomPropertyData const> data)
+void Element::install_custom_property_data(Layout::BegunRead const& read, Optional<CSS::PseudoElement> pseudo_element, RefPtr<CSS::CustomPropertyData const> data, CSS::IsAnimationOverlay is_animation_overlay)
{
+ VERIFY(data || is_animation_overlay == CSS::IsAnimationOverlay::No);
if (pseudo_element.has_value() && !CSS::Selector::PseudoElementSelector::is_known_pseudo_element_type(pseudo_element.value()))
return;
@@ -5834,12 +5467,27 @@ void Element::install_custom_property_data(Layout::BegunRead const& read, Option
return;
auto& style_engine = document().style_computer().style_engine();
if (!pseudo_element.has_value()) {
- style_engine.set_element_custom_property_data(read, *this, data.ptr());
+ style_engine.set_element_custom_property_data(read, *this, data.ptr(), is_animation_overlay);
return;
}
if (data)
(void)ensure_synthetic_pseudo_element(pseudo_element.value());
- CSS::StyleEngineFFI::style_engine_set_pseudo_element_custom_property_data(style_engine.host(), style_node.value(), to_underlying(pseudo_element.value()), data.ptr(), data ? data->identity() : 0);
+ // An animation overlay names the environment it lies over, which the engine resolves the pseudo-element's own
+ // custom properties over as the animated values replace theirs.
+ auto const* base = is_animation_overlay == CSS::IsAnimationOverlay::Yes ? data->parent().ptr() : nullptr;
+ auto note = [&](CSS::CustomPropertyData const& environment) {
+ if (!document().style_computer().custom_property_environment_needs_note(environment))
+ return;
+ auto inheritable = environment.inheritable(read, document());
+ CSS::StyleEngineFFI::style_engine_note_custom_property_environment(style_engine.host(), environment.identity(), environment.rust_store(),
+ inheritable ? inheritable->identity() : 0, inheritable ? inheritable->rust_store() : nullptr);
+ };
+ if (base)
+ note(*base);
+ if (is_animation_overlay == CSS::IsAnimationOverlay::Yes)
+ note(*data);
+ CSS::StyleEngineFFI::style_engine_set_pseudo_element_custom_property_data(style_engine.host(), style_node.value(), to_underlying(pseudo_element.value()), data.ptr(), data ? data->identity() : 0,
+ is_animation_overlay == CSS::IsAnimationOverlay::Yes, base ? base->identity() : 0);
return;
}
@@ -5852,7 +5500,7 @@ void Element::install_custom_property_data(Layout::BegunRead const& read, Option
// instead of on the Element/PseudoElement directly. Chrome displays this same (presumably broken)
// behavior whereas Firefox includes the properties in getComputedStyle.
if (auto existing_pseudo_element = get_pseudo_element(pseudo_element.value()); existing_pseudo_element.has_value())
- as<ElementReferencePseudoElement>(*existing_pseudo_element).referenced_element()->set_custom_property_data({}, move(data));
+ as<ElementReferencePseudoElement>(*existing_pseudo_element).referenced_element()->install_custom_property_data(read, {}, move(data), is_animation_overlay);
}
RefPtr<CSS::CustomPropertyData const> Element::custom_property_data(Optional<CSS::PseudoElement> pseudo_element) const
@@ -5876,16 +5524,22 @@ RefPtr<CSS::CustomPropertyData const> Element::custom_property_data(Optional<CSS
return nullptr;
}
-void Element::republish_style_record_environment(Layout::BegunRead const& read)
+bool Element::custom_property_data_is_animation_overlay(Optional<CSS::PseudoElement> pseudo_element) const
{
- if (!has_style() || style_node_id() == 0)
- return;
- auto data = custom_property_data({});
- if (data && data->is_animation_overlay_for({ *this }))
- data = data->parent();
- auto new_style_record = document().style_computer().style_engine().republish_record_environment(read, style_node_id(), data ? data->identity() : 0, data ? data->rust_store() : nullptr);
- if (!!new_style_record && new_style_record != style_record_identity())
- refresh_computed_style({}, new_style_record);
+ if (pseudo_element.has_value() && !CSS::Selector::PseudoElementSelector::is_known_pseudo_element_type(pseudo_element.value()))
+ return false;
+
+ if (!pseudo_element.has_value() || is_synthetic_pseudo_element(pseudo_element.value())) {
+ auto style_node = style_node_id();
+ if (style_node == 0)
+ return false;
+ return CSS::StyleEngineFFI::style_engine_custom_property_data_is_animation_overlay(document().style_computer().style_engine().host(), style_node.value(), pseudo_element.has_value() ? to_underlying(pseudo_element.value()) : NumericLimits<u8>::max());
+ }
+
+ if (auto existing_pseudo_element = get_pseudo_element(pseudo_element.value()); existing_pseudo_element.has_value())
+ return as<ElementReferencePseudoElement>(*existing_pseudo_element).referenced_element()->custom_property_data_is_animation_overlay({});
+
+ return false;
}
// https://drafts.csswg.org/cssom-view/#dom-element-scroll
@@ -5953,8 +5607,8 @@ void Element::scroll(Bindings::ScrollToOptions options, GC::Ptr<WebIDL::Promise>
&& this != document.body()
&& this != document.document_element()) {
document.update_style();
- auto const* misc_reset_values = style_group<CSS::ComputedValues::MiscResetValues>();
- if (!misc_reset_values || misc_reset_values->scroll_snap_strictness_value() == CSS::ScrollSnapStrictness::None) {
+ auto const* misc_interaction_values = style_group<CSS::ComputedValues::MiscInteractionValues>();
+ if (!misc_interaction_values || misc_interaction_values->scroll_snap_strictness_value() == CSS::ScrollSnapStrictness::None) {
if (promise)
WebIDL::resolve_promise(*promise);
return;
@@ -6060,7 +5714,7 @@ bool Element::check_visibility(CheckVisibilityOptions const& options)
// 2. If an ancestor of this in the flat tree has content-visibility: hidden, return false.
for (auto* element = flat_tree_parent_element(); element; element = element->flat_tree_parent_element()) {
- if (static_cast<CSS::ContentVisibility>(element->style_group<CSS::ComputedValues::InheritedBoxValues>()->content_visibility) == CSS::ContentVisibility::Hidden)
+ if (static_cast<CSS::ContentVisibility>(element->style_group<CSS::ComputedValues::MiscLayoutValues>()->content_visibility) == CSS::ContentVisibility::Hidden)
return false;
}
@@ -6076,7 +5730,7 @@ bool Element::check_visibility(CheckVisibilityOptions const& options)
// 4. If either the visibilityProperty or the checkVisibilityCSS dictionary members of options are true, and this
// is invisible, return false.
if (options.visibility_property || options.check_visibility_css) {
- if (static_cast<CSS::Visibility>(style_group<CSS::ComputedValues::InheritedBoxValues>()->visibility) == CSS::Visibility::Hidden)
+ if (CSS::visibility_from_inherited_bits(style_inherited_set_values()->bits) == CSS::Visibility::Hidden)
return false;
}
@@ -6086,7 +5740,7 @@ bool Element::check_visibility(CheckVisibilityOptions const& options)
auto const skipped_contents_due_to_content_visibility_auto = false;
if (options.content_visibility_auto && skipped_contents_due_to_content_visibility_auto) {
for (auto* element = flat_tree_parent_element(); element; element = element->flat_tree_parent_element()) {
- if (static_cast<CSS::ContentVisibility>(element->style_group<CSS::ComputedValues::InheritedBoxValues>()->content_visibility) == CSS::ContentVisibility::Auto)
+ if (static_cast<CSS::ContentVisibility>(element->style_group<CSS::ComputedValues::MiscLayoutValues>()->content_visibility) == CSS::ContentVisibility::Auto)
return false;
}
}
@@ -6683,7 +6337,7 @@ void Element::attribute_changed(Utf16FlyString const& local_name, Optional<Utf16
if (m_id != old_id) {
if (is_connected())
document().element_id_changed({}, *this, old_id);
- CSS::record_element_id_changed(*this, old_id, m_id);
+ CSS::record_element_id_changed(*this, m_id);
}
} else if (local_name == HTML::AttributeNames::name) {
m_has_name = !value_or_empty.is_empty();
@@ -6708,6 +6362,7 @@ void Element::attribute_changed(Utf16FlyString const& local_name, Optional<Utf16
m_classes.clear();
for_each_ascii_whitespace_separated_token(value_or_empty, [&](auto new_class) {
m_classes.append(Utf16FlyString::from_utf16(new_class));
+ add_to_subtree_name_filter(name_filter_bit(m_classes.last()));
return IterationDecision::Continue;
});
}
@@ -6730,9 +6385,23 @@ void Element::attribute_changed(Utf16FlyString const& local_name, Optional<Utf16
m_inline_style->set_declarations_from_text(text);
return;
}
+ // NB: Elements that write the same text share its block, which an edit through the CSSOM replaces
+ // rather than changes.
+ auto& inline_style_blocks = document().inline_style_blocks();
+ bool quirks = document().in_quirks_mode();
+ if (!text.is_empty()) {
+ if (auto* shared = inline_style_blocks.find(text, quirks)) {
+ CSS::Parser::ValueParserFFI::rust_declaration_block_destroy(exchange(m_inline_declarations, shared));
+ return;
+ }
+ }
CSS::Parser::ParsingParams parsing_params { document() };
parsing_params.rule_context.append(CSS::Parser::RuleContext::Style);
- auto* declarations = parse_css_property_declaration_block(parsing_params, text).leak_handle();
+ // NB: Only a block whose parse reported nothing is shared, so that a hit never hides a report.
+ bool parsed_cleanly = false;
+ auto* declarations = parse_css_property_declaration_block(parsing_params, text, &parsed_cleanly).leak_handle();
+ if (parsed_cleanly && !text.is_empty())
+ inline_style_blocks.insert(text, quirks, *declarations);
CSS::Parser::ValueParserFFI::rust_declaration_block_destroy(exchange(m_inline_declarations, declarations));
};
// https://html.spec.whatwg.org/multipage/dom.html#the-style-attribute
@@ -7075,8 +6744,8 @@ bool Element::meets_focusable_area_rendering_requirements() const
return false;
// NB: Elements whose boxes are not visible cannot be focused.
- auto const* values = style_group<CSS::ComputedValues::InheritedBoxValues>();
- return values && values->visibility_value() == CSS::Visibility::Visible;
+ auto const* values = style_inherited_set_values();
+ return values && CSS::visibility_from_inherited_bits(values->bits) == CSS::Visibility::Visible;
}
// https://drafts.csswg.org/css-view-transitions-1/#document-scoped-view-transition-name
@@ -7085,7 +6754,7 @@ Optional<Utf16FlyString> Element::document_scoped_view_transition_name()
// To get the document-scoped view transition name for an Element element:
// 1. Let scopedViewTransitionName be the computed value of view-transition-name for element.
- auto const* values = style_group<CSS::ComputedValues::MiscResetValues>();
+ auto const* values = style_group<CSS::ComputedValues::MiscInteractionValues>();
VERIFY(values);
auto scoped_view_transition_name = values->view_transition_name_value();
diff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.h
index 42d7b01b147..ca27a22f259 100644
--- a/Libraries/LibWeb/DOM/Element.h
+++ b/Libraries/LibWeb/DOM/Element.h
@@ -50,6 +50,12 @@ class KeyframeEffect;
}
+namespace Web::CSS {
+
+enum class MainEffects : u32;
+
+}
+
namespace Web::DOM {
class Element;
@@ -261,11 +267,11 @@ public:
// The element's attributes in order, borrowed until they next change.
ReadonlySpan<Attribute> attribute_list() const;
- // A filter over the local names of the attributes of this element and its descendants: a name whose bit is clear
- // is on none of them. Bits are only ever added, so a name may keep its bit after its last attribute is gone.
- static u64 attribute_name_filter_bit(Utf16FlyString const& local_name) { return 1ull << (local_name.hash() % 64); }
- u64 subtree_attribute_name_filter() const { return m_subtree_attribute_name_filter; }
- void add_to_subtree_attribute_name_filter(u64 bits);
+ // A filter over the local names of the attributes and the classes of this element and its descendants: a name whose
+ // bit is clear is on none of them. Bits are only ever added, so a name may keep its bit after it is last removed.
+ static u64 name_filter_bit(Utf16FlyString const& name) { return 1ull << (name.hash() % 64); }
+ u64 subtree_name_filter() const { return m_subtree_name_filter; }
+ void add_to_subtree_name_filter(u64 bits);
GC::Ptr<NamedNodeMap const> attributes() const;
GC::Ptr<NamedNodeMap> attributes();
@@ -353,6 +359,7 @@ public:
// elements keep 0, which is what makes them free.
[[nodiscard]] CSS::StyleNodeID style_node_id() const { return m_style_node_id; }
void set_style_node_id(CSS::StyleNodeID);
+ void record_style_environment_change();
// https://html.spec.whatwg.org/multipage/embedded-content-other.html#dimension-attributes
virtual bool supports_dimension_attributes() const { return false; }
@@ -365,64 +372,50 @@ public:
void run_attribute_change_steps(Utf16FlyString const& local_name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_);
- // Apply a base style record the style engine computed itself from this element's moved cascade
- // winners: no style computation runs here, only the diff against the old record and its effects.
- // The synthetic pseudo-element records the style engine settled beside an engine-computed record: a kind it
- // decided holds the record, or none when the pseudo-element is not generated; a kind it left alone is unchanged.
- using EnginePseudoElementRecords = Array<Optional<CSS::StyleRecordID>, to_underlying(CSS::PseudoElement::KnownPseudoElementCount)>;
- // What the style engine answered a record's installation damages, for the move between the two
- // records it names. Any other move is compared at installation.
- struct EngineRecordDamage {
- CSS::StyleRecordID old_style_record;
- CSS::StyleRecordID new_style_record;
- u32 packed { 0 };
-
- [[nodiscard]] bool answers(CSS::StyleRecordID old_record, CSS::StyleRecordID new_record) const { return old_style_record == old_record && new_style_record == new_record; }
- };
- // A pseudo-element's move is decided against the originating element's record as well, so its
- // answer also names that record.
- struct EnginePseudoElementRecordDamage {
- EngineRecordDamage move;
- CSS::StyleRecordID originating_style_record;
- };
- // The damages the style engine answered an element's row and its pseudo-element rows with.
- struct EngineRecordDamages {
- Optional<EngineRecordDamage> element;
- Array<Optional<EnginePseudoElementRecordDamage>, to_underlying(CSS::PseudoElement::KnownPseudoElementCount)> pseudo_elements {};
- };
- // Whether installing a record also applies the change of the element's display, or leaves that to a caller that
- // first composes the element's animations over the record and runs its transition step, as a C++ computation does.
- enum class DisplayNoneChange : u8 {
- Apply,
- LeftToCaller,
- };
- CSS::RequiredInvalidationAfterStyleChange apply_engine_computed_style_record(Layout::BegunRead const& read, CSS::StyleRecordID new_style_record, EnginePseudoElementRecords const&, bool uses_substitution, u8 record_reads, u32 explicitly_inherited_non_inherited_style_groups, bool& did_change_custom_properties, DisplayNoneChange, EngineRecordDamages const* = nullptr);
// Whether an element's display is none, with its animations and ignoring them.
struct DisplayNoneState {
bool display_is_none { true };
bool display_ignoring_animations_is_none { true };
- static DisplayNoneState of(CSS::ComputedValues const&);
+ static DisplayNoneState of(CSS::ComputedValues const&, CSS::InstalledStyle const&);
};
// None for an element without style.
[[nodiscard]] Optional<DisplayNoneState> display_none_state() const;
// Terminates or resumes the animations of a subtree whose display, ignoring animations, left or entered none since
// `before`, and clears the styles of a subtree that became display:none.
- void apply_display_none_change(Layout::BegunRead const& read, DisplayNoneState before);
+ void apply_display_none_change(DisplayNoneState before);
// Clears the styles of the descendants of a display:none element, which have no boxes: a CSSOM read or the subtree's
// reveal materializes them again. The styles of the SVG elements visible content can reference are computed again.
void clear_computed_styles_from_display_none_descendants(Layout::BegunRead const& read);
- // Whether a styled descendant is an SVG element visible content can reference, whose style is kept while the element
- // is display:none.
- [[nodiscard]] bool has_referenceable_svg_descendant() const;
- // Refreshes the pseudo-element styles of an element whose record the engine settled without them, once the host has
- // composed the element's animations over the record, which the pseudo-elements inherit. `old_computed_values` is
- // the style the element held before the record.
- CSS::RequiredInvalidationAfterStyleChange refresh_pseudo_element_styles_over_composition(Layout::BegunRead const& read, CSS::ComputedValues const* old_computed_values, bool& did_change_custom_properties);
// The custom-property environment an engine-computed record was published with: the one the
// element inherits, or one the engine resolved over it. Nothing when it cannot be installed.
- [[nodiscard]] RefPtr<CSS::CustomPropertyData const> custom_property_environment_of_engine_record(Layout::BegunRead const& read, CSS::StyleRecordID, bool& installable) const;
- CSS::RequiredInvalidationAfterStyleChange recompute_pseudo_element_styles(Layout::BegunRead const& read);
+ [[nodiscard]] RefPtr<CSS::CustomPropertyData const> custom_property_environment_of_engine_record(Layout::BegunRead const& read, u64 environment, bool& installable) const;
+ // Swaps in the style record the render side installed for the element, or for one of its synthetic
+ // pseudo-elements, in its box too. The side effects of the move are left to apply_style_main_effects().
+ void swap_in_style_record(Layout::BegunRead const& read, Optional<CSS::PseudoElement>, void const* record);
+ // Moves the animation subtree style generation of the element and its ancestors.
+ void note_subtree_style_moved();
+ [[nodiscard]] RefPtr<CSS::CustomPropertyData const> style_custom_property_environment(Layout::BegunRead const& read, CSS::InstalledStyle const&) const;
+ // Performs the main-side effects of the element's move from `old_style_record`, if it held one, to the style
+ // record it holds, which damages `invalidation`.
+ void apply_style_main_effects(Layout::BegunRead const& read, CSS::MainEffects, CSS::LayoutTreeRebuildRoot, CSS::RequiredInvalidationAfterStyleChange const& invalidation, CSS::InstalledStyle const& old_style);
+ // The pseudo-elements the style engine computes beside their element.
+ static constexpr Array<CSS::PseudoElement, 9> computed_pseudo_elements {
+ CSS::PseudoElement::Before,
+ CSS::PseudoElement::After,
+ CSS::PseudoElement::FirstLetter,
+ CSS::PseudoElement::Selection,
+ CSS::PseudoElement::SearchText,
+ CSS::PseudoElement::SearchTextCurrent,
+ CSS::PseudoElement::SpellingError,
+ CSS::PseudoElement::Backdrop,
+ CSS::PseudoElement::Marker,
+ };
+ // Composes the style records swapped in for those of the element's pseudo-elements the `composed` mask names, a
+ // bit at each kind: applies the plan each record decides, samples the animations over it, and runs the transition
+ // step for those the `transition_steps` mask names, against the record each held before, which
+ // `before_change_style_records` names in the order of `computed_pseudo_elements`.
+ CSS::RequiredInvalidationAfterStyleChange compose_style_pseudo_element_records(Layout::BegunRead const& read, u16 composed, u16 transition_steps, Array<CSS::InstalledStyle, computed_pseudo_elements.size()> const& before_change_styles);
void set_needs_layout_tree_rebuild(Layout::BegunRead const& read, SetNeedsLayoutTreeUpdateReason, CSS::LayoutTreeRebuildRoot);
bool apply_box_presence_change_in_place(Layout::BegunRead const& read, SetNeedsLayoutTreeUpdateReason);
@@ -446,19 +439,35 @@ public:
u64 animation_style_generation() const { return m_animation_style_generation; }
u64 animation_subtree_style_generation() const { return m_animation_subtree_style_generation; }
[[nodiscard]] bool has_style(Optional<CSS::PseudoElement> pseudo_element = {}) const { return !!style_record_identity(pseudo_element); }
- [[nodiscard]] void const* style_record_payloads(Optional<CSS::PseudoElement> pseudo_element = {}) const { return installed_style(pseudo_element).payloads(); }
+ [[nodiscard]] void const* style_record_groups(Optional<CSS::PseudoElement> pseudo_element = {}) const { return installed_style(pseudo_element).groups(); }
template<typename StyleGroup>
StyleGroup const* style_group(Optional<CSS::PseudoElement> pseudo_element = {}) const
{
- auto const* payloads = static_cast<void const* const*>(style_record_payloads(pseudo_element));
- if (!payloads)
+ auto const* groups = style_record_groups(pseudo_element);
+ if (!groups)
return nullptr;
- auto const* payload = payloads[StyleGroup::style_group_index];
- VERIFY(payload);
- return static_cast<StyleGroup const*>(payload);
+ return &CSS::style_record_group<StyleGroup>(groups);
+ }
+ // The properties that do not inherit the style holds as bits, where it has a style.
+ Optional<CSS::ComputedValuesFFI::ResetBits> style_reset_bits(Optional<CSS::PseudoElement> pseudo_element = {}) const
+ {
+ auto const* groups = style_record_groups(pseudo_element);
+ if (!groups)
+ return {};
+ return CSS::style_record_reset_bits(groups);
}
- void set_computed_style(Optional<CSS::PseudoElement>, CSS::StyleRecordID);
- void refresh_computed_style(Optional<CSS::PseudoElement>, CSS::StyleRecordID);
+ // The inherited longhands the style holds as bits, and its effective zoom, where it has a style.
+ CSS::ComputedValuesFFI::InheritedSetValues const* style_inherited_set_values(Optional<CSS::PseudoElement> pseudo_element = {}) const
+ {
+ auto const* groups = style_record_groups(pseudo_element);
+ if (!groups)
+ return nullptr;
+ return &CSS::style_record_inherited_values(groups);
+ }
+ void set_computed_style(Layout::BegunRead const&, Optional<CSS::PseudoElement>, CSS::InstalledStyle);
+ // Installs `style`, which the engine just published for the element or a pseudo-element of it, without asking the
+ // engine for it.
+ void refresh_computed_style(Layout::BegunRead const&, Optional<CSS::PseudoElement>, CSS::InstalledStyle);
// Install the custom properties beside a pseudo-element record the style engine derived.
void install_engine_pseudo_element_custom_property_data(Layout::BegunRead const& read, CSS::PseudoElement, u64 environment);
void update_animated_properties(Badge<Web::Animations::KeyframeEffect> const&, Optional<CSS::PseudoElement>, Web::Animations::KeyframeEffect&, Web::Animations::AnimationUpdateContext&);
@@ -595,36 +604,18 @@ public:
void set_shadow_root(GC::Ptr<ShadowRoot>);
void set_custom_property_data(Optional<CSS::PseudoElement>, RefPtr<CSS::CustomPropertyData const>);
- void replace_custom_property_data(Optional<CSS::PseudoElement>, RefPtr<CSS::CustomPropertyData const>);
+ void replace_custom_property_data(Optional<CSS::PseudoElement>, RefPtr<CSS::CustomPropertyData const>, CSS::IsAnimationOverlay);
[[nodiscard]] RefPtr<CSS::CustomPropertyData const> custom_property_data(Optional<CSS::PseudoElement>) const;
+ // Whether the environment `custom_property_data()` answers is the overlay of what the element's or the
+ // pseudo-element's own animations sample.
+ [[nodiscard]] bool custom_property_data_is_animation_overlay(Optional<CSS::PseudoElement>) const;
+ [[nodiscard]] size_t published_presentational_hint_properties_heap_size() const { return m_published_presentational_hint_properties.capacity() * sizeof(CSS::StyleProperty); }
// Publish the environment the element's custom-property data moved to on its record, so the
// engine reads the environment the element holds.
- void republish_style_record_environment(Layout::BegunRead const& read);
-
- // What the element's last computation was allowed to read, so a later one can ask whether any of
- // it moved before deriving a style that would be identical. Retired by anything that moves what
- // a word of it names without moving the name, which is a write to a declaration the element
- // itself sources.
- // What the custom-property name index was last told about this element. Publishing it again
- // costs one atom per name and a crossing into the engine, and a recomputation that resolved the
- // same environment has the same names to publish.
- struct PublishedCustomPropertyNames {
- RefPtr<CSS::CustomPropertyData const> data;
- bool uses_var_css_function { false };
- bool uses_custom_function { false };
- bool operator==(PublishedCustomPropertyNames const&) const = default;
- };
- struct PseudoElementStyleQueryCustomPropertyReferences {
- CSS::PseudoElement pseudo_element;
- Vector<Utf16FlyString> references;
- };
- void record_style_query_custom_property_reference(Optional<CSS::PseudoElement>, Utf16FlyString const&);
bool style_uses_attr_css_function() const { return m_style_uses_attr_css_function; }
void set_style_uses_attr_css_function() { m_style_uses_attr_css_function = true; }
- bool style_uses_var_css_function() const { return m_style_uses_var_css_function; }
- void set_style_uses_var_css_function() { m_style_uses_var_css_function = true; }
// A tree-counting function is answered from the element's position among its siblings, so what
// has to be remembered is on the parent: a child list mutation there moves the answer.
void set_style_uses_tree_counting_function()
@@ -645,16 +636,6 @@ public:
void set_style_uses_if_css_function();
bool style_depends_on_viewport_metrics() const { return m_style_depends_on_viewport_metrics; }
void set_style_depends_on_viewport_metrics();
- bool style_uses_inherit_css_function() const { return m_style_uses_inherit_css_function; }
- void set_style_uses_inherit_css_function()
- {
- if (m_style_uses_inherit_css_function)
- return;
- bool const publishes = !style_recomputes_on_environment_move();
- m_style_uses_inherit_css_function = true;
- if (publishes)
- publish_style_recomputes_on_environment_move();
- }
bool style_depends_on_size_container_query() const { return m_style_depends_on_size_container_query; }
void set_style_depends_on_size_container_query()
{
@@ -668,19 +649,8 @@ public:
{
if (m_style_depends_on_style_container_query)
return;
- bool const publishes = !style_recomputes_on_environment_move();
m_style_depends_on_style_container_query = true;
- if (publishes)
- publish_style_recomputes_on_environment_move();
- }
- // Whether a moved custom-property environment computes this element again: whether its style reads the
- // environment other than through var(), through if(), inherit(), a custom function or a style container query.
- bool style_recomputes_on_environment_move() const
- {
- return m_style_uses_if_css_function || m_style_uses_inherit_css_function || m_style_uses_custom_function || m_style_depends_on_style_container_query;
}
- // Tell the style engine.
- void publish_style_recomputes_on_environment_move();
// Set on the element a container query selected as its query container, so a change on it knows
// whether anything under it was ever asking. Neither is ever cleared: a dependent that stops
// asking republishes nothing, and answering "maybe" costs the scan the element used to pay
@@ -985,6 +955,7 @@ protected:
struct RareData;
private:
+ void bump_dom_tree_version_for_attribute_change();
// The attributes of an element, in order, in the same allocation as their count and capacity.
class AttributeList {
AK_MAKE_NONCOPYABLE(AttributeList);
@@ -1038,7 +1009,7 @@ private:
void append_to_attribute_list(QualifiedName, Utf16String value);
- void install_custom_property_data(Layout::BegunRead const& read, Optional<CSS::PseudoElement>, RefPtr<CSS::CustomPropertyData const>);
+ void install_custom_property_data(Layout::BegunRead const& read, Optional<CSS::PseudoElement>, RefPtr<CSS::CustomPropertyData const>, CSS::IsAnimationOverlay);
void synchronize_attribute(Utf16FlyString const& qualified_name) const;
void synchronize_attribute_ns(Optional<Utf16FlyString> const&, Utf16FlyString const& local_name) const;
void synchronize_style_attribute() const;
@@ -1066,12 +1037,10 @@ private:
Utf16FlyString make_html_uppercased_qualified_name() const;
void exit_fullscreen_on_element_removal();
- CSS::RequiredInvalidationAfterStyleChange recompute_pseudo_element_styles(Layout::BegunRead const& read, bool& did_change_custom_properties, bool had_list_marker, CSS::ComputedValues const* old_originating_style, EnginePseudoElementRecords const* = nullptr, EngineRecordDamages const* = nullptr);
void apply_computed_style_to_layout_node_if_needed(Layout::BegunRead const& read, CSS::RequiredInvalidationAfterStyleChange const&);
void apply_computed_pseudo_element_styles_to_layout_nodes_if_needed(Layout::BegunRead const& read, CSS::RequiredInvalidationAfterStyleChange const&);
- void publish_custom_property_names();
void update_anchor_name_registry(CSS::ComputedValues const* old_computed_values, CSS::ComputedValues const& new_computed_values);
- void replace_style_record(CSS::StyleRecordID);
+ void replace_installed_style(Layout::BegunRead const&, CSS::InstalledStyle);
WebIDL::ExceptionOr<GC::Ptr<Node>> insert_adjacent(Utf16View where, GC::Ref<Node> node);
@@ -1088,7 +1057,7 @@ private:
Vector<Utf16FlyString, 1> m_classes;
OwnPtr<AttributeList> m_attributes;
- u64 m_subtree_attribute_name_filter { 0 };
+ u64 m_subtree_name_filter { 0 };
// NB: The declarations of a style attribute, until something asks for their CSSOM object (m_inline_style), which
// takes them over. At most one of the two is set.
CSS::Parser::ValueParserFFI::DeclarationBlock* m_inline_declarations { nullptr };
@@ -1099,7 +1068,6 @@ private:
CSS::InstalledStyle m_installed_style;
u64 m_animation_style_generation { 0 };
u64 m_animation_subtree_style_generation { 0 };
- PublishedCustomPropertyNames m_published_custom_property_names;
Vector<CSS::StyleProperty> m_published_presentational_hint_properties;
void register_element_reference_pseudo_element(CSS::PseudoElement type, GC::Ref<Element> element);
@@ -1115,11 +1083,9 @@ private:
bool m_rendered_in_top_layer : 1 { false };
// Authoritative dependency marks left by this element's latest style computation.
bool m_style_uses_attr_css_function : 1 { false };
- bool m_style_uses_var_css_function : 1 { false };
bool m_style_uses_if_css_function : 1 { false };
bool m_style_depends_on_viewport_metrics : 1 { false };
bool m_style_uses_custom_function : 1 { false };
- bool m_style_uses_inherit_css_function : 1 { false };
bool m_style_depends_on_size_container_query : 1 { false };
bool m_style_depends_on_style_container_query : 1 { false };
bool m_is_style_query_container : 1 { false };
diff --git a/Libraries/LibWeb/DOM/ElementByIdMap.cpp b/Libraries/LibWeb/DOM/ElementByIdMap.cpp
index 3aafd26544f..b99dfff8a59 100644
--- a/Libraries/LibWeb/DOM/ElementByIdMap.cpp
+++ b/Libraries/LibWeb/DOM/ElementByIdMap.cpp
@@ -95,4 +95,12 @@ void ElementByIdMap::for_each_element_with_id(Utf16View element_id, Node const&
});
}
+ReadonlySpan<GC::Weak<Element>> ElementByIdMap::elements_with_id(Utf16FlyString const& element_id) const
+{
+ auto maybe_entry = m_map.get(element_id);
+ if (!maybe_entry.has_value())
+ return {};
+ return maybe_entry->elements.span();
+}
+
}
diff --git a/Libraries/LibWeb/DOM/ElementByIdMap.h b/Libraries/LibWeb/DOM/ElementByIdMap.h
index 15450542695..b17066236e6 100644
--- a/Libraries/LibWeb/DOM/ElementByIdMap.h
+++ b/Libraries/LibWeb/DOM/ElementByIdMap.h
@@ -22,6 +22,8 @@ public:
GC::Ptr<Element> get(Utf16View element_id, Node const& scope_root) const;
bool contains(Utf16FlyString const& element_id) const { return m_map.contains(element_id); }
void for_each_element_with_id(Utf16View element_id, Node const& scope_root, Function<void(Element&)> callback) const;
+ // Every element with the id, in no particular order.
+ ReadonlySpan<GC::Weak<Element>> elements_with_id(Utf16FlyString const& element_id) const;
template<typename Callback>
void for_each_id(Callback callback)
diff --git a/Libraries/LibWeb/DOM/ElementRareData.h b/Libraries/LibWeb/DOM/ElementRareData.h
index c2be3cf19d2..743469a4924 100644
--- a/Libraries/LibWeb/DOM/ElementRareData.h
+++ b/Libraries/LibWeb/DOM/ElementRareData.h
@@ -31,15 +31,6 @@ struct Element::RareData
GC::Ptr<DOMTokenList> part_list;
GC::Ptr<NamedNodeMap> attribute_map;
mutable OwnPtr<PseudoElementData> pseudo_element_data;
- struct CustomPropertyConsumerData {
- AK_ALLOC_WITH_KMALLOC;
-
- Vector<Utf16FlyString> style_query_references;
- Vector<PseudoElementStyleQueryCustomPropertyReferences> pseudo_element_style_query_references;
- Vector<RefPtr<CSS::CustomPropertyData const>> published_pseudo_element_data;
- Vector<Utf16FlyString> published_references;
- };
- OwnPtr<CustomPropertyConsumerData> custom_property_consumer_data;
Optional<CSS::PseudoElement> associated_shadow_host_pseudo_element;
Vector<Utf16FlyString> parts;
diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cpp
index f29a0509ec6..734981f24b7 100644
--- a/Libraries/LibWeb/DOM/Node.cpp
+++ b/Libraries/LibWeb/DOM/Node.cpp
@@ -117,7 +117,7 @@
namespace Web::DOM {
#if ARCH(X86_64) && !defined(AK_OS_WINDOWS)
-static_assert(sizeof(Node) == 104);
+static_assert(sizeof(Node) == 96);
#endif
static bool final_direct_list_item_does_not_renumber_existing_content(Element const& list_item)
@@ -236,7 +236,7 @@ CSS::UserSelect Node::user_select_used_value() const
element = flat_tree_parent_element();
}
- auto const* values = element ? element->style_group<CSS::ComputedValues::MiscResetValues>() : nullptr;
+ auto const* values = element ? element->style_group<CSS::ComputedValues::MiscInteractionValues>() : nullptr;
if (!values)
return CSS::UserSelect::None;
@@ -356,13 +356,6 @@ UniqueNodeID Node::unique_id() const
return unique_id_of_node_directory_slot(m_node_directory_slot);
}
-Optional<UniqueNodeID> Node::unique_id_if_assigned() const
-{
- if (!m_node_directory_slot)
- return {};
- return unique_id_of_node_directory_slot(m_node_directory_slot);
-}
-
Optional<String> Node::webdriver_node_id() const
{
if (!m_rare_data)
@@ -717,38 +710,6 @@ CSS::StyleScope& Node::style_scope()
return document().style_scope();
}
-void Node::record_style_environment_change()
-{
- document().bump_style_environment_version();
-
- if (is_document()) {
- // NB: An engine created later starts from the environment as it is then.
- if (auto* style_computer = document().style_computer_if_created())
- CSS::StyleEngineFFI::style_engine_record_environment_change(style_computer->style_engine().host());
- return;
- }
-
- // A shadow root has no style of its own, so a caller naming one means the scope it heads. An
- // element names its own environment input; StyleEngine routes any consequences of its changed
- // facts separately.
- // The environment version this bumped is a published document input, so what these rows need
- // is a drive against the new one, which the engine can do for itself. What the host knows that
- // the engine does not is only WHICH nodes to drive, and that is what the reaction carries.
- if (is_element()) {
- auto& element = static_cast<Element&>(*this);
- document().style_computer().style_engine().record_derived_element_style_input_change(element.style_node_id(), CSS::StyleEngine::PublishedStyle | CSS::StyleEngine::RecomputeStyle);
- return;
- }
-
- for_each_shadow_including_inclusive_descendant([](Node& descendant) {
- auto* element = as_if<Element>(descendant);
- if (!element)
- return TraversalDecision::Continue;
- element->document().style_computer().style_engine().record_derived_element_style_input_change(element->style_node_id(), CSS::StyleEngine::PublishedStyle | CSS::StyleEngine::RecomputeStyle);
- return TraversalDecision::Continue;
- });
-}
-
Utf16String Node::child_text_content() const
{
auto const* parent_node = as_if<ParentNode>(*this);
@@ -1425,77 +1386,22 @@ static void pin_bound_box_style_record_for_detachment(Node& node, Optional<CSS::
Layout::RustFFI::render_state_pin_bound_box_style_record_for_detachment(arena->host(), Layout::Node::style_node_of(&node).value(), generated_for);
}
-class RemovalStyleRecordPins {
-public:
- // NB: A document that has no style computer yet holds no style records to pin.
- explicit RemovalStyleRecordPins(CSS::StyleComputer const* style_computer)
- : m_style_computer(style_computer)
- {
- }
-
- ~RemovalStyleRecordPins()
- {
- release_dom_style_records();
- }
-
- void pin_style_records_before_removal(Node& node, bool was_connected)
- {
- if (!was_connected)
- return;
- node.for_each_shadow_including_inclusive_descendant([&](Node& inclusive_descendant) {
- pin_bound_box_style_record_for_detachment(inclusive_descendant);
-
- if (auto* element = as_if<Element>(inclusive_descendant)) {
- pin_dom_style_record(element->style_record_identity());
- element->for_each_synthetic_pseudo_element([&](CSS::PseudoElement type, SyntheticPseudoElement& pseudo_element) {
- pin_bound_box_style_record_for_detachment(*element, type);
- pin_dom_style_record(pseudo_element.style_record_identity());
- });
- }
-
- return TraversalDecision::Continue;
- });
- }
-
- void pin_style_records_after_removal(Node& node, bool was_connected)
- {
- if (was_connected)
- return;
- // Detached subtrees do not need DOM-held record pins, but layout nodes can still outlive removing steps and
- // keep their detachment pins.
- node.for_each_shadow_including_inclusive_descendant([](Node& inclusive_descendant) {
- pin_bound_box_style_record_for_detachment(inclusive_descendant);
-
- if (auto* element = as_if<Element>(inclusive_descendant)) {
- element->for_each_synthetic_pseudo_element([&](CSS::PseudoElement type, SyntheticPseudoElement&) {
- pin_bound_box_style_record_for_detachment(*element, type);
- });
- }
-
- return TraversalDecision::Continue;
- });
- }
-
- void release_dom_style_records()
- {
- for (auto style_record_identity : m_dom_style_record_pins)
- m_style_computer->unpin_style_record(style_record_identity);
- m_dom_style_record_pins.clear();
- }
+// The boxes of a removed subtree can outlive its removing steps, so each keeps its style record, as its layout node
+// reads it, until it is detached.
+static void pin_bound_box_style_records_for_detachment(Node& node)
+{
+ node.for_each_shadow_including_inclusive_descendant([](Node& inclusive_descendant) {
+ pin_bound_box_style_record_for_detachment(inclusive_descendant);
-private:
- void pin_dom_style_record(CSS::StyleRecordID style_record_identity)
- {
- if (!style_record_identity)
- return;
- VERIFY(m_style_computer);
- m_style_computer->pin_style_record(style_record_identity);
- m_dom_style_record_pins.append(style_record_identity);
- }
+ if (auto* element = as_if<Element>(inclusive_descendant)) {
+ element->for_each_synthetic_pseudo_element([&](CSS::PseudoElement type, SyntheticPseudoElement&) {
+ pin_bound_box_style_record_for_detachment(*element, type);
+ });
+ }
- GC::Ptr<CSS::StyleComputer const> m_style_computer;
- Vector<CSS::StyleRecordID, 16> m_dom_style_record_pins;
-};
+ return TraversalDecision::Continue;
+ });
+}
bool Node::schedule_list_item_renumber_for_removal()
{
@@ -1618,6 +1524,15 @@ GC::RootVector<GC::Ref<HTML::HTMLSlotElement>> Node::descendant_slots_before_rem
return descendant_slots;
}
+// The chain :focus-within leaves as a subtree does starts at the slot its root is assigned to, where it is one, which
+// nothing can tell once the root has left.
+static GC::Ptr<Node> old_flat_tree_parent_for_focus_within(Node& node, Node& parent)
+{
+ if (auto const* element = as_if<Element>(node); element && element->assigned_slot_internal())
+ return element->assigned_slot_internal();
+ return parent;
+}
+
void Node::assign_slottables_after_removal(Node& parent, Node& parent_root, ReadonlySpan<GC::Ref<HTML::HTMLSlotElement>> descendant_slots)
{
// AD-HOC: Assigned nodes are recomputed lazily.
@@ -1772,9 +1687,11 @@ void Node::remove(bool suppress_observers)
auto& parent_root = parent->root();
auto descendant_slots = descendant_slots_before_removal(parent_root);
+ auto old_flat_tree_parent = old_flat_tree_parent_for_focus_within(*this, *parent);
+ bool const holds_a_propagating_state_source = CSS::Invalidation::holds_a_propagating_state_source(*this);
- RemovalStyleRecordPins removal_style_record_pins { document().style_computer_if_created() };
- removal_style_record_pins.pin_style_records_before_removal(*this, was_tracked_by_style_engine);
+ if (was_tracked_by_style_engine)
+ pin_bound_box_style_records_for_detachment(*this);
if (was_tracked_by_style_engine) {
Layout::ForcedReadScope read { document() };
// A suppressed-observer removal may be the first half of a compound mutation that immediately reinserts
@@ -1795,11 +1712,13 @@ void Node::remove(bool suppress_observers)
// 10. If node has an inclusive descendant that is a slot, then:
assign_slottables_after_removal(*parent, parent_root, descendant_slots);
- removal_style_record_pins.pin_style_records_after_removal(*this, was_connected);
+ if (!was_connected)
+ pin_bound_box_style_records_for_detachment(*this);
// NB: A subtree holding the focused or hovered node takes :focus-within and :hover out of its old ancestor
// chain. Republish that chain before the removing steps clear the focused area.
- CSS::Invalidation::invalidate_style_after_subtree_place_changed(*this, parent);
+ if (holds_a_propagating_state_source)
+ CSS::Invalidation::invalidate_style_after_subtree_holding_a_state_source_left(*this, old_flat_tree_parent);
// 11. Run the removing steps with node, true, and parent.
// 12. Let isParentConnected be parent’s connected.
@@ -1808,8 +1727,6 @@ void Node::remove(bool suppress_observers)
// 14. For each shadow-including descendant descendant of node, in shadow-including tree order:
run_removing_steps(*parent, parent_root, was_tracked_by_style_engine);
- removal_style_record_pins.release_dom_style_records();
-
// 15. Add transient registered observers given node and parent.
add_transient_registered_observers(*parent);
@@ -2088,6 +2005,8 @@ WebIDL::ExceptionOr<void> Node::move_node(Node& new_parent, Node* child)
GC::Ptr<Node> const moved_from_parent = moved_element ? moved_element->parent() : nullptr;
GC::Ptr<Element> const moved_from_previous = moved_element ? moved_element->previous_element_sibling() : nullptr;
GC::Ptr<Element> const moved_from_next = moved_element ? moved_element->next_element_sibling() : nullptr;
+ GC::Ptr<Element> const moved_from_slot = moved_element ? moved_element->assigned_slot_internal() : nullptr;
+ bool const holds_a_propagating_state_source = CSS::Invalidation::holds_a_propagating_state_source(*this);
if (old_parent->is_connected()) {
// NOTE: If we did not contribute to the layout tree before, rebuilding it will not create a box
@@ -2175,7 +2094,7 @@ WebIDL::ExceptionOr<void> Node::move_node(Node& new_parent, Node* child)
CSS::record_node_moved_in_dom_order(*this, *old_parent);
if (moved_element)
- CSS::record_element_moved(*moved_element, moved_from_parent.ptr(), moved_from_previous.ptr(), moved_from_next.ptr());
+ CSS::record_element_moved(*moved_element, moved_from_parent.ptr(), moved_from_previous.ptr(), moved_from_next.ptr(), moved_from_slot.ptr());
else if (is<CharacterData>(*this)) {
auto const* text = as_if<Text>(*this);
auto counts_for_emptiness = text && !text->data().is_empty();
@@ -2236,7 +2155,8 @@ WebIDL::ExceptionOr<void> Node::move_node(Node& new_parent, Node* child)
// NB: Refresh lookup caches before moving steps can query the completed tree change.
document().subtree_was_moved({}, *this, old_parent_root);
- CSS::Invalidation::invalidate_style_after_subtree_place_changed(*this, moved_from_parent);
+ if (holds_a_propagating_state_source)
+ CSS::Invalidation::invalidate_style_after_subtree_holding_a_state_source_left(*this, moved_from_slot ? GC::Ptr<Node> { moved_from_slot } : moved_from_parent);
// 25. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:
for_each_shadow_including_inclusive_descendant([this, &new_parent, old_parent](Node& inclusive_descendant) {
@@ -3197,9 +3117,11 @@ void Node::remove_all_children(bool suppress_observers)
list_owner_renumber_scheduled = child->schedule_list_item_renumber_for_removal();
auto descendant_slots = child->descendant_slots_before_removal(parent_root);
+ auto old_flat_tree_parent = old_flat_tree_parent_for_focus_within(*child, *this);
+ bool const child_holds_a_propagating_state_source = a_child_holds_a_propagating_state_source && CSS::Invalidation::holds_a_propagating_state_source(*child);
- RemovalStyleRecordPins removal_style_record_pins { document().style_computer_if_created() };
- removal_style_record_pins.pin_style_records_before_removal(*child, was_tracked_by_style_engine);
+ if (was_tracked_by_style_engine)
+ pin_bound_box_style_records_for_detachment(*child);
if (was_tracked_by_style_engine) {
Layout::ForcedReadScope read { document() };
child->update_layout_tree_for_removal(read, *this, LayoutSubtreeRemoval::RebuildParent, ancestors_may_have_first_letter);
@@ -3216,11 +3138,12 @@ void Node::remove_all_children(bool suppress_observers)
// 10. If node has an inclusive descendant that is a slot, then:
child->assign_slottables_after_removal(*this, parent_root, descendant_slots);
- removal_style_record_pins.pin_style_records_after_removal(*child, was_connected);
+ if (!was_connected)
+ pin_bound_box_style_records_for_detachment(*child);
// NB: Republish the old chain before the removing steps clear the focused area.
- if (a_child_holds_a_propagating_state_source)
- CSS::Invalidation::invalidate_style_after_subtree_place_changed(*child, this);
+ if (child_holds_a_propagating_state_source)
+ CSS::Invalidation::invalidate_style_after_subtree_holding_a_state_source_left(*child, old_flat_tree_parent);
// 11. Run the removing steps with node, true, and parent.
// 12. Let isParentConnected be parent’s connected.
@@ -3229,8 +3152,6 @@ void Node::remove_all_children(bool suppress_observers)
// 14. For each shadow-including descendant descendant of node, in shadow-including tree order:
child->run_removing_steps(*this, parent_root, was_tracked_by_style_engine);
- removal_style_record_pins.release_dom_style_records();
-
// 15. Add transient registered observers given node and parent.
child->add_transient_registered_observers(*this);
@@ -4280,7 +4201,7 @@ static void add_to_attribute_name_filter_of_parent(Node& parent, Node const& chi
auto* parent_element = as_if<Element>(parent);
auto const* child_element = as_if<Element>(child);
if (parent_element && child_element)
- parent_element->add_to_subtree_attribute_name_filter(child_element->subtree_attribute_name_filter());
+ parent_element->add_to_subtree_name_filter(child_element->subtree_name_filter());
}
void Node::append_child_impl(GC::Ref<Node> node)
@@ -4335,28 +4256,6 @@ void Node::begin_child_index_generation()
});
}
-void Node::add_children_explicitly_inherited_non_inherited_style_groups(u32 style_groups)
-{
- auto const previous_groups = m_children_explicitly_inherited_non_inherited_style_groups;
- m_children_explicitly_inherited_non_inherited_style_groups |= style_groups;
- if (previous_groups != m_children_explicitly_inherited_non_inherited_style_groups)
- publish_children_explicitly_inherit_mark();
-}
-
-void Node::publish_children_explicitly_inherit_mark()
-{
- if (m_children_explicitly_inherited_non_inherited_style_groups == 0)
- return;
- // An element's or a shadow root's children are the ones that read it; the engine keeps no mark for anything else.
- CSS::StyleNodeID style_node;
- if (auto const* element = as_if<Element>(*this))
- style_node = element->style_node_id();
- else if (auto const* shadow_root = as_if<ShadowRoot>(*this))
- style_node = shadow_root->style_node_id();
- if (style_node != 0)
- CSS::StyleEngineFFI::style_engine_note_children_explicitly_inherit(document().style_computer().style_engine().host(), style_node, m_children_explicitly_inherited_non_inherited_style_groups);
-}
-
void Node::change_associated_animation_count_in_subtree(i32 delta)
{
for (auto* node = this; node; node = node->parent_or_shadow_host())
@@ -4400,9 +4299,9 @@ void Node::build_accessibility_tree(AccessibilityTreeNode& parent)
// absence of a layout node must not exclude it: it is included under the usual rules, and when it isn't (for
// a presentational role, e.g.), its children get flattened into its parent below.
auto is_display_contents = element->has_display_contents();
- auto const* inherited_box_values = element->style_group<CSS::ComputedValues::InheritedBoxValues>();
- auto is_visibility_hidden = inherited_box_values
- && static_cast<CSS::Visibility>(inherited_box_values->visibility) != CSS::Visibility::Visible;
+ auto const* inherited_values = element->style_inherited_set_values();
+ auto is_visibility_hidden = inherited_values
+ && CSS::visibility_from_inherited_bits(inherited_values->bits) != CSS::Visibility::Visible;
if (element->include_in_accessibility_tree()) {
auto current_node = AccessibilityTreeNode::create(this);
diff --git a/Libraries/LibWeb/DOM/Node.h b/Libraries/LibWeb/DOM/Node.h
index 22ba2cf6283..5e675a27f08 100644
--- a/Libraries/LibWeb/DOM/Node.h
+++ b/Libraries/LibWeb/DOM/Node.h
@@ -519,12 +519,6 @@ public:
[[nodiscard]] u32 associated_animation_count_in_subtree() const { return m_associated_animation_count_in_subtree; }
void change_associated_animation_count_in_subtree(i32 delta);
- [[nodiscard]] u32 children_explicitly_inherited_non_inherited_style_groups() const { return m_children_explicitly_inherited_non_inherited_style_groups; }
- void add_children_explicitly_inherited_non_inherited_style_groups(u32 style_groups);
- // Tell the style engine of this node's mark, which it keeps for the node's style node.
- void publish_children_explicitly_inherit_mark();
-
- void record_style_environment_change();
CSS::StyleScope& style_scope();
CSS::StyleScope const& style_scope() const { return const_cast<Node*>(this)->style_scope(); }
@@ -557,8 +551,6 @@ public:
bool is_shadow_including_inclusive_ancestor_of(Node const&) const;
[[nodiscard]] UniqueNodeID unique_id() const;
- // The node's unique id, without giving it one if it has none.
- [[nodiscard]] Optional<UniqueNodeID> unique_id_if_assigned() const;
static Node* from_unique_id(UniqueNodeID);
Optional<String> webdriver_node_id() const;
@@ -720,7 +712,6 @@ protected:
};
[[nodiscard]] u8 layout_tree_update_reuse_reasons() const;
- u32 m_children_explicitly_inherited_non_inherited_style_groups { 0 };
u32 m_associated_animation_count_in_subtree { 0 };
bool m_in_editable_subtree { false };
bool m_is_connected { false };
diff --git a/Libraries/LibWeb/DOM/PseudoElement.cpp b/Libraries/LibWeb/DOM/PseudoElement.cpp
index 8de732460c1..e9c8e5e6a7b 100644
--- a/Libraries/LibWeb/DOM/PseudoElement.cpp
+++ b/Libraries/LibWeb/DOM/PseudoElement.cpp
@@ -80,29 +80,42 @@ void SyntheticPseudoElement::update_animated_properties(Badge<Web::Animations::K
effect.update_computed_properties_for_style(context, abstract_element);
}
-void SyntheticPseudoElement::replace_style_record(CSS::StyleRecordID style_record_identity)
+void SyntheticPseudoElement::replace_installed_style(Layout::BegunRead const& read, CSS::InstalledStyle style)
{
VERIFY(m_originating_element);
- Layout::ForcedReadScope read { m_originating_element->document() };
+ auto const style_record_identity = style.record();
if (m_installed_style.record() == style_record_identity)
return;
auto& style_computer = m_originating_element->document().style_computer();
- m_installed_style = style_computer.install_style(read, style_record_identity);
+ auto held_before = exchange(m_installed_style, move(style));
// The pseudo-element holds the record it installed before until the engine takes the new one in, so the layout node
// reads what it moves from before the pseudo-element lets go of it.
if (auto* layout_node = unsafe_layout_node(read))
layout_node->set_style_record_identity(m_installed_style.record());
if (auto style_node_id = m_originating_element->style_node_id(); style_node_id != 0)
- CSS::StyleEngineFFI::style_engine_set_held_pseudo_style_record(style_computer.style_engine().host(), style_node_id, to_underlying(type()), style_record_identity.value());
+ CSS::StyleEngineFFI::style_engine_set_held_pseudo_style_record(style_computer.style_engine().host(), style_node_id, to_underlying(type()), style_record_identity.value(), held_before.record_pointer());
}
-void SyntheticPseudoElement::set_computed_style(CSS::StyleRecordID style_record_identity)
+void SyntheticPseudoElement::swap_in_style_record(Layout::BegunRead const& read, void const* record)
{
- if (!style_record_identity) {
+ VERIFY(m_originating_element);
+ CSS::InstalledStyle style { record };
+ auto const style_record = style.record();
+ VERIFY(style_record);
+ if (m_installed_style.record() == style_record)
+ return;
+ m_installed_style = move(style);
+ if (auto* layout_node = unsafe_layout_node(read))
+ layout_node->set_style_record_identity(style_record);
+}
+
+void SyntheticPseudoElement::set_computed_style(Layout::BegunRead const& read, CSS::InstalledStyle style)
+{
+ if (!style) {
clear_computed_style();
return;
}
- replace_style_record(style_record_identity);
+ replace_installed_style(read, move(style));
}
void SyntheticPseudoElement::clear_computed_style(RefPtr<CSS::ComputedValues const> style_to_preserve_for_detachment)
@@ -116,17 +129,11 @@ void SyntheticPseudoElement::clear_computed_style(RefPtr<CSS::ComputedValues con
layout_node->pin_style_record_for_detachment();
}
if (auto style_node_id = m_originating_element->style_node_id(); style_node_id != 0 && !!m_installed_style.record())
- CSS::StyleEngineFFI::style_engine_set_held_pseudo_style_record(m_originating_element->document().style_computer().style_engine().host(), style_node_id, to_underlying(type()), 0);
+ CSS::StyleEngineFFI::style_engine_set_held_pseudo_style_record(m_originating_element->document().style_computer().style_engine().host(), style_node_id, to_underlying(type()), 0, m_installed_style.record_pointer());
}
m_installed_style = {};
}
-void SyntheticPseudoElement::refresh_computed_style(CSS::StyleRecordID style_record_identity)
-{
- replace_style_record(style_record_identity);
- VERIFY(m_installed_style.record());
-}
-
SyntheticPseudoElementTreeNode::SyntheticPseudoElementTreeNode(CSS::PseudoElement type)
: SyntheticPseudoElement(type)
{
diff --git a/Libraries/LibWeb/DOM/PseudoElement.h b/Libraries/LibWeb/DOM/PseudoElement.h
index cac90df0a8b..808edc15d0b 100644
--- a/Libraries/LibWeb/DOM/PseudoElement.h
+++ b/Libraries/LibWeb/DOM/PseudoElement.h
@@ -59,9 +59,13 @@ public:
virtual CSS::InstalledStyle const& installed_style() const override { return m_installed_style; }
void update_animated_properties(Badge<Web::Animations::KeyframeEffect> const&, DOM::AbstractElement, Web::Animations::KeyframeEffect&, Web::Animations::AnimationUpdateContext&) override;
- void set_computed_style(CSS::StyleRecordID);
+ void set_computed_style(Layout::BegunRead const&, CSS::InstalledStyle);
+ // Swaps in a record a style installation installs, which the render side noted the pseudo-element holds, unless
+ // `tell_render_side` asks.
+ void swap_in_style_record(Layout::BegunRead const&, void const* record);
void clear_computed_style(RefPtr<CSS::ComputedValues const> style_to_preserve_for_detachment = nullptr);
- void refresh_computed_style(CSS::StyleRecordID);
+ // Installs `style`, which the engine just published for the pseudo-element, without asking the engine for it.
+ void replace_installed_style(Layout::BegunRead const&, CSS::InstalledStyle);
CSSPixelPoint scroll_offset() const { return m_scroll_offset; }
void set_scroll_offset(CSSPixelPoint);
@@ -70,8 +74,6 @@ public:
virtual void visit_edges(JS::Cell::Visitor&) override;
private:
- void replace_style_record(CSS::StyleRecordID);
-
CSS::PseudoElement m_type;
GC::Ptr<Element> m_originating_element;
// The authoritative StyleEngine record. C++ compatibility consumers borrow the record-owned
diff --git a/Libraries/LibWeb/DOM/ShadowRoot.cpp b/Libraries/LibWeb/DOM/ShadowRoot.cpp
index b807144595f..af807609e3d 100644
--- a/Libraries/LibWeb/DOM/ShadowRoot.cpp
+++ b/Libraries/LibWeb/DOM/ShadowRoot.cpp
@@ -85,9 +85,6 @@ void ShadowRoot::set_style_node_id(CSS::StyleNodeID style_node_id)
// the node that held it before left behind.
if (auto* arena = document().layout_node_arena_if_created(); arena && style_node_id != 0)
Layout::RustFFI::render_state_clear_layout_tree_update_marks(arena->host(), style_node_id.value());
- // The style engine keeps the mark of the children that explicitly inherit by identity too.
- if (style_node_id != 0)
- publish_children_explicitly_inherit_mark();
}
// https://fullscreen.spec.whatwg.org/#dom-document-fullscreenelement
diff --git a/Libraries/LibWeb/DOM/ShadowRoot.h b/Libraries/LibWeb/DOM/ShadowRoot.h
index e13702f1998..78eb7bea95d 100644
--- a/Libraries/LibWeb/DOM/ShadowRoot.h
+++ b/Libraries/LibWeb/DOM/ShadowRoot.h
@@ -186,6 +186,7 @@ private:
IntrusiveListNode<ShadowRoot> m_list_node;
IntrusiveListNode<ShadowRoot> m_slot_assignment_list_node;
+ IntrusiveListNode<ShadowRoot> m_counter_style_settle_list_node;
CSS::StyleScope m_style_scope;
@@ -203,6 +204,7 @@ private:
public:
using DocumentShadowRootList = IntrusiveList<&ShadowRoot::m_list_node>;
using DocumentSlotAssignmentList = IntrusiveList<&ShadowRoot::m_slot_assignment_list_node>;
+ using DocumentCounterStyleSettleList = IntrusiveList<&ShadowRoot::m_counter_style_settle_list_node>;
};
template<>
diff --git a/Libraries/LibWeb/DOM/Text.cpp b/Libraries/LibWeb/DOM/Text.cpp
index 0e0dc9ccc13..99678f07c91 100644
--- a/Libraries/LibWeb/DOM/Text.cpp
+++ b/Libraries/LibWeb/DOM/Text.cpp
@@ -18,7 +18,7 @@
namespace Web::DOM {
#if ARCH(X86_64) && !defined(AK_OS_WINDOWS)
-static_assert(sizeof(Text) == 144);
+static_assert(sizeof(Text) == 136);
#endif
struct Text::RareData final
diff --git a/Libraries/LibWeb/Editing/ReplacementStyleCleanup.cpp b/Libraries/LibWeb/Editing/ReplacementStyleCleanup.cpp
index 683618c73af..44650970561 100644
--- a/Libraries/LibWeb/Editing/ReplacementStyleCleanup.cpp
+++ b/Libraries/LibWeb/Editing/ReplacementStyleCleanup.cpp
@@ -9,6 +9,7 @@
#include <LibWeb/CSS/ComputedStyleWorkingSet.h>
#include <LibWeb/CSS/SerializationMode.h>
#include <LibWeb/CSS/StyleComputer.h>
+#include <LibWeb/CSS/StyleValues/PendingSubstitutionStyleValue.h>
#include <LibWeb/DOM/AbstractElement.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
@@ -36,6 +37,24 @@ static bool computed_property_values_are_equivalent(CSS::PropertyID property_id,
return false;
}
+// NB: A shorthand written with an arbitrary substitution function is a declaration beside the longhands pending it, and
+// only the longhands compute. They stay or go together, as a pending longhand alone would serialize to nothing.
+static bool inline_declaration_is_redundant(CSS::StyleProperty const& property, CSS::ComputedStyleWorkingSet const& with_inline_style, CSS::ComputedStyleWorkingSet const& without_inline_style)
+{
+ auto property_id = property.property_id;
+ if (property.value->is_pending_substitution()) {
+ ValueComparingNonnullRefPtr<CSS::StyleValue const> written = property.value;
+ while (written->as_pending_substitution().original_shorthand_value()->is_pending_substitution())
+ written = written->as_pending_substitution().original_shorthand_value();
+ property_id = written->as_pending_substitution().original_shorthand();
+ }
+ if (!CSS::property_is_shorthand(property_id))
+ return computed_property_values_are_equivalent(property_id, with_inline_style, without_inline_style);
+ return all_of(CSS::expanded_longhands_for_shorthand(property_id), [&](auto longhand_id) {
+ return computed_property_values_are_equivalent(longhand_id, with_inline_style, without_inline_style);
+ });
+}
+
void remove_redundant_styles_from_inserted_content(Layout::BegunRead const& read, InsertedContent& inserted_content)
{
GC::RootVector<GC::Ref<DOM::Element>> styled_elements;
@@ -69,16 +88,16 @@ void remove_redundant_styles_from_inserted_content(Layout::BegunRead const& read
auto style_with_inline_declaration = style_computer.reconstruct_computed_properties(*computed_values);
// What the element would compute to without its inline declaration, which the style engine answers privately
// without touching the live element. An element it gives no answer for keeps its inline style.
- auto answer = style_computer.style_engine().answer_record_demand(read, element->style_node_id(), CSS::StyleEngine::RecordDemand::ElementReadWithoutInlineStyle).record;
- auto view = style_computer.computed_style_record_view(read, CSS::StyleRecordID { answer.style_record });
- if (!view)
+ CSS::InstalledStyle const style { style_computer.style_engine().answer_record_demand(read, element->style_node_id(), CSS::StyleEngine::RecordDemand::ElementReadWithoutInlineStyle).record.host_record };
+ if (!style)
continue;
+ auto view = style_computer.computed_style_record_view(style);
auto style_without_inline_declaration = style_computer.reconstruct_computed_properties(*view);
Vector<CSS::StyleProperty> retained_properties;
retained_properties.ensure_capacity(inline_style->properties().size());
for (auto const& property : inline_style->properties()) {
- if (!computed_property_values_are_equivalent(property.property_id, *style_with_inline_declaration, *style_without_inline_declaration))
+ if (!inline_declaration_is_redundant(property, *style_with_inline_declaration, *style_without_inline_declaration))
retained_properties.append(property);
}
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 9f6677c5236..89917c60d6a 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -207,6 +207,7 @@ class BackgroundSizeStyleValue;
class BlurFilterStyleValue;
class CalculatedStyleValue;
class CustomPropertyData;
+enum class IsAnimationOverlay : bool;
class ColorFilterStyleValue;
class ColorFunctionStyleValue;
class ColorSchemeStyleValue;
diff --git a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
index 9c21dfe62de..fbe7d8923c1 100644
--- a/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
+++ b/Libraries/LibWeb/HTML/Canvas/Canvas2DContextBase.cpp
@@ -418,8 +418,8 @@ static bool resolve_font(CanvasType& canvas_element, Utf16View font, CanvasFontS
auto& document = canvas_element.document();
Layout::ForcedReadScope read { document };
document.update_style_for_element(DOM::AbstractElement { canvas_element }, DOM::Document::StyleUpdateMode::OnlyIfNeeded);
- auto style_record = canvas_element.style_record_identity();
- if (!style_record || has_flag(document.style_computer().style_engine().style_record_dependency_flags(read, style_record), CSS::StyleRecordDependencyFlag::InDisplayNoneSubtree))
+ auto const& style = canvas_element.installed_style();
+ if (!style || has_flag(style.dependency_flags(), CSS::StyleRecordDependencyFlag::InDisplayNoneSubtree))
document.update_style_for_element(DOM::AbstractElement { canvas_element });
if (canvas_element.navigable() && canvas_element.is_connected()) {
diff --git a/Libraries/LibWeb/HTML/Focus.cpp b/Libraries/LibWeb/HTML/Focus.cpp
index f37c0392d6e..530be40f4a0 100644
--- a/Libraries/LibWeb/HTML/Focus.cpp
+++ b/Libraries/LibWeb/HTML/Focus.cpp
@@ -104,6 +104,20 @@ static bool is_top_level_document_viewport(DOM::Node const* node)
return document && document->navigable() && !document->navigable()->parent();
}
+// Whether a listener can run on `element` as its blur and focusout events are dispatched: on its flat tree path, or on
+// its document or window.
+static bool a_handler_may_read_style_during_blur(DOM::Element& element)
+{
+ auto listens = [](DOM::EventTarget const& target) {
+ return target.has_event_listener(HTML::EventNames::blur) || target.has_event_listener(HTML::EventNames::focusout);
+ };
+ for (DOM::Node* node = &element; node; node = node->flat_tree_parent()) {
+ if (listens(*node))
+ return true;
+ }
+ return listens(element.document()) || listens(relevant_window(element));
+}
+
// https://html.spec.whatwg.org/multipage/interaction.html#focus-update-steps
void run_focus_update_steps(Vector<GC::Root<DOM::Node>> old_chain, Vector<GC::Root<DOM::Node>> new_chain, GC::Ptr<DOM::Node> new_focus_target)
{
@@ -121,6 +135,8 @@ void run_focus_update_steps(Vector<GC::Root<DOM::Node>> old_chain, Vector<GC::Ro
auto new_focus_target_is_document_viewport = new_focus_target && new_focus_target->is_document();
GC::Ptr<DOM::Node> focus_transition_source;
Vector<GC::Root<DOM::Element>> old_focus_within_chain;
+ bool focus_transition_source_indicated_focus = false;
+ bool focus_state_published_for_blur_handlers = false;
auto build_focus_within_chain = [](GC::Ptr<DOM::Node> source) {
Vector<GC::Root<DOM::Element>> chain;
@@ -134,9 +150,29 @@ void run_focus_update_steps(Vector<GC::Root<DOM::Node>> old_chain, Vector<GC::Ro
return chain;
};
+ // AD-HOC: What a blur handler reads of the old area's style is what it matches now, while the focusability check of
+ // the new area runs over the state the old area left, so that a selector keeping the new area rendered
+ // does not hide it first.
+ auto publish_focus_state_of_transition_source = [&](bool focused) {
+ auto* element = as_if<DOM::Element>(focus_transition_source.ptr());
+ if (!element)
+ return;
+ CSS::record_element_state_changed(*element, CSS::PseudoClass::Focus, focused);
+ if (focus_transition_source_indicated_focus)
+ CSS::record_element_state_changed(*element, CSS::PseudoClass::FocusVisible, focused);
+ for (auto& ancestor : old_focus_within_chain)
+ CSS::record_element_state_changed(*ancestor, CSS::PseudoClass::FocusWithin, focused);
+ };
+
+ auto restore_focus_state_for_focusability_check = [&] {
+ if (exchange(focus_state_published_for_blur_handlers, false))
+ publish_focus_state_of_transition_source(true);
+ };
+
auto finish_focus_transition = [&](GC::Ptr<DOM::Node> destination) {
if (!focus_transition_source)
return;
+ restore_focus_state_for_focusability_check();
CSS::Invalidation::invalidate_style_after_pseudo_class_state_change(CSS::PseudoClass::Focus, focus_transition_source, destination);
CSS::Invalidation::invalidate_style_after_pseudo_class_state_change(CSS::PseudoClass::FocusVisible, focus_transition_source, destination);
@@ -223,8 +259,13 @@ void run_focus_update_steps(Vector<GC::Root<DOM::Node>> old_chain, Vector<GC::Ro
if (preserve_focus_state) {
focus_transition_source = element;
old_focus_within_chain = build_focus_within_chain(element);
+ focus_transition_source_indicated_focus = element->should_indicate_focus();
}
element->document().set_focused_area(nullptr, preserve_focus_state ? DOM::Document::InvalidateFocusPseudoClasses::No : DOM::Document::InvalidateFocusPseudoClasses::Yes);
+ if (preserve_focus_state && a_handler_may_read_style_during_blur(*element)) {
+ publish_focus_state_of_transition_source(false);
+ focus_state_published_for_blur_handlers = true;
+ }
}
// 4. If blur event target is not null, fire a focus event named blur at blur event target, with related blur
@@ -262,6 +303,7 @@ void run_focus_update_steps(Vector<GC::Root<DOM::Node>> old_chain, Vector<GC::Ro
if (entry->is_document()) {
designate_document_viewport_as_focused_area(entry->document());
} else if (entry->document().focused_area().ptr() != entry.ptr()) {
+ restore_focus_state_for_focusability_check();
if (entry->is_focusable()) {
relevant_window(*entry).navigation()->set_focus_changed_during_ongoing_navigation(true);
diff --git a/Libraries/LibWeb/HTML/HTMLButtonElement.cpp b/Libraries/LibWeb/HTML/HTMLButtonElement.cpp
index 747182dae4b..66793bbf760 100644
--- a/Libraries/LibWeb/HTML/HTMLButtonElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLButtonElement.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <LibWeb/CSS/Invalidation/FormControlInvalidator.h>
#include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Event.h>
@@ -82,8 +83,11 @@ void HTMLButtonElement::form_associated_element_attribute_changed(Utf16FlyString
{
PopoverTargetAttributes::associated_attribute_changed(name, value, namespace_);
- if (name == AttributeNames::type && !namespace_.has_value())
+ if (name == AttributeNames::type && !namespace_.has_value()) {
m_type_state = parse_type_attribute(value);
+ // The type decides whether the button is a candidate for constraint validation.
+ CSS::Invalidation::invalidate_style_after_validity_change(*this);
+ }
if (name.is_one_of(AttributeNames::type, AttributeNames::command, AttributeNames::commandfor)) {
submit_button_state_changed();
diff --git a/Libraries/LibWeb/HTML/HTMLElement.cpp b/Libraries/LibWeb/HTML/HTMLElement.cpp
index e4f08100425..ce577607135 100644
--- a/Libraries/LibWeb/HTML/HTMLElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLElement.cpp
@@ -639,7 +639,7 @@ static Vector<RenderedTextItem> rendered_text_collection_steps(Layout::BegunRead
if (auto const* layout_text_node = as_if<Layout::TextNode>(layout_node)) {
items.append(UnprocessedText {
layout_text_node->rendered_text_for_dom(),
- style_node.style_group<CSS::ComputedValues::InheritedTextValues>().white_space_collapse_value(),
+ CSS::white_space_collapse_from_inherited_bits(style_node.inherited_set_values().bits),
});
return items;
}
@@ -860,9 +860,9 @@ GC::Ptr<DOM::Element> HTMLElement::offset_parent() const
// fixed, and no ancestor establishes a fixed position containing block, terminate this algorithm and return
// null.
bool ancestor_is_closed_shadow_hidden = ancestor->is_closed_shadow_hidden_from(*this);
- auto const* ancestor_box_values = ancestor->style_group<CSS::ComputedValues::BoxValues>();
- VERIFY(ancestor_box_values);
- bool ancestor_is_fixed_position = static_cast<CSS::Positioning>(ancestor_box_values->position) == CSS::Positioning::Fixed;
+ auto ancestor_reset_bits = ancestor->style_reset_bits();
+ VERIFY(ancestor_reset_bits.has_value());
+ bool ancestor_is_fixed_position = CSS::position_from_reset_bits(*ancestor_reset_bits) == CSS::Positioning::Fixed;
auto const* ancestor_layout_node = ancestor->layout_node(read);
if (ancestor_is_closed_shadow_hidden
&& ancestor_is_fixed_position
@@ -1150,6 +1150,17 @@ void HTMLElement::attribute_changed(Utf16FlyString const& name, Optional<Utf16St
void HTMLElement::set_subtree_inertness(bool is_inert)
{
+ // NB: An inert element behaves as if it were not editable, which :read-write and :read-only tell.
+ struct PreviousReadWriteState {
+ GC::Ptr<DOM::Element> element;
+ bool value;
+ };
+ GC::ConservativeVector<PreviousReadWriteState> previous_read_write_states;
+ for_each_in_inclusive_subtree_of_type<DOM::Element>([&](DOM::Element& element) {
+ previous_read_write_states.append({ element, SelectorMatching::element_matches_state(element, CSS::PseudoClass::ReadWrite) });
+ return TraversalDecision::Continue;
+ });
+
auto repaint_if_inertness_reaches_painted_output = [](DOM::Node& node) {
node.publish_dom_paint_facts();
};
@@ -1173,6 +1184,8 @@ void HTMLElement::set_subtree_inertness(bool is_inert)
update_inertness(*html_element);
return TraversalDecision::Continue;
});
+ for (auto const& state : previous_read_write_states)
+ CSS::Invalidation::invalidate_style_after_read_write_state_change(*state.element, state.value);
document().page().keyboard_scroll_editability_changed(document());
}
diff --git a/Libraries/LibWeb/HTML/HTMLOrSVGOrMathMLElement.cpp b/Libraries/LibWeb/HTML/HTMLOrSVGOrMathMLElement.cpp
index ab095003aad..4f1ba0f1498 100644
--- a/Libraries/LibWeb/HTML/HTMLOrSVGOrMathMLElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLOrSVGOrMathMLElement.cpp
@@ -182,7 +182,7 @@ void HTMLOrSVGOrMathMLElement<ElementBase>::inserted()
// https://html.spec.whatwg.org/multipage/interaction.html#the-autofocus-attribute
// OPTIMIZATION: The subtree attribute name filter rules out the attribute for most elements without a lookup.
- auto might_have_autofocus = (element.subtree_attribute_name_filter() & DOM::Element::attribute_name_filter_bit(HTML::AttributeNames::autofocus)) != 0;
+ auto might_have_autofocus = (element.subtree_name_filter() & DOM::Element::name_filter_bit(HTML::AttributeNames::autofocus)) != 0;
if (might_have_autofocus && element.has_attribute(HTML::AttributeNames::autofocus)) {
// When an element with the autofocus attribute specified is inserted into a document, run the following steps:
diff --git a/Libraries/LibWeb/HTML/LocalNavigable.cpp b/Libraries/LibWeb/HTML/LocalNavigable.cpp
index e306d91f846..07fb975631b 100644
--- a/Libraries/LibWeb/HTML/LocalNavigable.cpp
+++ b/Libraries/LibWeb/HTML/LocalNavigable.cpp
@@ -4695,6 +4695,7 @@ void LocalNavigable::set_viewport_size(CSSPixelSize size, InvalidateDisplayList
if (m_viewport_size == size && invalidate_display_list == InvalidateDisplayList::No)
return;
+ auto previous_viewport_size = m_viewport_size;
m_viewport_size = size;
if (has_compositor_context()) {
@@ -4705,10 +4706,11 @@ void LocalNavigable::set_viewport_size(CSSPixelSize size, InvalidateDisplayList
}
if (auto document = active_document()) {
+ // NB: A display list invalidated with the viewport is for a device pixel ratio that moved, as a zoom moves it.
if (invalidate_display_list == InvalidateDisplayList::PaintCommandsAndHitTestList)
- document->record_style_environment_change();
- else
- document->invalidate_style_for_viewport_change();
+ document->record_style_environment_change(DOM::StyleEnvironmentChange::DevicePixelRatio | DOM::StyleEnvironmentChange::MediaFeatures);
+ if (previous_viewport_size != size)
+ document->invalidate_style_for_viewport_change(previous_viewport_size);
document->set_needs_media_query_evaluation();
document->set_needs_layout_update(DOM::SetNeedsLayoutReason::NavigableSetViewportSize);
}
@@ -7369,7 +7371,7 @@ void LocalNavigable::abort_in_flight_smooth_scrolls_taken_over_by_user_input(Web
static bool scrolls_smoothly(Bindings::ScrollBehavior behavior, GC::Ptr<DOM::Element> associated_element)
{
if (behavior == Bindings::ScrollBehavior::Auto && associated_element) {
- if (auto const* values = associated_element->style_group<CSS::ComputedValues::MiscResetValues>())
+ if (auto const* values = associated_element->style_group<CSS::ComputedValues::MiscInteractionValues>())
return static_cast<CSS::ScrollBehavior>(values->scroll_behavior) == CSS::ScrollBehavior::Smooth;
}
return behavior == Bindings::ScrollBehavior::Smooth;
@@ -7983,8 +7985,8 @@ void LocalNavigable::reset_zoom()
bool LocalNavigable::has_inclusive_ancestor_with_visibility_hidden() const
{
if (auto container = this->container()) {
- if (auto const* values = container->style_group<CSS::ComputedValues::InheritedBoxValues>()) {
- if (static_cast<CSS::Visibility>(values->visibility) == CSS::Visibility::Hidden)
+ if (auto const* values = container->style_inherited_set_values()) {
+ if (CSS::visibility_from_inherited_bits(values->bits) == CSS::Visibility::Hidden)
return true;
}
if (auto ancestor_navigable = container->document().navigable()) {
diff --git a/Libraries/LibWeb/HTML/NavigableContainer.cpp b/Libraries/LibWeb/HTML/NavigableContainer.cpp
index 5cb3f059906..5ec2b43d3fa 100644
--- a/Libraries/LibWeb/HTML/NavigableContainer.cpp
+++ b/Libraries/LibWeb/HTML/NavigableContainer.cpp
@@ -599,8 +599,8 @@ void NavigableContainer::report_content_navigable_viewport_rect(Layout::BegunRea
visible.intersect({ {}, content_box.size() });
if (Core::StatsLog::the()) {
bool displayed = !visible.is_empty() && !document().navigable()->has_inclusive_ancestor_with_visibility_hidden();
- if (auto const* values = style_group<CSS::ComputedValues::InheritedBoxValues>())
- displayed &= static_cast<CSS::Visibility>(values->visibility) != CSS::Visibility::Hidden;
+ if (auto const* values = style_inherited_set_values())
+ displayed &= CSS::visibility_from_inherited_bits(values->bits) != CSS::Visibility::Hidden;
report_stats_displayed(displayed);
}
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index 67f580517f8..9b55fc806d2 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -18,6 +18,7 @@
#include <LibGC/RootVector.h>
#include <LibTextCodec/Decoder.h>
#include <LibWeb/CSS/Parser/Parser.h>
+#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>
#include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
#include <LibWeb/CSS/StyleValues/PercentageStyleValue.h>
@@ -2968,6 +2969,7 @@ extern "C" void ladybird_html_parser_set_document_quirks_mode(void* parser, Rust
auto& document = parser_from_html_parser_ffi(parser).document();
if (!document.parser_cannot_change_the_mode())
document.set_quirks_mode(quirks_mode_from_html_parser_ffi(mode));
+ CSS::prepare_non_author_stylesheets(document);
}
extern "C" bool ladybird_html_parser_document_is_iframe_srcdoc_document(void* parser)
diff --git a/Libraries/LibWeb/Page/EventHandler.cpp b/Libraries/LibWeb/Page/EventHandler.cpp
index 7f4c0369388..5b04ce3d5c0 100644
--- a/Libraries/LibWeb/Page/EventHandler.cpp
+++ b/Libraries/LibWeb/Page/EventHandler.cpp
@@ -130,8 +130,14 @@ static GC::Ptr<DOM::Node> associated_descendant_editing_host(Layout::BegunRead c
return editing_host;
}
- if (ancestor != &node && ancestor->is_focusable())
- break;
+ if (ancestor != &node) {
+ auto ancestor_is_focusable = ancestor->is_focusable();
+ // NB: Asking whether an element is focusable catches up its style, animations included, which can leave
+ // layout stale for what is read of it next.
+ node.document().update_layout(DOM::UpdateLayoutReason::EventHandlerHandleMouseDown);
+ if (ancestor_is_focusable)
+ break;
+ }
}
return nullptr;
diff --git a/Libraries/LibWeb/Page/Page.cpp b/Libraries/LibWeb/Page/Page.cpp
index fbef33d4b94..579a44b4d66 100644
--- a/Libraries/LibWeb/Page/Page.cpp
+++ b/Libraries/LibWeb/Page/Page.cpp
@@ -14,6 +14,7 @@
#include <LibIPC/Encoder.h>
#include <LibWeb/Bindings/CSS.h>
#include <LibWeb/CSS/StyleComputer.h>
+#include <LibWeb/CSS/StyleEngineInput.h>
#include <LibWeb/Compositor/CompositorHost.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
@@ -2014,13 +2015,15 @@ void Page::invalidate_user_style()
if (!has_top_level_traversable())
return;
+ // NB: The new user sheet is attached in place of the old one, which restyles the elements the rules of either
+ // match. It is attached now, so a style read before the next style update sees it pending. Its rules
+ // match in shadow trees as in the document, and the animations naming its @keyframes, which the document's
+ // scope publishes, are planned again, so no element of a shadow tree restyles for it otherwise.
auto invalidate_document = [](DOM::Document& document) {
document.invalidate_content_blocker_style_sheet();
document.style_scope().invalidate_user_style_sheet();
- document.for_each_shadow_root([](auto& shadow_root) {
- shadow_root.record_style_environment_change();
- });
- document.record_style_environment_change();
+ if (document.style_computer_if_created())
+ CSS::record_non_author_stylesheets(document);
};
// Each page invalidates the documents it hosts.
@@ -2036,7 +2039,7 @@ void Page::invalidate_style_for_preference_change()
return;
auto invalidate_document = [](DOM::Document& document) {
- document.record_style_environment_change();
+ document.record_style_environment_change(DOM::StyleEnvironmentChange::ColorScheme | DOM::StyleEnvironmentChange::MediaFeatures);
document.set_needs_media_query_evaluation();
};
diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rs
index 07a95830b76..5034f14f8fe 100644
--- a/Libraries/LibWeb/Rust/build.rs
+++ b/Libraries/LibWeb/Rust/build.rs
@@ -442,15 +442,13 @@ fn write_enum_and_from_ffi(output: &mut String, enum_name: &str, variants: &[Str
}
writeln!(output, "}}").unwrap();
writeln!(output).unwrap();
- // Only the pseudo-classes cross the boundary as numbers.
- if enum_name != "PseudoClassType" {
- return;
- }
- writeln!(
- output,
- "pub(crate) fn pseudo_class_from_ffi(value: u8) -> {enum_name} {{"
- )
- .unwrap();
+ // The pseudo-classes cross the boundary as numbers, and parsed selectors hold both kinds as numbers.
+ let function_name = match enum_name {
+ "PseudoClassType" => "pseudo_class_from_ffi",
+ "PseudoElementType" => "pseudo_element_from_ffi",
+ _ => return,
+ };
+ writeln!(output, "pub(crate) fn {function_name}(value: u8) -> {enum_name} {{").unwrap();
writeln!(output, " match value {{").unwrap();
for (index, variant) in variants.iter().enumerate() {
writeln!(output, " {index} => {enum_name}::{variant},").unwrap();
@@ -663,7 +661,7 @@ fn generate_selector_pseudo_types(manifest_dir: &Path, out_dir: &Path) -> Result
let mut compiler_mapping = String::from(
"// Generated by build.rs from CSS/PseudoClasses.json.\n\n\
- fn state_fact_for(pseudo_class: PseudoClassType) -> Option<StateFact> {\n\
+ pub(super) fn state_fact_for(pseudo_class: PseudoClassType) -> Option<StateFact> {\n\
\x20 match pseudo_class {\n",
);
for name in &state_fact_names {
@@ -1035,29 +1033,28 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
affects_hit_testing[index] = metadata_flag("affects-hit-testing", false);
let style_group = property_field(name, "style-group").and_then(|value| value.as_str().map(str::to_owned));
style_group_indices[index] = match style_group.as_deref() {
- Some("InheritedTableValues") => 0,
- Some("InheritedListValues") => 1,
- Some("InheritedUIValues") => 2,
- Some("InheritedSVGValues") => 3,
- Some("InheritedTextValues") => 4,
- Some("InheritedBoxValues") => 5,
- Some("FontValues") => 6,
- Some("AnimationValues") => 7,
- Some("SVGResetValues") => 8,
- Some("GridValues") => 9,
- Some("AnchorValues") => 10,
- Some("EffectsValues") => 11,
- Some("MaskValues") => 12,
- Some("TextResetValues") => 13,
- Some("ContentValues") => 14,
- Some("TransformValues") => 15,
- Some("BackgroundValues") => 16,
- Some("BorderValues") => 17,
- Some("AlignmentValues") => 18,
- Some("MiscResetValues") => 19,
- Some("SizingValues") => 20,
- Some("SurroundValues") => 21,
- Some("BoxValues") => 22,
+ Some("InheritedListTableValues") => 0,
+ Some("InheritedUIValues") => 1,
+ Some("InheritedSVGValues") => 2,
+ Some("InheritedTextValues") => 3,
+ Some("FontValues") => 4,
+ Some("AnimationValues") => 5,
+ Some("SVGResetValues") => 6,
+ Some("GridValues") => 7,
+ Some("AnchorValues") => 8,
+ Some("ContentValues") => 9,
+ Some("AlignmentValues") => 10,
+ Some("MiscLayoutValues") => 11,
+ Some("MiscInteractionValues") => 12,
+ Some("EffectsValues") => 13,
+ Some("MaskValues") => 14,
+ Some("TextResetValues") => 15,
+ Some("TransformValues") => 16,
+ Some("BackgroundValues") => 17,
+ Some("BorderValues") => 18,
+ Some("SizingValues") => 19,
+ Some("SurroundValues") => 20,
+ Some("BoxValues") => 21,
Some(group) => return Err(format!("unknown style group '{group}' for {name}").into()),
None => u8::MAX,
};
@@ -1630,7 +1627,7 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
idl_names
));
output.push_str(&format!(
- "pub(crate) static PROPERTY_IS_LOGICAL_ALIAS: [bool; {}] = {:?};\n\n",
+ "pub(crate) const PROPERTY_IS_LOGICAL_ALIAS: [bool; {}] = {:?};\n\n",
logical_aliases.len(),
logical_aliases
));
@@ -1640,7 +1637,7 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
logical_groups
));
output.push_str(&format!(
- "pub(crate) static LOGICAL_ALIAS_TO_PHYSICAL: [u16; {}] = {:?};\n\n",
+ "pub(crate) const LOGICAL_ALIAS_TO_PHYSICAL: [u16; {}] = {:?};\n\n",
logical_alias_to_physical.len(),
logical_alias_to_physical
));
@@ -1781,7 +1778,7 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),
affects_hit_testing
));
output.push_str(&format!(
- "pub(crate) static PROPERTY_STYLE_GROUP_INDICES: [u8; {}] = {:?};\n",
+ "pub(crate) const PROPERTY_STYLE_GROUP_INDICES: [u8; {}] = {:?};\n",
style_group_indices.len(),
style_group_indices
));
@@ -2118,6 +2115,17 @@ fn generate_css_enums(manifest_dir: &Path, out_dir: &Path) -> Result<(), Box<dyn
output.push_str(&format!(" \"{value}\",\n"));
}
output.push_str(" ];\n");
+ // The keyword of each member, indexed by value code, as a style holding the code reads it.
+ output.push_str(&format!(" pub const KEYWORDS: [u16; {code}] = [\n"));
+ for value in values {
+ let value = value.as_str().ok_or("enum value is not a string")?;
+ if value.contains('=') {
+ continue;
+ }
+ let keyword_constant = value.replace('-', "_").to_uppercase();
+ output.push_str(&format!(" super::keyword::{keyword_constant},\n"));
+ }
+ output.push_str(" ];\n");
output.push_str("}\n\n");
// The keyword-to-enum-value mapping, mirroring the C++ keyword_to_<enum> generator,
@@ -2513,6 +2521,17 @@ fn main() -> Result<(), Box<dyn Error>> {
.export
.exclude
.push("CalcReificationStorage".to_string());
+ // A style value list keeps its element count in the word before its first element.
+ style_value_config.export.body.insert(
+ "RetainedStyleValueDataList".to_string(),
+ " size_t length() const { return pointer ? reinterpret_cast<size_t const*>(pointer)[-1] : 0; }".to_string(),
+ );
+ // C++ reads a boxed variant payload through the box as through a pointer.
+ style_value_config.export.body.insert(
+ "StyleValueBox".to_string(),
+ " T const* operator->() const { return pointer; }\n T const& operator*() const { return *pointer; }"
+ .to_string(),
+ );
// A compositor keyframe value is substituted by the document's style engine, which the document host reaches.
declare_document_host_of_layout_header(&mut style_value_config);
@@ -2606,6 +2625,7 @@ fn main() -> Result<(), Box<dyn Error>> {
manifest_dir.join("src/css/style_rule.rs"),
manifest_dir.join("src/css/scope_selectors.rs"),
manifest_dir.join("src/css/media_list.rs"),
+ manifest_dir.join("src/css/inline_style_blocks.rs"),
manifest_dir.join("src/css/counter_representation.rs"),
manifest_dir.join("src/css/counter_style.rs"),
manifest_dir.join("src/css/namespace_rule.rs"),
@@ -2661,7 +2681,7 @@ fn main() -> Result<(), Box<dyn Error>> {
);
// The host queues the engine's changes on the document host, which the layout header declares.
declare_document_host_of_layout_header(&mut style_engine_config);
- // A style transaction flies only where nothing blocks it, which the layout header names as it does for a recording.
+ // A style update flies only where nothing blocks it, which the layout header names as it does for a recording.
style_engine_config.export.rename.insert(
"FfiFlightBlocker".to_string(),
"Web::Layout::RustFFI::FfiFlightBlocker".to_string(),
@@ -2707,10 +2727,17 @@ fn main() -> Result<(), Box<dyn Error>> {
style_engine_config,
&[
manifest_dir.join("src/css/style/bridge.rs"),
+ manifest_dir.join("src/css/style/bridge/animations.rs"),
+ manifest_dir.join("src/css/style/bridge/container_effects.rs"),
+ manifest_dir.join("src/css/style/bridge/native_rules.rs"),
+ manifest_dir.join("src/css/style/bridge/records.rs"),
manifest_dir.join("src/css/style/identities.rs"),
manifest_dir.join("src/css/style/engine_calls.rs"),
manifest_dir.join("src/css/style/host_atoms.rs"),
manifest_dir.join("src/css/style/reaction_application.rs"),
+ manifest_dir.join("src/css/style/pipeline/install.rs"),
+ manifest_dir.join("src/css/style/pipeline/main_effects.rs"),
+ manifest_dir.join("src/css/style/pipeline/matched_rules.rs"),
manifest_dir.join("src/css/style/rule_writes.rs"),
manifest_dir.join("src/css/style/style_job.rs"),
manifest_dir.join("src/css/ffi_support.rs"),
@@ -2734,7 +2761,6 @@ fn main() -> Result<(), Box<dyn Error>> {
"BoxValues".to_string(),
"ComputedVerticalAlign".to_string(),
"GridValues".to_string(),
- "STYLE_GROUP_STATIC_REFCOUNT".to_string(),
"GENERATED_CONTENT_DEFINES_COUNTERS".to_string(),
"GENERATED_CONTENT_DEFINES_LIST_ITEM_COUNTER".to_string(),
"GENERATED_CONTENT_SHOWS_LIST_ITEM_COUNTER".to_string(),
@@ -2758,8 +2784,10 @@ fn main() -> Result<(), Box<dyn Error>> {
"ComputedTextUnderlinePosition".to_string(),
"ComputedTextUnderlineOffset".to_string(),
"InheritedTextValues".to_string(),
- "InheritedTableValues".to_string(),
- "InheritedBoxValues".to_string(),
+ "InheritedListTableValues".to_string(),
+ "InheritedBits".to_string(),
+ "ResetBits".to_string(),
+ "InheritedSetValues".to_string(),
"SizingValues".to_string(),
"AlignmentValues".to_string(),
"SVGResetValues".to_string(),
@@ -2769,18 +2797,17 @@ fn main() -> Result<(), Box<dyn Error>> {
"MaskValues".to_string(),
"BackgroundValues".to_string(),
"BorderValues".to_string(),
- "InheritedListValues".to_string(),
"ContentValues".to_string(),
"ComputedOverflowClipMarginSide".to_string(),
"ComputedOverflowClipMargin".to_string(),
- "MiscResetValues".to_string(),
+ "MiscLayoutValues".to_string(),
+ "MiscInteractionValues".to_string(),
"FontValues".to_string(),
"FontCascadeListHandle".to_string(),
"FrozenFontListRef".to_string(),
"FfiFontGroupBuildInputs".to_string(),
"TextResetValues".to_string(),
"AnchorValues".to_string(),
- "FfiTableInheritanceDependentValue".to_string(),
"FfiEffectiveLonghandValue".to_string(),
"FfiUtf16View".to_string(),
"EFFECTIVE_LONGHAND_SOURCE_TABLE".to_string(),
@@ -2811,13 +2838,13 @@ fn main() -> Result<(), Box<dyn Error>> {
computed_values_config.export.exclude.push(name.to_string());
}
computed_values_config.export.rename.insert(
- "DeclarationBlockData".to_string(),
- "Web::CSS::Parser::ValueParserFFI::DeclarationBlockData".to_string(),
+ "DeclarationBlockHeader".to_string(),
+ "Web::CSS::Parser::ValueParserFFI::DeclarationBlockHeader".to_string(),
);
computed_values_config
.after_includes
.get_or_insert_with(String::new)
- .push_str("\nnamespace Web::CSS::Parser::ValueParserFFI { struct DeclarationBlockData; }");
+ .push_str("\nnamespace Web::CSS::Parser::ValueParserFFI { struct DeclarationBlockHeader; }");
// The computations C++ hands a style value take the value as the style value header declares it.
computed_values_config.export.rename.insert(
"StyleValueData".to_string(),
@@ -2848,6 +2875,7 @@ fn main() -> Result<(), Box<dyn Error>> {
manifest_dir.join("src/css/computed_values.rs"),
manifest_dir.join("src/css/property_metadata.rs"),
manifest_dir.join("src/css/style_compute.rs"),
+ manifest_dir.join("src/css/style_compute/adjustments.rs"),
manifest_dir.join("src/css/display.rs"),
manifest_dir.join("src/css/computed_value_types.rs"),
manifest_dir.join("src/css/retained_fly_string.rs"),
diff --git a/Libraries/LibWeb/Rust/cbindgen.toml b/Libraries/LibWeb/Rust/cbindgen.toml
index ea41b8458b1..be12c67e938 100644
--- a/Libraries/LibWeb/Rust/cbindgen.toml
+++ b/Libraries/LibWeb/Rust/cbindgen.toml
@@ -32,5 +32,10 @@ rename_types = "PascalCase"
"SpanMut" = "AK::Span"
# A style engine handle is opaque to C++.
"StyleEngineHandle" = "const void*"
+# What an unresolved value's text holds, as bits C++ does not read.
+"UnresolvedFacts" = "uint16_t"
+# A style value C++ hands back or lends is the pointer at the value it was given.
+"OwnedStyleValue" = "const Web::CSS::StyleValueFFI::StyleValueData*"
+"StyleValueRef" = "const Web::CSS::StyleValueFFI::StyleValueData*"
# So is a parsed syntax, which C++ holds by pointer.
"SyntaxNode" = "void"
diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge.rs b/Libraries/LibWeb/Rust/src/css/style/bridge.rs
index ec96d508f5d..655cef1ee77 100644
--- a/Libraries/LibWeb/Rust/src/css/style/bridge.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/bridge.rs
@@ -31,35 +31,40 @@ use std::ffi::c_void;
use crate::abort_on_panic;
use crate::css::animated_overlay::AnimatedOverlay;
-use crate::css::computed_longhand_table::ComputedLonghandTable;
use crate::css::custom_properties::CustomPropertyRegistry;
-use crate::css::host_shared::{HostShared, SharedPayload};
-use crate::css::selector::CompiledSelector;
+use crate::css::host_shared::HostShared;
+use crate::css::selector::SelectorListRef;
use crate::css::style_value::RetainedStyleValueData;
-use super::batch_matcher::RuleMatch;
-
use super::compiler::ImplicitScopeRoot;
-use super::compiler::NamespaceScope;
-use super::compiler::ScopeChain;
use super::index::FeatureValue;
use super::index::LocalFeatureKey;
use super::index::StyleAtomID;
-use super::program::CascadeOrigin;
-use super::program::CustomDeclaration;
-use super::program::DeclarationBlockID;
+use super::pipeline::rule_store::CascadeOrigin;
+use super::pipeline::rule_store::CustomDeclaration;
+use super::pipeline::rule_store::DeclarationBlockID;
use super::StyleEngine;
-use super::program::RuleID;
-use super::program::SheetID;
-use super::transaction::ElementDeclarationKind;
-use super::transaction::InputKey;
-use super::transaction::InputValue;
-use super::transaction::StateFact;
-use super::transaction::TreeRelations;
+use super::input_types::ElementDeclarationKind;
+use super::input_types::InputKey;
+use super::input_types::InputValue;
+use super::input_types::StateFact;
+use super::input_types::TreeRelations;
+use super::pipeline::rule_store::RuleID;
+use super::pipeline::rule_store::SheetID;
use super::tree::StyleNodeID;
use super::tree::TreeScopeID;
+mod animations;
+mod container_effects;
+mod native_rules;
+mod records;
+pub(crate) use animations::*;
+pub(crate) use container_effects::*;
+#[cfg(test)]
+pub(crate) use native_rules::*;
+pub(crate) use records::*;
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
pub enum FfiStyleInvalidationField {
@@ -75,7 +80,6 @@ pub enum FfiStyleInvalidationField {
RepaintTextDecorations = 1 << 18,
NonInheritedInheritanceSource = 1 << 19,
AnyComputedValueChanged = 1 << 20,
- CacheHit = 1 << 21,
AffectsHitTesting = 1 << 22,
/// The word holds the damage the engine computed with its answer.
EngineComputed = 1 << 23,
@@ -86,60 +90,31 @@ pub enum FfiStyleInvalidationField {
WhiteSpaceCollapseChanged = 1 << 25,
}
+/// The `InvalidationLevel` of a style move at which its box is painted again, the one at which it lays out again, and
+/// the one at which the layout tree is built again.
+pub(crate) const REPAINT_LEVEL: u32 = 1;
+pub(crate) const RELAYOUT_LEVEL: u32 = 2;
+pub(crate) const REBUILD_LEVEL: u32 = 3;
+
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(C)]
pub struct FfiAnimationInvalidation {
pub invalidation: u32,
- pub changed_non_inherited_style_groups: u32,
pub requires_base_style_recomputation: bool,
pub requires_layout_node_style_application: bool,
pub requires_style_resource_update: bool,
}
-/// How a row stands.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum FfiStyleDeltaGap {
- None = 0,
- /// The engine did not settle the row: the host answers it from the element's record demand.
- Materialize = 1,
- /// The engine computed the new record itself from the moved cascade winners; C++ applies it
- /// without running a style computation.
- Computed = 2,
- /// The element needs no style: the host holds none for it in a display:none subtree, and
- /// neither it nor any element inheriting from it reads style while hidden. A read or the
- /// subtree's reveal asks for its record.
- Hidden = 4,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u16)]
-pub enum FfiStyleDeltaDamage {
- None,
- Full,
-}
-
-/// One final style assignment or a typed request to materialize it in C++.
-///
-/// A zero match-answer identity means the complete answer is node-contextual and cannot be shared
-/// across elements. It remains in transaction scratch under the style-node identity.
+/// One final style assignment.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct FfiStyleDelta {
pub style_node: u32,
- pub match_answer: u32,
pub old_style_record: u64,
pub new_style_record: u64,
- pub damage: FfiStyleDeltaDamage,
pub reaction: u8,
pub inherited_style_groups: u8,
pub pseudo_kind: u8,
- pub gap: FfiStyleDeltaGap,
- /// Substitution usage for an engine-computed element, including its pseudo-elements.
- pub uses_substitution: bool,
- /// What an engine-computed element's records read beyond their cascade, as
- /// `FfiNodeRecordReads` bits, for the host to note as its own computation notes them.
- pub record_reads: u8,
/// The non-inherited style groups an engine-computed element read straight from its parent
/// through an explicit `inherit`, which the host marks the parent with; all of them when
/// `u32::MAX`.
@@ -162,101 +137,38 @@ pub struct FfiStyleDelta {
pub composed_by_the_host: bool,
}
-impl FfiStyleDelta {
- /// A row the engine leaves for the host to answer from the element's record demand.
- pub(super) fn unsettled(element: StyleNodeID, reaction: u8) -> Self {
- Self {
- style_node: element.raw(),
- match_answer: 0,
- old_style_record: 0,
- new_style_record: 0,
- damage: FfiStyleDeltaDamage::None,
- reaction,
- inherited_style_groups: 0,
- pseudo_kind: u8::MAX,
- gap: FfiStyleDeltaGap::Materialize,
- uses_substitution: false,
- record_reads: 0,
- explicitly_inherited_groups: 0,
- record_damage: 0,
- owes_an_animation_plan: false,
- owes_a_transition_step: false,
- composed_by_the_host: false,
- }
- }
-}
+impl FfiStyleDelta {}
-/// An engine record a demand settled and the metadata needed to install it.
-#[derive(Clone, Copy, Debug, Default)]
+/// An engine record a demand settled.
+#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct FfiEngineComputedRecord {
pub style_record: u64,
- pub uses_substitution: bool,
- /// As [`FfiStyleDelta::record_reads`].
- pub record_reads: u8,
- /// As [`FfiStyleDelta::explicitly_inherited_groups`].
- pub explicitly_inherited_groups: u32,
- /// As [`FfiStyleDelta::owes_an_animation_plan`].
- pub owes_an_animation_plan: bool,
- /// As [`FfiStyleDelta::owes_a_transition_step`].
- pub owes_a_transition_step: bool,
- /// As [`FfiStyleDelta::composed_by_the_host`].
- pub composed_by_the_host: bool,
- /// The synthetic pseudo-element kinds whose records the engine settled beside the
- /// element's, as a bit per kind; a present slot holding zero is a removal.
- pub pseudo_records_present: u16,
- pub pseudo_records: [u64; PSEUDO_RECORD_SLOTS],
+ /// The record the host holds for `style_record`, which the engine holds until the element's
+ /// styles are next read or settled, or null where the demand answered none.
+ pub host_record: *const c_void,
}
-/// The synthetic pseudo-element records the engine settled beside an element's installed record.
-#[derive(Clone, Copy, Debug, Default)]
-#[repr(C)]
-pub struct FfiSettledPseudoRecords {
- /// The engine settled none: one of the pseudo-elements reads a value it cannot compute, or one
- /// of their rules a container condition it cannot decide. They keep the records they hold, and
- /// nothing else here is set.
- pub refused: bool,
- /// Whether a settled pseudo-element substituted custom properties.
- pub uses_substitution: bool,
- /// As [`FfiStyleDelta::record_reads`].
- pub record_reads: u8,
- /// As [`FfiStyleDelta::explicitly_inherited_groups`].
- pub explicitly_inherited_groups: u32,
- /// The kinds whose records the engine settled, as a bit per kind; a present slot holding zero
- /// is a removal, and an absent kind keeps its record.
- pub pseudo_records_present: u16,
- pub pseudo_records: [u64; PSEUDO_RECORD_SLOTS],
+impl Default for FfiEngineComputedRecord {
+ fn default() -> Self {
+ Self {
+ style_record: 0,
+ host_record: std::ptr::null(),
+ }
+ }
}
/// One record slot per synthetic pseudo-element kind in an engine record answer.
pub const PSEUDO_RECORD_SLOTS: usize = 11;
#[derive(Default)]
-pub(crate) struct FfiStyleTransactionOutput {
+pub(crate) struct FfiStyleUpdateOutput {
scoped: bool,
- connected_element_count: u32,
- only_derived_child_reactions: bool,
transaction_version: u64,
- program_version: u64,
answers: Vec<FfiStyleDelta>,
reclaimed_style_atoms: Vec<super::atoms::ReclaimedStyleAtom>,
}
-#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct FfiStyleTransactionView {
- pub transaction_version: u64,
- pub program_version: u64,
- pub answers: *const FfiStyleDelta,
- pub count: usize,
- pub scoped: bool,
- /// The transaction planned nothing but the child reactions the engine derived from the
- /// reactions C++ applied last: one more generation of the same style change, not a new one.
- pub only_derived_child_reactions: bool,
- /// The elements connected to the document as the transaction was taken.
- pub connected_element_count: u32,
-}
-
/// A host-owned object the engine names but never follows.
///
/// The engine holds it as an integer rather than a raw pointer, because the read side an
@@ -293,7 +205,7 @@ impl FfiHostHandle {
}
}
-/// Document-wide scalar computation inputs captured at a style transaction boundary.
+/// Document-wide scalar computation inputs captured at a style update boundary.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FfiDocumentStyleComputationInputs {
@@ -337,6 +249,8 @@ pub struct FfiDocumentStyleComputationInputs {
pub document_base_url_length: usize,
pub style_sheet_resource_contexts: FfiHostHandle,
pub style_sheet_resource_context_count: usize,
+ /// Which collection of the contexts the host lends, which the engine need not read where it holds that one.
+ pub style_sheet_resource_contexts_version: u64,
/// What `media()` conditions in `if()` read, lent for the boundary call only as the style
/// update's media environment holds them: an `FfiMediaFeatureValue` for each media feature,
/// and the `FfiLengthResolutionContext` lengths in a media query resolve against. The engine
@@ -426,6 +340,7 @@ impl Default for FfiDocumentStyleComputationInputs {
document_base_url_length: 0,
style_sheet_resource_contexts: FfiHostHandle { address: 0 },
style_sheet_resource_context_count: 0,
+ style_sheet_resource_contexts_version: 0,
media_feature_values: FfiHostHandle { address: 0 },
media_feature_value_count: 0,
media_length_resolution_context: FfiHostHandle { address: 0 },
@@ -525,20 +440,6 @@ pub struct FfiResolvedFont {
pub font_size_adjust_from_font: f64,
}
-impl Default for FfiStyleTransactionView {
- fn default() -> Self {
- Self {
- transaction_version: 0,
- program_version: 0,
- answers: std::ptr::null(),
- count: 0,
- scoped: false,
- only_derived_child_reactions: false,
- connected_element_count: 0,
- }
- }
-}
-
/// One final base-style assignment. Zero names the absent side of an insertion or removal.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(C)]
@@ -551,54 +452,85 @@ pub struct FfiStyleRecordDelta {
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct FfiStyleRecordView {
- pub payloads: *const *const c_void,
- pub base_payloads: *const *const c_void,
- /// The base record's borrowed table, matching `WithAnimationsApplied::No`.
- pub longhand_table: *const c_void,
+ /// The record's groups, a `StyleGroups`, composed with its animation overlay where it carries
+ /// one, which the host reads through `CSS::style_record_group`.
+ pub groups: *const c_void,
+ /// The style record that makes a table for each reader asking for one, which holds the
+ /// payloads beneath the animation overlay where the view carries one.
+ pub longhand_table_record: *const c_void,
+ /// The record's animation overlay, which only the record of an element animating carries.
pub animated_overlay: *const c_void,
- pub payload_count: usize,
- pub pseudo_element_styles: u64,
- pub counter_style_environment_identity: u64,
- pub animation_overlay_identity: u64,
pub dependency_flags: u8,
pub present: bool,
}
+// NB: Every element and pseudo-element the host styles holds one of these.
+const _: () = assert!(size_of::<FfiStyleRecordView>() == 32);
+
impl FfiStyleRecordView {
- /// The record's table, the base record's where it carries an overlay.
+ /// The view of `record`, a record the host holds: an installed record, or the sample of the
+ /// animations over one, whose view reads the longhands of the base.
+ pub(super) fn of_record(record: &super::pipeline::Record) -> Self {
+ match record.sample_of_animations() {
+ Some(sample) => Self {
+ groups: std::ptr::from_ref(&record.payloads).cast(),
+ longhand_table_record: std::sync::Arc::as_ptr(&sample.base).cast(),
+ animated_overlay: std::sync::Arc::as_ptr(&sample.animated_overlay).cast(),
+ dependency_flags: sample.dependency_flags,
+ present: true,
+ },
+ None => Self {
+ groups: std::ptr::from_ref(&record.payloads).cast(),
+ longhand_table_record: std::ptr::from_ref(record).cast(),
+ animated_overlay: std::ptr::null(),
+ dependency_flags: record.view_dependency_flags(),
+ present: true,
+ },
+ }
+ }
+
+ /// The longhands of the record, the base record's where it carries an overlay, which reading
+ /// does not make a style record's table for.
///
/// # Safety
///
- /// The view must name a record of an element, which carries a table, that stays live for as long as the borrow.
- pub(crate) unsafe fn longhand_table(&self) -> &ComputedLonghandTable {
+ /// The view must name a record that stays live for as long as the borrow.
+ pub(crate) unsafe fn longhands(&self) -> Option<super::ViewLonghands<'_>> {
// SAFETY: Guaranteed by the caller.
- unsafe { &*self.longhand_table.cast::<ComputedLonghandTable>() }
+ unsafe { self.longhand_table_record.cast::<super::pipeline::Record>().as_ref() }
+ .map(super::ViewLonghands::of_record)
}
/// The record's animation overlay, if it carries one.
///
/// # Safety
///
- /// As for [`Self::longhand_table`].
+ /// As for [`Self::longhands`].
pub(crate) unsafe fn animated_overlay(&self) -> Option<&AnimatedOverlay> {
// SAFETY: Guaranteed by the caller.
unsafe { self.animated_overlay.cast::<AnimatedOverlay>().as_ref() }
}
- pub(crate) fn missing() -> Self {
- Self {
- payloads: std::ptr::null(),
- base_payloads: std::ptr::null(),
- longhand_table: std::ptr::null(),
- animated_overlay: std::ptr::null(),
- payload_count: 0,
- pseudo_element_styles: 0,
- counter_style_environment_identity: 0,
- animation_overlay_identity: 0,
- dependency_flags: 0,
- present: false,
+ /// The group payloads beneath the record's animation overlay, which are its own payloads where
+ /// it carries none, or null where the view is missing.
+ ///
+ /// # Safety
+ ///
+ /// As for [`Self::longhands`].
+ pub(crate) unsafe fn base_groups(&self) -> Option<&crate::css::computed_values::StyleGroups> {
+ // SAFETY: Guaranteed by the caller.
+ match unsafe { self.longhand_table_record.cast::<super::pipeline::Record>().as_ref() } {
+ Some(record) => Some(&record.payloads),
+ // SAFETY: Guaranteed by the caller.
+ None => unsafe { self.groups().as_ref() },
}
}
+
+ /// The record's groups, composed with its animation overlay where it carries one, or null
+ /// where the view is missing.
+ pub(crate) fn groups(&self) -> *const crate::css::computed_values::StyleGroups {
+ self.groups.cast()
+ }
}
/// The tree relations of one style node on one side of a mutation. Zero means "no such relation".
@@ -636,19 +568,31 @@ pub struct FfiTreeDelta {
pub new_relations: FfiTreeRelations,
}
-/// Selector-visible facts which exist when one style node first joins the tree. Variable-width
-/// custom states occupy one shared atom column and are named by this row's offset and count.
+/// Selector-visible facts which exist when one style node first joins the tree, all of which its
+/// projection row takes in one write. The variable-width lists occupy one shared atom column, from
+/// this row's offset on: its custom states, then its classes, then its attributes as name and value
+/// atom pairs.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct FfiElementArrival {
+ /// The element's states, a bit per `FfiStateFact`.
+ pub states: u64,
pub node: u32,
+ pub tag_atom: u32,
+ /// The ASCII-lowercase folding of the tag, or the tag itself where folding leaves it as it is.
+ pub folded_tag_atom: u32,
+ /// The element's ID, or zero for none.
+ pub id_atom: u32,
pub namespace_atom: u32,
pub language_atom: u32,
pub directionality_atom: u32,
- pub custom_state_offset: u32,
pub custom_state_count: u32,
+ pub class_count: u32,
+ pub attribute_count: u32,
pub heading_level: u8,
pub is_slot: bool,
+ /// Whether a text child keeps the element from being `:empty`.
+ pub has_text_content: bool,
/// One plus the element-backed pseudo-element kind the element stands for in its host's
/// shadow tree, or zero.
pub associated_pseudo_kind_plus_one: u8,
@@ -661,29 +605,36 @@ pub struct FfiElementArrival {
pub construction_facts: u32,
}
-/// The last pseudo-element kind C++ materializes as a synthetic pseudo-element; the kinds up to
-/// it are the bits a style record's pseudo-element mask carries. Mirrors the C++
-/// `last_synthetic_pseudo_element`.
-pub const LAST_SYNTHETIC_PSEUDO_ELEMENT_KIND: u16 = 10;
+/// The facts of `arrival` its row takes, with its run `atoms` of the shared atom column: its custom states, then its
+/// classes, then its attributes as name and value pairs.
+pub(in crate::css::style) fn element_arrival_facts<'a>(
+ arrival: &FfiElementArrival,
+ atoms: &'a [u32],
+) -> super::projection_writes::ElementArrivalFacts<'a> {
+ super::projection_writes::ElementArrivalFacts {
+ tag: StyleAtomID(arrival.tag_atom),
+ folded_tag: StyleAtomID(arrival.folded_tag_atom),
+ namespace: StyleAtomID(arrival.namespace_atom),
+ id: StyleAtomID(arrival.id_atom),
+ language: StyleAtomID(arrival.language_atom),
+ directionality: StyleAtomID(arrival.directionality_atom),
+ heading_level: arrival.heading_level,
+ backing_pseudo_kind_plus_one: arrival.associated_pseudo_kind_plus_one,
+ is_slot: arrival.is_slot,
+ has_text_content: arrival.has_text_content,
+ states: super::index::StateSet(arrival.states),
+ adjustment_facts: arrival.adjustment_facts,
+ construction_facts: arrival.construction_facts,
+ box_kind: ElementBoxKind::from_raw(arrival.box_kind),
+ atoms,
+ custom_state_count: arrival.custom_state_count as usize,
+ class_count: arrival.class_count as usize,
+ }
+}
+
pub const FIRST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND: u8 = 11;
pub const LAST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND: u8 = 16;
-/// What C++ reports about a style reaction it applied, for the engine to derive the reactions of
-/// the element's children. Mirrors C++ `StyleReactionAppliedFact`.
-pub mod style_reaction_applied_fact {
- pub const DID_CHANGE_CUSTOM_PROPERTIES: u32 = 1 << 0;
- pub const INVALIDATION_IS_NONE: u32 = 1 << 1;
- pub const NEEDS_LAYOUT_TREE_REBUILD: u32 = 1 << 2;
- pub const RECOMPUTE_DESCENDANT_STYLES: u32 = 1 << 3;
- pub const CHILDREN_EXPLICITLY_INHERIT: u32 = 1 << 4;
- pub const SHADOW_CHILDREN_EXPLICITLY_INHERIT: u32 = 1 << 5;
- pub const WAS_UNSTYLED: u32 = 1 << 6;
- pub const WAS_DISPLAY_NONE: u32 = 1 << 7;
- /// The applied reaction moved the element's computed display, which its children's box-type
- /// transformation reads.
- pub const DISPLAY_CHANGED: u32 = 1 << 11;
-}
-
/// The element facts the style computation's box-type transformation and element style
/// adjustments read. Mirrors C++ `ElementStyleAdjustmentFact`.
pub mod element_adjustment_fact {
@@ -708,8 +659,7 @@ pub mod element_adjustment_fact {
/// An SVG graphics element folds its own transform into its SVG container's layout, which the
/// damage of the element's record moves reads.
pub const IS_SVG_GRAPHICS_ELEMENT: u32 = 1 << 18;
- /// The element stands for an element-reference pseudo-element of its shadow host, whose
- /// style C++ computes and installs on it.
+ /// The element stands for an element-reference pseudo-element of its shadow host.
pub const IS_SHADOW_HOST_PSEUDO_ELEMENT: u32 = 1 << 19;
/// An HTML `<body>`. The first one among an HTML `<html>` root's children propagates its style
/// to the viewport, which layout and the damage of the element's record moves read.
@@ -732,20 +682,102 @@ pub mod element_adjustment_fact {
pub const IS_HTML_HTML_ELEMENT: u32 = 1 << 30;
/// An HTML `<frameset>`, which is the document's body in place of a `<body>`.
pub const IS_HTML_FRAMESET_ELEMENT: u32 = 1 << 31;
- /// The facts only the layout tree build reads. No style depends on them, so a style record
- /// computed for one element is as good for another that differs only in these.
- pub const LAYOUT_TREE_FACTS: u32 = IS_SVG_ELEMENT
- | IS_SVG_SWITCH_ELEMENT
- | IS_SVG_CONTAINER
- | REQUIRES_SVG_CONTAINER
- | IS_SVG_FOREIGN_OBJECT_ELEMENT
- | IS_SVG_MASK_ELEMENT
- | IS_SVG_CLIP_PATH_ELEMENT
- | IS_SVG_PATTERN_ELEMENT
- | RENDERED_IN_TOP_LAYER
- | IS_HTML_FRAMESET_ELEMENT;
- /// The facts only the damage of a record move reads. No style depends on them either.
- pub const RECORD_DAMAGE_FACTS: u32 = IS_SVG_GRAPHICS_ELEMENT | IS_HTML_BODY_ELEMENT | IS_HTML_HTML_ELEMENT;
+}
+
+/// A set of the main-side effects of installing one element's style record, as the host's
+/// `CSS::MainEffects` names them.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[repr(transparent)]
+pub struct MainEffects(u32);
+
+impl MainEffects {
+ pub(crate) const NONE: Self = Self(0);
+ /// The element's animations compose over the record.
+ pub(crate) const ANIMATED: Self = Self(1 << 0);
+ /// The element enters or leaves display:none.
+ pub(crate) const DISPLAY_NONE_FLIP: Self = Self(1 << 1);
+ /// The host clears the styles of the element's descendants, as the element enters display:none, or stays
+ /// display:none while what they inherit moves. The render side decided it, and notes the descendants cleared as
+ /// the host takes the installation.
+ pub(crate) const CLEAR_HIDDEN_DESCENDANTS: Self = Self(1 << 2);
+ /// The element's visibility changes.
+ pub(crate) const VISIBILITY_FLIP: Self = Self(1 << 3);
+ /// The element's custom-property environment moves.
+ pub(crate) const CUSTOM_PROPERTIES: Self = Self(1 << 4);
+ /// The element registers or unregisters anchor names.
+ pub(crate) const ANCHOR_NAMES: Self = Self(1 << 5);
+ /// The root element's font metrics may move.
+ pub(crate) const ROOT_FONT_METRICS: Self = Self(1 << 6);
+ /// Children waiting for the element to leave display:none may be revealed.
+ pub(crate) const REVEAL_WAITING: Self = Self(1 << 7);
+ /// The resources an SVG graphics element references.
+ pub(crate) const SVG_REFERENCES: Self = Self(1 << 8);
+ /// The timelines the element declares by name change.
+ pub(crate) const TIMELINES: Self = Self(1 << 9);
+ /// A form control restyles its shadow tree.
+ pub(crate) const FORM_CONTROL: Self = Self(1 << 10);
+ /// Scroll containers re-snap, or the element's box registers as a scroll snap container or area.
+ pub(crate) const SCROLL_SNAP: Self = Self(1 << 11);
+ /// The layout tree is built again from the root the effects name.
+ pub(crate) const REBUILD: Self = Self(1 << 12);
+ /// The container queries the record read note their containers and the element's dependencies.
+ pub(crate) const CONTAINER_EFFECTS: Self = Self(1 << 13);
+ /// The boxes of the element or its pseudo-elements load or let go of images.
+ pub(crate) const IMAGES: Self = Self(1 << 14);
+ /// The element's highlight pseudo-element styles are pushed to paint.
+ pub(crate) const HIGHLIGHTS: Self = Self(1 << 15);
+ /// The element's box is not a plain one: it takes facts from its element as the host styles it.
+ pub(crate) const HOST_BOX_FACTS: Self = Self(1 << 16);
+ /// The element owes the plan of its animations, which the host applies before it composes them.
+ pub(crate) const ANIMATION_PLAN: Self = Self(1 << 17);
+ /// The element owes the transition step, which the host runs against the record it moves from once it applied the
+ /// plan.
+ pub(crate) const TRANSITION_STEP: Self = Self(1 << 18);
+
+ pub(crate) fn with(self, other: Self, condition: bool) -> Self {
+ if condition { self | other } else { self }
+ }
+
+ /// These effects, but none of `other`.
+ pub(crate) fn without(self, other: Self) -> Self {
+ Self(self.0 & !other.0)
+ }
+
+ /// Whether any of the effects of `other` is one of these.
+ pub(crate) fn intersects(self, other: Self) -> bool {
+ self.0 & other.0 != 0
+ }
+}
+
+/// Where a layout tree rebuild starts, as the host's `CSS::LayoutTreeRebuildRoot` names it, ordered by how much of the
+/// tree it rebuilds.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
+#[repr(transparent)]
+pub struct LayoutTreeRebuildRoot(u8);
+
+impl LayoutTreeRebuildRoot {
+ /// Recreate ::before and ::after while retaining the principal box where its structure permits it.
+ pub(crate) const PSEUDO_ELEMENTS: Self = Self(0);
+ pub(crate) const SELF: Self = Self(1);
+ pub(crate) const SELF_UNLESS_DOCUMENT_ELEMENT_OR_BODY: Self = Self(2);
+ pub(crate) const PARENT: Self = Self(4);
+
+ pub(crate) const fn from_raw(raw: u8) -> Self {
+ Self(raw)
+ }
+}
+
+impl std::ops::BitOr for MainEffects {
+ type Output = Self;
+ fn bitor(self, other: Self) -> Self {
+ Self(self.0 | other.0)
+ }
+}
+
+impl std::ops::BitOrAssign for MainEffects {
+ fn bitor_assign(&mut self, other: Self) {
+ self.0 |= other.0;
+ }
}
/// What a layout row records about the element it is built for at the moment it is allocated, so
@@ -763,6 +795,7 @@ pub mod element_construction_fact {
pub const IS_DOCUMENT_ELEMENT: u32 = 1 << 6;
pub const IS_SVG_RESOURCE_ELEMENT: u32 = 1 << 7;
pub const IS_SVG_GEOMETRY_ELEMENT: u32 = 1 << 8;
+ pub const IS_HTML_SELECT_ELEMENT: u32 = 1 << 9;
/// The layout algorithm a MathML element's tag name selects, as a `MathLayoutKind` in these bits.
pub const MATHML_LAYOUT_KIND_SHIFT: u32 = 16;
pub const MATHML_LAYOUT_KIND_MASK: u32 = 0x1f << MATHML_LAYOUT_KIND_SHIFT;
@@ -911,8 +944,8 @@ pub enum FfiFeatureValueKind {
Atom = 2,
/// Present, with a value that differs from the one the fact held before. Attribute values do
/// not cross as text - an exact test reads the live DOM - but a change to one is still a
- /// change, and a delta that reported presence on both sides would cancel in the journal and
- /// invalidate nothing.
+ /// change, and a delta that reported presence on both sides would write the fact the
+ /// projection already holds and invalidate nothing.
ChangedValue = 3,
}
@@ -924,8 +957,6 @@ pub struct FfiLocalFeatureDelta {
pub feature_kind: FfiFeatureKind,
/// The class atom or attribute-name atom the key is about. Unused for tag names and IDs.
pub name_atom: u32,
- pub old_kind: FfiFeatureValueKind,
- pub old_atom: u32,
pub new_kind: FfiFeatureValueKind,
pub new_atom: u32,
}
@@ -963,7 +994,8 @@ pub struct FfiElementDeclarationDelta {
pub new_block: u32,
}
-/// One exact non-selector style reaction for an element.
+/// One exact non-selector style reaction for an element, which a test records directly.
+#[cfg(test)]
#[derive(Clone, Copy)]
#[repr(C)]
pub struct FfiElementStyleInput {
@@ -1013,6 +1045,59 @@ fn decode_feature_value(kind: FfiFeatureValueKind, atom: u32) -> FeatureValue {
}
}
+impl super::projection_writes::ProjectionWrites<'_> {
+ /// Write the tree delta the host published as `delta`.
+ pub(crate) fn record_ffi_tree_delta(&mut self, delta: &FfiTreeDelta) {
+ let Some(node) = StyleNodeID::from_raw(delta.node) else {
+ return;
+ };
+ let old = delta.old_connected.then(|| delta.old_relations.decode());
+ let new = delta.new_connected.then(|| delta.new_relations.decode());
+ self.record_tree_delta(node, old, new);
+ }
+
+ /// Write the arrival the host published as `arrival`, whose custom states, classes and attribute pairs come next
+ /// in `atoms`, the shared atom column.
+ #[cfg(test)]
+ pub(crate) fn record_ffi_element_arrival(&mut self, arrival: &FfiElementArrival, atoms: &mut &[u32]) {
+ let Some(node) = StyleNodeID::from_raw(arrival.node) else {
+ debug_assert!(false, "an element arrival named an invalid style node");
+ return;
+ };
+ let count =
+ arrival.custom_state_count as usize + arrival.class_count as usize + 2 * arrival.attribute_count as usize;
+ let Some((arrival_atoms, rest)) = atoms.split_at_checked(count) else {
+ debug_assert!(false, "an element arrival named atoms outside the shared atom column");
+ return;
+ };
+ *atoms = rest;
+ self.record_element_arrival(node, &element_arrival_facts(arrival, arrival_atoms));
+ }
+
+ /// Write the local fact the host published as `delta`.
+ pub(crate) fn record_ffi_local_feature(&mut self, delta: &FfiLocalFeatureDelta) {
+ let Some(node) = StyleNodeID::from_raw(delta.node) else {
+ return;
+ };
+ let arriving = self.projection.arrival_is_pending(node);
+ self.record_feature(
+ node,
+ decode_feature_key(delta),
+ decode_feature_value(delta.new_kind, delta.new_atom),
+ arriving,
+ );
+ }
+
+ /// Write the state the host published as `delta`.
+ pub(crate) fn record_ffi_state(&mut self, delta: &FfiStateDelta) {
+ let Some(node) = StyleNodeID::from_raw(delta.node) else {
+ return;
+ };
+ let arriving = self.projection.arrival_is_pending(node);
+ self.record_state(node, decode_state_fact(delta.fact), delta.new_value, arriving);
+ }
+}
+
fn decode_element_declaration_kind(kind: FfiElementDeclarationKind) -> ElementDeclarationKind {
match kind {
FfiElementDeclarationKind::InlineStyle => ElementDeclarationKind::InlineStyle,
@@ -1022,8 +1107,9 @@ fn decode_element_declaration_kind(kind: FfiElementDeclarationKind) -> ElementDe
}
impl StyleEngine {
- /// Apply one flat transaction. Tree deltas are staged in arrival order so derived neighbour
- /// rows follow the live tree step by step, while the journal normalizes for discovery.
+ /// Apply one flat transaction as a test's host would publish it at one barrier: its tree deltas in order, then its
+ /// arrivals, local facts and states, then its declarations and style inputs.
+ #[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub fn apply_transaction_batch(
&mut self,
@@ -1034,169 +1120,73 @@ impl StyleEngine {
element_declaration_deltas: &[FfiElementDeclarationDelta],
element_style_inputs: &[FfiElementStyleInput],
) {
- let (element_arrivals, arrival_custom_state_atoms) = arrival_columns;
- let largest_element_index = tree_deltas
- .iter()
- .filter_map(|delta| StyleNodeID::from_raw(delta.node)?.element_index())
- .max()
- .unwrap_or(0);
- let mut arriving_nodes = vec![false; largest_element_index as usize + 1];
- let mut initial_tree_was_bulk_loaded = false;
- if self.can_bulk_load_initial_tree() && !tree_deltas.is_empty() {
- let mut initial_arrivals = Vec::with_capacity(tree_deltas.len());
- let mut initial_document_root = None;
- let mut can_bulk_load_initial_tree = true;
+ let (element_arrivals, mut arrival_atoms) = arrival_columns;
+ self.retained.write_projection_for_test(|writes| {
for delta in tree_deltas {
- let Some(node) = StyleNodeID::from_raw(delta.node) else {
- can_bulk_load_initial_tree = false;
- continue;
- };
- let Some(index) = node.element_index() else {
- can_bulk_load_initial_tree = false;
- continue;
- };
- let is_unique_arrival = !delta.old_connected && delta.new_connected && !arriving_nodes[index as usize];
- can_bulk_load_initial_tree &= is_unique_arrival;
- arriving_nodes[index as usize] = is_unique_arrival;
- if is_unique_arrival {
- let relations = delta.new_relations.decode();
- if relations.parent.is_none() && relations.tree_scope == TreeScopeID::DOCUMENT {
- can_bulk_load_initial_tree &= initial_document_root.replace(node).is_none();
- }
- initial_arrivals.push((node, relations));
- }
+ writes.record_ffi_tree_delta(delta);
}
- if can_bulk_load_initial_tree && let Some(document_root) = initial_document_root {
- self.bulk_load_initial_tree(document_root, &initial_arrivals);
- initial_tree_was_bulk_loaded = true;
+ for arrival in element_arrivals {
+ writes.record_ffi_element_arrival(arrival, &mut arrival_atoms);
}
- }
- if !initial_tree_was_bulk_loaded {
- self.host.initial_tree_batch_applied |= !tree_deltas.is_empty();
- for delta in tree_deltas {
- let Some(node) = StyleNodeID::from_raw(delta.node) else {
- continue;
- };
- let old = delta.old_connected.then(|| delta.old_relations.decode());
- let new = delta.new_connected.then(|| delta.new_relations.decode());
- self.record_tree_delta(node, old, new);
+ for delta in local_feature_deltas {
+ writes.record_ffi_local_feature(delta);
}
- for delta in tree_deltas {
- let Some(node) = StyleNodeID::from_raw(delta.node) else {
- continue;
- };
- let Some(index) = node.element_index() else {
- continue;
- };
- arriving_nodes[index as usize] = self.node_arrival_is_pending(node);
+ for delta in state_deltas {
+ writes.record_ffi_state(delta);
}
- }
- let node_is_arriving = |node: StyleNodeID| {
- node.element_index()
- .and_then(|index| arriving_nodes.get(index as usize))
- .copied()
- .unwrap_or(false)
- };
-
- if !element_arrivals.is_empty() {
- for arrival in element_arrivals {
- let Some(node) = StyleNodeID::from_raw(arrival.node) else {
- debug_assert!(false, "an element arrival named an invalid style node");
- continue;
- };
- let Some(custom_state_end) = arrival.custom_state_offset.checked_add(arrival.custom_state_count) else {
- debug_assert!(false, "an element arrival custom-state range overflowed");
- continue;
- };
- let Ok(custom_state_range) = usize::try_from(arrival.custom_state_offset)
- .and_then(|start| usize::try_from(custom_state_end).map(|end| start..end))
- else {
- debug_assert!(false, "an element arrival custom-state range exceeded usize");
- continue;
- };
- let Some(custom_states) = arrival_custom_state_atoms.get(custom_state_range) else {
- debug_assert!(
- false,
- "an element arrival named custom states outside the shared atom column"
- );
- continue;
- };
- let custom_states = custom_states.iter().copied().map(StyleAtomID).collect::<Vec<_>>();
- // The host can submit an element's features a batch after its arrival, where it submitted its input
- // as the element's subtree was being inserted: the arrival is pending still.
- let arriving = node_is_arriving(node) || self.node_arrival_is_pending(node);
- self.record_element_arrival(node, arrival, &custom_states, arriving);
+ });
+ for arrival in element_arrivals {
+ if let Some(node) = StyleNodeID::from_raw(arrival.node)
+ && arrival.associated_pseudo_kind_plus_one != 0
+ {
+ self.retained.note_backing_element(node);
}
- self.settle_batched_inputs();
- }
-
- for delta in local_feature_deltas {
- let Some(node) = StyleNodeID::from_raw(delta.node) else {
- continue;
- };
- self.record_batched_input(
- InputKey::LocalFeature(node, decode_feature_key(delta)),
- InputValue::Feature(decode_feature_value(delta.old_kind, delta.old_atom)),
- InputValue::Feature(decode_feature_value(delta.new_kind, delta.new_atom)),
- node_is_arriving(node),
- );
}
- // NB: Settling discards the answers a style pass the host is installing published for its rows still to come,
- // so a batch that records nothing, such as the states the host publishes as it installs a row whose states
- // stand, settles nothing.
- if !tree_deltas.is_empty() || !local_feature_deltas.is_empty() {
- self.settle_batched_inputs();
+ // As the adoption of a host's publication does, the hover's chain follows the tree where it moved.
+ if !tree_deltas.is_empty() {
+ self.set_hover(self.hover_target());
}
-
- let mut states_moved = false;
- for delta in state_deltas {
- let Some(node) = StyleNodeID::from_raw(delta.node) else {
+ self.record_element_declaration_deltas(element_declaration_deltas);
+ for input in element_style_inputs {
+ let Some(node) = StyleNodeID::from_raw(input.style_node) else {
continue;
};
- states_moved |= self.record_batched_state(
- node,
- decode_state_fact(delta.fact),
- delta.new_value,
- node_is_arriving(node),
+ self.record_input(
+ InputKey::ElementStyleInput(node),
+ InputValue::ElementStyleInput {
+ reaction: 0,
+ inherited_style_groups: 0,
+ },
+ InputValue::ElementStyleInput {
+ reaction: input.reaction,
+ inherited_style_groups: input.inherited_style_groups,
+ },
);
}
- if states_moved {
- self.settle_batched_inputs();
- }
+ }
+ /// Record the declaration blocks the host published elements to hold, or no longer to hold.
+ pub(crate) fn record_element_declaration_deltas(
+ &mut self,
+ element_declaration_deltas: &[FfiElementDeclarationDelta],
+ ) {
for delta in element_declaration_deltas {
let Some(node) = StyleNodeID::from_raw(delta.node) else {
continue;
};
// Zero means the node has no declaration block of that kind on that side.
- let block = |raw: u32| (raw != 0).then_some(DeclarationBlockID(raw));
+ let block = |raw: u32| (raw != 0).then(|| DeclarationBlockID::new(raw));
// The block's contents moved even where the host's object for it did not, so what makes
// this a change is a fresh version of the block, which is minted here rather than by the
// host: the host says only that the node has one.
let new_block =
- (delta.new_block != 0).then(|| DeclarationBlockID(self.retained.next_declaration_block_version()));
+ (delta.new_block != 0).then(|| DeclarationBlockID::new(self.retained.next_declaration_block_version()));
self.record_input(
InputKey::ElementDeclaration(node, decode_element_declaration_kind(delta.kind)),
InputValue::ElementDeclaration(block(delta.old_block)),
InputValue::ElementDeclaration(new_block),
);
}
- for input in element_style_inputs {
- let Some(node) = StyleNodeID::from_raw(input.style_node) else {
- continue;
- };
- self.record_input(
- InputKey::ElementStyleInput(node),
- InputValue::ElementStyleInput {
- reaction: 0,
- inherited_style_groups: 0,
- },
- InputValue::ElementStyleInput {
- reaction: input.reaction,
- inherited_style_groups: input.inherited_style_groups,
- },
- );
- }
}
}
@@ -1219,16 +1209,21 @@ pub struct FfiAppliedAnimationDefinition {
pub range_end_calculated: *const c_void,
}
-/// What an applied animation definition holds by value.
+/// What an applied animation definition holds by value, its numbers before its bytes, which pack
+/// behind them.
#[repr(C)]
#[derive(Clone, Copy, PartialEq)]
pub struct FfiAppliedAnimationValues {
- pub duration_is_auto: bool,
pub duration: f64,
pub iteration_count: f64,
+ pub delay: f64,
+ pub range_start_px: f64,
+ pub range_start_percentage: f64,
+ pub range_end_px: f64,
+ pub range_end_percentage: f64,
+ pub duration_is_auto: bool,
pub direction: u8,
pub play_state: u8,
- pub delay: f64,
pub fill_mode: u8,
pub composition: u8,
/// An `FfiAnimationTimelineKind`.
@@ -1236,13 +1231,11 @@ pub struct FfiAppliedAnimationValues {
pub scroll_scroller: u8,
pub scroll_axis: u8,
pub range_start_name: u8,
- pub range_start_px: f64,
- pub range_start_percentage: f64,
pub range_end_name: u8,
- pub range_end_px: f64,
- pub range_end_percentage: f64,
}
+const _: () = assert!(size_of::<FfiAppliedAnimationValues>() == 72);
+
// SAFETY: the keyframe set is only compared by address, and the timing function is immutable style
// value data the animation retains for as long as the definition is published, read only to
// compare it.
@@ -1260,7 +1253,6 @@ unsafe impl Sync for FfiAppliedAnimationDefinition {}
pub extern "C" fn style_engine_set_tree_scope_animation_keyframes(
host: &DocumentHost,
tree_scope: u32,
- shadow_root_identity: usize,
name_lengths: ak::Span<'_, u32>,
name_units: ak::Span<'_, u16>,
keyframe_sets: ak::Span<'_, usize>,
@@ -1277,7 +1269,6 @@ pub extern "C" fn style_engine_set_tree_scope_animation_keyframes(
);
let write = super::engine_calls::EngineWrite::AnimationKeyframes {
tree_scope: TreeScopeID(tree_scope),
- shadow_root_identity,
row,
};
super::engine_calls::queue(host, write);
@@ -1288,7 +1279,7 @@ pub extern "C" fn style_engine_set_tree_scope_animation_keyframes(
/// row up.
///
/// # Safety
-/// Each declaration pointer must be a live `Arc<DeclarationBlockData>` the call borrows.
+/// Each declaration pointer must be a live `SharedDeclarationBlock` the call borrows.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn style_engine_set_tree_scope_position_try_rules(
host: &DocumentHost,
@@ -1332,15 +1323,14 @@ pub unsafe extern "C" fn style_engine_note_custom_property_environment(
inheritable: u64,
inheritable_store: *const c_void,
) {
- use super::custom_property_environments::RetainedCustomPropertyStore;
- // SAFETY: Guaranteed by the caller.
- let retain =
- |store: *const c_void| (!store.is_null()).then(|| unsafe { RetainedCustomPropertyStore::from_borrowed(store) });
+ use super::custom_property_environments::retained_store;
let write = super::engine_calls::EngineWrite::NoteCustomPropertyEnvironment {
identity,
- store: retain(store),
+ // SAFETY: Guaranteed by the caller.
+ store: unsafe { retained_store(store) },
inheritable,
- inheritable_store: retain(inheritable_store),
+ // SAFETY: Guaranteed by the caller.
+ inheritable_store: unsafe { retained_store(inheritable_store) },
};
super::engine_calls::queue(host, write);
}
@@ -1372,244 +1362,14 @@ pub extern "C" fn style_engine_inheritable_custom_property_environment(
})
}
-/// How one animation effect's description travels across the boundary: the ranges of the flat
-/// buffers that belong to it.
-#[repr(C)]
-pub struct FfiPublishedAnimationEffect {
- pub identity: u64,
- pub generation: u64,
- /// The effect belongs to a CSS transition, which the interpolation treats differently.
- pub is_transition: bool,
- /// The effect's keyframes come from a style sheet, which their URLs resolve against: its base
- /// URL is the range of the base URL buffer below.
- pub has_resource_context: bool,
- pub resource_context_is_origin_clean: bool,
- pub first_keyframe: u32,
- pub keyframe_count: u32,
- pub base_url_offset: u32,
- pub base_url_length: u32,
- /// A transition's reversing-adjusted start value, or null for any other effect.
- pub reversing_adjusted_start_value: *const c_void,
- /// A transition's reversing shortening factor.
- pub reversing_shortening_factor: f64,
-}
-
-/// The easing function a published keyframe spells out.
-#[repr(u8)]
-#[derive(Clone, Copy)]
-#[expect(dead_code, reason = "C++ constructs the variants")]
-pub enum FfiPublishedEasingKind {
- Linear,
- CubicBezier,
- Steps,
-}
-
-/// One keyframe of a published effect: its offset on the scale the host keys keyframes by, its
-/// easing spelled out, its composite operation and the ranges of what it declares.
-#[repr(C)]
-pub struct FfiPublishedAnimationKeyframe {
- pub key: i64,
- pub easing_kind: FfiPublishedEasingKind,
- pub step_position: u8,
- pub interval_count: i32,
- pub x1: f64,
- pub y1: f64,
- pub x2: f64,
- pub y2: f64,
- pub first_linear_point: u32,
- pub linear_point_count: u32,
- /// The keyframe's own easing where it still has to be substituted against the element being
- /// sampled, or null.
- pub easing_value: *const c_void,
- /// The keyframe's composite operation, with `auto` already the effect's own.
- pub composite: crate::css::animation::FfiCompositeOperation,
- pub first_declaration: u32,
- pub declaration_count: u32,
- pub first_custom_declaration: u32,
- pub custom_declaration_count: u32,
-}
-
-/// One control point of a published `linear()` easing.
-#[repr(C)]
-pub struct FfiPublishedLinearEasingPoint {
- pub input: f64,
- pub output: f64,
-}
-
-/// One longhand a published keyframe declares. A null value stands for the element's own value,
-/// which a keyframe the host synthesized holds and which is not known until the element is
-/// sampled.
-#[repr(C)]
-pub struct FfiPublishedAnimationDeclaration {
- pub property_id: u16,
- pub value: *const c_void,
-}
-
-/// One custom property a published keyframe declares, by the raw representation of its name. A
-/// null value stands for the element's own value of it.
-#[repr(C)]
-pub struct FfiPublishedAnimationCustomDeclaration {
- pub name: usize,
- pub value: *const c_void,
-}
-
-/// The version of one animation effect the host is about to sample.
-#[repr(C)]
-pub struct FfiAnimationEffectVersion {
- pub identity: u64,
- pub generation: u64,
-}
-
-/// Describe the effects one of an element's animation lists holds, in composite order, for the
-/// style engine to sample them from. The host retains every value the effects name and streams
-/// the description to the engine.
-///
-/// # Safety
-/// `host` must be a live document host, on its document's thread, every buffer must hold the count
-/// it is given, and every value and custom-property name the buffers name must be live for the
-/// duration of the call.
-#[unsafe(no_mangle)]
-#[allow(clippy::too_many_arguments)]
-pub unsafe extern "C" fn style_engine_set_element_animation_effect_descriptions(
- host: &DocumentHost,
- node: u32,
- slot: u8,
- effects: *const FfiPublishedAnimationEffect,
- effect_count: usize,
- keyframes: *const FfiPublishedAnimationKeyframe,
- keyframe_count: usize,
- declarations: *const FfiPublishedAnimationDeclaration,
- declaration_count: usize,
- custom_declarations: *const FfiPublishedAnimationCustomDeclaration,
- custom_declaration_count: usize,
- linear_points: *const FfiPublishedLinearEasingPoint,
- linear_point_count: usize,
- base_url_bytes: *const u8,
- base_url_byte_count: usize,
-) {
- let Some(node) = StyleNodeID::from_raw(node) else {
- return;
- };
- // SAFETY: Guaranteed by the caller.
- let effects = unsafe {
- super::effect_descriptions::PublishedEffectBuffers {
- effects: ak::slice_from_raw_parts(effects, effect_count),
- keyframes: ak::slice_from_raw_parts(keyframes, keyframe_count),
- declarations: ak::slice_from_raw_parts(declarations, declaration_count),
- custom_declarations: ak::slice_from_raw_parts(custom_declarations, custom_declaration_count),
- linear_points: ak::slice_from_raw_parts(linear_points, linear_point_count),
- base_url_bytes: ak::slice_from_raw_parts(base_url_bytes, base_url_byte_count),
- }
- .effects()
- };
- host.engine_memo().described.borrow_mut().follow(node, slot, &effects);
- host.queue_change(crate::render_state::ArenaChange::Engine(
- super::engine_calls::EngineWrite::AnimationEffectDescriptions { node, slot, effects },
- ));
-}
-
-/// Whether the engine describes one of an element's animation lists as holding exactly these
-/// versions of its effects, in this order, so that the host need not describe them again. Only
-/// the host describes them, so it knows without asking.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_describes_animation_effects(
- host: &DocumentHost,
- node: u32,
- slot: u8,
- versions: ak::Span<'_, FfiAnimationEffectVersion>,
-) -> bool {
- StyleNodeID::from_raw(node).is_some_and(|node| {
- host.engine_memo()
- .described
- .borrow()
- .describe(node, slot, versions.as_slice())
- })
-}
-
-/// Publish already bound immutable selector inputs, after all host interning has finished.
-pub(crate) fn publish_style_rule(
- engine: &mut StyleEngine,
- sheet: u32,
- before_rule: u32,
- compiled: &[&CompiledSelector],
- namespaces: NamespaceScope,
- bound_scope: &BoundScopeChain,
-) -> u32 {
- if sheet == 0 || compiled.is_empty() {
- return 0;
- }
- let scope: Vec<_> = bound_scope.roots.iter().map(|selector| selector.as_ref()).collect();
- let limits: Vec<_> = bound_scope.limits.iter().map(|selector| selector.as_ref()).collect();
- let before = match before_rule {
- 0 => None,
- id => Some(RuleID(id - 1)),
- };
- let scope = ScopeChain {
- roots: &scope,
- limits: &limits,
- levels: &bound_scope.levels,
- implicit_roots: &bound_scope.implicit_roots,
- };
- let rule = engine.add_style_rule_in_scope(SheetID(sheet - 1), before, compiled, namespaces, &scope);
- rule.0 + 1
-}
-
-/// Publishes a style rule of a user-agent sheet with the selector program the process compiled for
-/// it, or answers `None` when the rule is not one or the engine compiles its own.
-pub(crate) fn publish_user_agent_style_rule(
- engine: &mut StyleEngine,
- sheet: u32,
- before_rule: u32,
- rule_identity: u64,
- compiled: &[&CompiledSelector],
- namespaces: Option<&super::rule_writes::NamespaceTexts>,
- bound_scope: &BoundScopeChain,
-) -> Option<u32> {
- if sheet == 0 || !bound_scope.levels.is_empty() {
- return None;
- }
- let sheet = SheetID(sheet - 1);
- if engine.program.sheet_origin(sheet) != crate::css::cascaded_properties::CascadeOrigin::UserAgent
- || !engine.shares_user_agent_selector_programs()
- {
- return None;
- }
- let before = (before_rule != 0).then(|| RuleID(before_rule - 1));
- Some(
- engine
- .add_user_agent_style_rule(sheet, before, rule_identity, compiled, namespaces)
- .0
- + 1,
- )
-}
-
-/// Replace selectors using immutable compilation inputs, preserving rule identity.
-pub(crate) fn publish_style_rule_selectors(
- engine: &mut StyleEngine,
- rule: u32,
- compiled: &[&CompiledSelector],
- namespaces: NamespaceScope,
- bound_scope: &BoundScopeChain,
-) {
- if rule == 0 || compiled.is_empty() {
- return;
- }
- let scope: Vec<_> = bound_scope.roots.iter().map(|selector| selector.as_ref()).collect();
- let limits: Vec<_> = bound_scope.limits.iter().map(|selector| selector.as_ref()).collect();
- let scope = ScopeChain {
- roots: &scope,
- limits: &limits,
- levels: &bound_scope.levels,
- implicit_roots: &bound_scope.implicit_roots,
- };
- engine.replace_style_rule_selectors(RuleID(rule - 1), compiled, namespaces, &scope);
-}
#[derive(Clone, Default)]
pub(crate) struct BoundScopeChain {
- roots: Vec<std::sync::Arc<CompiledSelector>>,
- limits: Vec<std::sync::Arc<CompiledSelector>>,
- levels: Vec<(u32, u32)>,
- implicit_roots: Vec<Option<ImplicitScopeRoot>>,
+ pub(crate) roots: Vec<crate::css::selector::SelectorRef>,
+ pub(crate) limits: Vec<crate::css::selector::SelectorRef>,
+ /// Whether each of `limits` names `&` or `:scope`, anywhere in it.
+ pub(crate) limits_name_the_root: Vec<bool>,
+ pub(crate) levels: Vec<(u32, u32)>,
+ pub(crate) implicit_roots: Vec<Option<ImplicitScopeRoot>>,
}
impl BoundScopeChain {
@@ -1632,119 +1392,25 @@ impl BoundScopeChain {
node => StyleNodeID::from_raw(node).map(ImplicitScopeRoot::Node),
});
if let Some(start) = start {
- self.roots.extend(start.selectors.iter().cloned());
+ self.roots.extend(start.selectors.owned());
}
if let Some(end) = end {
- self.limits.extend(end.selectors.iter().cloned());
- }
- }
-}
-
-/// One concrete match, as the boundary carries it.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(C)]
-pub struct FfiRuleMatch {
- pub node: u32,
- /// The rule identity as the boundary numbers it: one more than the engine's, so that zero can
- /// mean no rule.
- pub rule: u32,
- /// Collision-checked identity of the rule's complete semantic declaration inventory, or zero
- /// when custom properties or another declaration kind remain on the C++ side.
- pub semantic_declaration: u32,
- /// The pseudo-element the match targets, or `u32::MAX` for the originating element itself.
- pub pseudo_element: u32,
- /// The host whose shadow tree this match decides in, or 0 for the document's own context. How
- /// deeply encapsulated a rule is orders it against the contexts around it, and the scope the
- /// match resolved through is not always the one the element is in: `:host`, `::slotted()` and
- /// `::part()` all decide for an element outside their own tree.
- pub scope_host: u32,
- /// Generational hops from the scoping root the match resolved through, or `u32::MAX` for a rule
- /// that is not scoped. A nearer root wins the proximity comparison.
- pub scope_proximity: u32,
-}
-
-unsafe fn write_rule_matches(
- engine: &mut StyleEngine,
- matches: &[RuleMatch],
- out: *mut FfiRuleMatch,
- capacity: usize,
-) -> usize {
- if matches.len() > capacity {
- return matches.len();
- }
- for (index, entry) in matches.iter().enumerate() {
- unsafe {
- *out.add(index) = FfiRuleMatch {
- node: entry.node.raw(),
- rule: entry.rule.0 + 1,
- semantic_declaration: if engine.program.declarations_are_complete_for(entry.rule) {
- engine.program.ensure_semantic_declaration(entry.rule).0
- } else {
- 0
- },
- pseudo_element: entry.pseudo_element.map_or(u32::MAX, |target| u32::from(target.kind.0)),
- scope_host: engine.cascade_context_host(entry.rule, entry.tree_scope),
- scope_proximity: entry.scope_proximity,
- };
+ self.limits.extend(end.selectors.owned());
+ self.limits_name_the_root.extend(end.selectors.owned().map(|limit| {
+ let tree = limit.view().to_tree();
+ crate::css::selector_operations::contains_nesting(&tree)
+ || crate::css::selector_operations::contains_pseudo_class(
+ &tree,
+ crate::css::selector::PseudoClassType::Scope,
+ )
+ }));
}
}
- matches.len()
-}
-
-/// Matches one element and writes its matches, in cascade order, into `out`.
-///
-/// The same answer the document pass gives for that element, asked one element at a time, which is
-/// what a style recompute needs.
-///
-/// Returns the number written, `usize::MAX` when the pass could not complete, or a count larger
-/// than `capacity` when nothing was written because the buffer was too small.
-///
-/// # Safety
-/// `host` must be a live document host, on its document's thread, and `out` must point at
-/// `capacity` writable `FfiRuleMatch` values.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_match_element(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- node: u32,
- out: *mut FfiRuleMatch,
- capacity: usize,
- compact_for_cascade: bool,
-) -> usize {
- // SAFETY: Guaranteed by the caller.
- // SAFETY: Guaranteed by the caller.
- with_engine(read, host, |engine| unsafe {
- match_element(engine, node, out, capacity, compact_for_cascade)
- })
-}
-
-/// [`style_engine_match_element`] on `engine`.
-///
-/// # Safety
-/// As for [`style_engine_match_element`], for the arguments after `engine`.
-pub unsafe fn match_element(
- engine: &mut StyleEngine,
- node: u32,
- out: *mut FfiRuleMatch,
- capacity: usize,
- compact_for_cascade: bool,
-) -> usize {
- let Some(node) = StyleNodeID::from_raw(node) else {
- return usize::MAX;
- };
- let result = match compact_for_cascade {
- true => engine.match_element_for_cascade(node),
- false => engine.match_element(node),
- };
- let Ok(matches) = result else {
- return usize::MAX;
- };
- unsafe { write_rule_matches(engine, &matches, out, capacity) }
}
fn collect_native_custom_declarations(
engine: &mut StyleEngine,
- custom_properties: &[crate::css::declaration_block::CustomProperty],
+ custom_properties: crate::css::declaration_block::CustomProperties<'_>,
) -> Vec<(CustomDeclaration, RetainedStyleValueData)> {
custom_properties
.iter()
@@ -1752,31 +1418,25 @@ fn collect_native_custom_declarations(
let name = property.name.to_fly_string();
let atom = engine.atoms.intern_raw(name.raw());
// SAFETY: The fly string is live for the call, and the engine takes a reference of its own.
- unsafe { engine.note_custom_property_name(atom, name.raw(), property.name.units()) };
+ unsafe { engine.note_custom_property_name(atom, name.raw()) };
let declaration = &property.declaration;
- // Custom properties retain their authored values, without normal-property
- // canonicalization. Their token spelling is observable after substitution.
- let value = engine.intern_specified_value(&declaration.value);
+ // Custom properties retain their authored values. Their token spelling is observable
+ // after substitution.
let written = RetainedStyleValueData::from_arc(declaration.value.clone());
- let declared = CustomDeclaration {
- name: atom,
- important: declaration.important,
- operator: super::program_updates::declaration_operator(&declaration.value),
- value,
- };
+ let declared = CustomDeclaration::new(atom, declaration.important, declaration.operator);
(declared, written)
})
.collect()
}
-pub(super) fn register_element_declared_properties(
+pub(super) fn register_element_declared_properties<'a>(
engine: &mut StyleEngine,
node: StyleNodeID,
kind: FfiElementDeclarationKind,
- declarations: &[crate::css::declaration_block::DeclaredProperty],
- custom_properties: &[crate::css::declaration_block::CustomProperty],
+ declarations: impl ExactSizeIterator<Item = crate::css::declaration_block::DeclarationRef<'a>>,
+ custom_properties: crate::css::declaration_block::CustomProperties<'_>,
) {
- let declarations = engine.intern_element_declared_properties(declarations);
+ let declarations = super::specified_value::element_declared_properties(declarations);
let custom_declarations = collect_native_custom_declarations(engine, custom_properties);
let declaration_kind = decode_element_declaration_kind(kind);
engine.set_element_declared_properties(node, declaration_kind, declarations, custom_declarations);
@@ -1784,10 +1444,12 @@ pub(super) fn register_element_declared_properties(
}
/// Whether `declarations` can define transitions.
-pub(crate) fn declares_transitions(declarations: &[crate::css::declaration_block::DeclaredProperty]) -> bool {
+pub(crate) fn declares_transitions<'a>(
+ declarations: impl IntoIterator<Item = crate::css::declaration_block::DeclarationRef<'a>>,
+) -> bool {
use crate::css::property_metadata::property_defines_a_css_transition;
declarations
- .iter()
+ .into_iter()
.any(|declaration| property_defines_a_css_transition(declaration.property_id))
}
@@ -1804,7 +1466,9 @@ pub extern "C" fn style_engine_set_element_inline_style_properties(
return false;
};
let data = block.map(DeclarationBlock::data);
- let has_transitions = data.as_ref().is_some_and(|data| declares_transitions(&data.properties));
+ let has_transitions = data
+ .as_ref()
+ .is_some_and(|data| declares_transitions(data.properties()));
super::engine_calls::queue(host, super::engine_calls::EngineWrite::InlineStyle { node, data });
has_transitions
}
@@ -1822,7 +1486,7 @@ pub unsafe extern "C" fn style_engine_set_element_presentational_hint_properties
properties: *const c_void,
count: usize,
) -> bool {
- use crate::css::declaration_block::{DeclarationBlockData, FfiDeclaredProperty, declaration_from_view};
+ use crate::css::declaration_block::{FfiDeclaredProperty, declaration_from_view};
let Some(node) = StyleNodeID::from_raw(node) else {
return false;
};
@@ -1834,12 +1498,17 @@ pub unsafe extern "C" fn style_engine_set_element_presentational_hint_properties
};
// A hint may name a shorthand. Expanded as any declaration block is, it declares every longhand it decides, and so
// do all declarations the engine is given.
- let mut hints = DeclarationBlockData::default();
+ let mut hints = crate::css::declaration_block::DeclarationBlockBuilder::default();
for property in properties {
// SAFETY: Guaranteed by the caller.
hints.append_in_specified_order(unsafe { declaration_from_view(property) });
}
- let has_transitions = declares_transitions(&hints.properties);
+ let has_transitions = declares_transitions(
+ hints
+ .properties
+ .iter()
+ .map(crate::css::declaration_block::DeclaredProperty::borrowed),
+ );
super::engine_calls::queue(
host,
super::engine_calls::EngineWrite::PresentationalHints {
@@ -1851,256 +1520,125 @@ pub unsafe extern "C" fn style_engine_set_element_presentational_hint_properties
has_transitions
}
-/// Publishes the immutable inputs of one element's base style and returns its old and new
-/// `StyleRecordID` assignments. An equal pair means the final semantic output did not change.
+/// Installs the record of a style the host made outside the engine, as for a layout node, holding
+/// `payloads`, every computed group, with the inherited bits `inherited_bits` and the effective
+/// zoom's bits `effective_zoom_bits` beside the inherited ones, and answers its identity. Nothing holds the record yet: the
+/// host pins it before the engine sweeps its records again.
///
/// # Safety
-/// `host` must be a live document host, on its document's thread. Every non-empty array must have
-/// its reported number of readable entries. Group payloads and style values must remain live for
-/// this call. `animated_overlay` must be null or point at a live Rust animation overlay.
-/// `longhand_table` must be null for an anonymous layout style or point to a live, frozen
-/// `ComputedLonghandTable`.
+/// `host` must be a live document host, on its document's thread. `payloads` must point at
+/// `count` readable group payloads, which must remain live for this call. `source_record` must
+/// be null for an anonymous layout style or be a style record the caller holds, which the
+/// installed record derives from.
+/// `custom_property_store` must be null or the live store `custom_property_environment` resolves
+/// to.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_publish_computed_groups(
+pub unsafe extern "C" fn style_engine_install_host_style_record(
host: &DocumentHost,
read: &crate::render_state::BegunRead,
- node: u32,
- pseudo_kind: u8,
payloads: *const *const c_void,
count: usize,
- inherited_group_count: usize,
+ inherited_bits: u32,
+ effective_zoom_bits: u32,
+ reset_bits: u32,
custom_property_environment: u64,
- inherited_group_swap_candidate: bool,
counter_style_environment_identity: u64,
- animation_overlay_identity: u64,
- animated_overlay: *const c_void,
- animation_overlay_payloads: *const *const c_void,
- animation_overlay_payload_count: usize,
- longhand_table: *const c_void,
+ source_record: *const c_void,
custom_property_store: *const c_void,
-) -> FfiStyleRecordDelta {
- // SAFETY: Guaranteed by the caller.
- // SAFETY: Guaranteed by the caller.
- with_engine(read, host, |engine| unsafe {
- publish_computed_groups(
- engine,
- node,
- pseudo_kind,
- payloads,
- count,
- inherited_group_count,
- custom_property_environment,
- inherited_group_swap_candidate,
- counter_style_environment_identity,
- animation_overlay_identity,
- animated_overlay,
- animation_overlay_payloads,
- animation_overlay_payload_count,
- longhand_table,
- custom_property_store,
- )
+) -> u64 {
+ assert!(!payloads.is_null() && count == crate::css::table_group_builder::group_index::COUNT);
+ let bits = crate::css::computed_value_types::StyleBits {
+ inherited: crate::css::computed_value_types::InheritedSetValues {
+ bits: crate::css::computed_value_types::InheritedBits(inherited_bits),
+ effective_zoom_bits,
+ },
+ reset: crate::css::computed_value_types::ResetBits(reset_bits),
+ };
+ // SAFETY: Guaranteed by the caller.
+ let payloads =
+ &unsafe { crate::css::computed_values::StyleGroups::retained(ak::slice_from_raw_parts(payloads, count), bits) };
+ // SAFETY: Guaranteed by the caller.
+ let source_record = unsafe { source_record.cast::<super::pipeline::Record>().as_ref() };
+ with_engine(read, host, |engine| {
+ let record = match source_record {
+ Some(source) => engine.install_record_derived(source, payloads, Some(counter_style_environment_identity)),
+ None => engine.install_initial_derived_record(payloads, counter_style_environment_identity),
+ };
+ // The store is what the environment resolves to; an engine-computed environment builds on it.
+ // SAFETY: Guaranteed by the caller.
+ unsafe {
+ engine
+ .custom_property_environments
+ .retain_raw(custom_property_environment, custom_property_store);
+ }
+ record.raw()
})
}
-/// [`style_engine_publish_computed_groups`] on `engine`.
-///
-/// # Safety
-/// As for [`style_engine_publish_computed_groups`], for the arguments after `engine`.
-#[allow(clippy::too_many_arguments)]
-pub unsafe fn publish_computed_groups(
- engine: &mut StyleEngine,
- node: u32,
- pseudo_kind: u8,
- payloads: *const *const c_void,
- count: usize,
- inherited_group_count: usize,
- custom_property_environment: u64,
- inherited_group_swap_candidate: bool,
- counter_style_environment_identity: u64,
- animation_overlay_identity: u64,
- animated_overlay: *const c_void,
- animation_overlay_payloads: *const *const c_void,
- animation_overlay_payload_count: usize,
- longhand_table: *const c_void,
- custom_property_store: *const c_void,
-) -> FfiStyleRecordDelta {
- if count != 0 && payloads.is_null() {
- return FfiStyleRecordDelta::default();
- }
- let payloads = match count {
- 0 => &[],
- _ => SharedPayload::from_pointer_slice(unsafe { ak::slice_from_raw_parts(payloads, count) }),
- };
- if animation_overlay_payload_count != 0 && animation_overlay_payloads.is_null() {
- return FfiStyleRecordDelta::default();
- }
- let animation_overlay_payloads = match animation_overlay_payload_count {
- 0 => &[],
- _ => SharedPayload::from_pointer_slice(unsafe {
- ak::slice_from_raw_parts(animation_overlay_payloads, animation_overlay_payload_count)
- }),
- };
- let longhand_table = unsafe {
- longhand_table
- .cast::<crate::css::computed_longhand_table::ComputedLonghandTable>()
- .as_ref()
- };
- publish_computed_groups_from_inputs(
- engine,
- node,
- pseudo_kind,
- payloads,
- inherited_group_count,
- custom_property_environment,
- inherited_group_swap_candidate,
- counter_style_environment_identity,
- animation_overlay_identity,
- animated_overlay,
- animation_overlay_payloads,
- longhand_table,
- custom_property_store,
- )
-}
-
-/// Builds every style group of the document's own style from its longhand table, against the used color-scheme and
-/// `color` the table computed, and interns the record no element holds. Answers the record.
+/// The record of the document's own style, whose computed values are `values`, with the flags
+/// and dependency flags its computation settled, which no element holds and which holds the
+/// default groups until [`intern_document_style`] builds its own. Answers one reference to it.
+pub(crate) fn document_style_record(
+ values: crate::css::computed_values::GroupValues<'_>,
+ flags: crate::css::computed_longhand_table::LonghandTableFlags,
+ dependency_flags: u8,
+ defaults: &crate::css::computed_values::DefaultGroups,
+) -> *const c_void {
+ let record = super::pipeline::Record::from_values(values, flags, dependency_flags, defaults);
+ std::sync::Arc::into_raw(std::sync::Arc::new(record)).cast()
+}
+
+/// Builds every style group of the document's own style from the longhands of `record`, which
+/// [`document_style_record`] made, against the used color-scheme and `color` they computed, and
+/// installs the record no element holds. Answers the record.
///
/// # Safety
-/// `font` must borrow platform font resources that stay live across the call.
+/// `record` must be a record `document_style_record` made, which the caller holds. `font` must
+/// borrow platform font resources that stay live across the call.
pub(crate) unsafe fn intern_document_style(
engine: &mut StyleEngine,
- table: &ComputedLonghandTable,
+ record: *const c_void,
font: &crate::css::table_group_builder::FfiFontGroupBuildInputs,
length: &crate::css::style_compute::FfiLengthResolutionContext,
) -> u64 {
- use crate::css::table_group_builder::{assemble_group_from_table, assembly_color_inputs, group_index};
- let color_inputs = assembly_color_inputs(table, length);
- let payloads: [*const c_void; group_index::COUNT] = std::array::from_fn(|group| unsafe {
- assemble_group_from_table(table, group, Some(font), None, color_inputs, length)
- });
- let delta = unsafe {
- publish_computed_groups(
- engine,
- 0,
- crate::css::cascaded_properties::NO_PSEUDO_ELEMENT,
- payloads.as_ptr(),
- payloads.len(),
- super::computed::ENGINE_INHERITED_GROUP_COUNT,
- 0,
- false,
- 0,
- 0,
- std::ptr::null(),
- std::ptr::null(),
- 0,
- std::ptr::from_ref(table).cast(),
- std::ptr::null(),
- )
+ use crate::css::table_group_builder::{
+ LonghandSource, assemble_group_from_source, assembly_color_inputs_from_source,
};
- // Interning a record no element holds retains its groups, so the references the builders handed over go back.
- for (group, payload) in payloads.into_iter().enumerate() {
- crate::css::computed_values::release_group_payload(group, payload);
- }
- delta.new_style_record
-}
-
-// Shared by host publication and native layout-style derivation.
-#[allow(clippy::too_many_arguments)]
-pub(crate) fn publish_computed_groups_from_inputs(
- engine: &mut StyleEngine,
- node: u32,
- pseudo_kind: u8,
- payloads: &[SharedPayload],
- inherited_group_count: usize,
- custom_property_environment: u64,
- inherited_group_swap_candidate: bool,
- counter_style_environment_identity: u64,
- animation_overlay_identity: u64,
- animated_overlay: *const c_void,
- animation_overlay_payloads: &[SharedPayload],
- longhand_table: Option<&crate::css::computed_longhand_table::ComputedLonghandTable>,
- custom_property_store: *const c_void,
-) -> FfiStyleRecordDelta {
- assert!(longhand_table.is_some() || (node == 0 && pseudo_kind == u8::MAX));
- let pseudo_element_styles = longhand_table.map_or(0, |table| table.pseudo_element_styles());
- let inherited_group_swap_eligible = longhand_table.is_some_and(|table| {
- inherited_group_swap_candidate && table.property_inheritance_is_standard() && !table.display_is_list_item()
- });
- let holds_image_values =
- // SAFETY: Published style-group payloads stay live while their records do.
- unsafe { crate::css::computed_values::style_group_payloads_hold_image_values(HostShared::as_pointer_slice(payloads)) }
- // SAFETY: Published style-group payloads stay live while their records do.
- || unsafe { crate::css::computed_values::style_group_payloads_hold_image_values(HostShared::as_pointer_slice(
- animation_overlay_payloads,
- )) };
- let dependency_flags = longhand_table.map_or(0, |table| table.publication_dependency_flags())
- | (u8::from(inherited_group_swap_eligible) * super::computed::INHERITED_GROUP_SWAP_ELIGIBLE)
- | (u8::from(holds_image_values) * super::computed::HOLDS_IMAGE_VALUES);
- if animation_overlay_identity != 0 && animated_overlay.is_null() {
- return FfiStyleRecordDelta::default();
- }
- let metadata_input = super::computed::ComputedMetadataInput {
- pseudo_element_styles,
- dependency_flags,
- counter_style_environment_identity,
- animation_overlay_identity,
- animated_overlay: HostShared::new(animated_overlay).cast(),
- animation_overlay_payloads,
- longhand_table: HostShared::new(longhand_table.map_or(std::ptr::null(), std::ptr::from_ref)),
+ // SAFETY: Guaranteed by the caller.
+ let record = unsafe { &*record.cast::<super::pipeline::Record>() };
+ let source = LonghandSource::Longhands {
+ longhands: super::ViewLonghands::of_record(record),
+ animated_overlay: None,
};
- let publication = if let Some(node) = StyleNodeID::from_raw(node) {
- let target = super::computed::ComputedStyleTarget::new(node, pseudo_kind);
- engine.forget_engine_computed_record(target);
- engine.publish_computed_groups(
- target,
- payloads,
- inherited_group_count,
- custom_property_environment,
- metadata_input,
- )
- } else {
- engine.intern_computed_groups(
- if animation_overlay_identity != 0 {
- animation_overlay_payloads
- } else {
- payloads
- },
- inherited_group_count,
- custom_property_environment,
- metadata_input,
+ let color_inputs = assembly_color_inputs_from_source(&source, length);
+ // SAFETY: Each build hands over a reference to a payload of its group.
+ let payloads = unsafe {
+ crate::css::computed_values::StyleGroups::adopt(
+ std::array::from_fn(|group| {
+ assemble_group_from_source(
+ &source,
+ group,
+ Some(font),
+ crate::css::computed_values::GroupShares::new(engine.default_groups(), group, None),
+ color_inputs,
+ length,
+ )
+ }),
+ source.style_bits(),
)
};
- // The store is what the environment resolves to; an engine-computed environment builds on it,
- // and an element alike in its custom declarations takes the environment itself.
- unsafe {
- engine
- .custom_property_environments
- .retain_raw(custom_property_environment, custom_property_store);
- }
- if pseudo_kind == u8::MAX
- && let Some(node) = StyleNodeID::from_raw(node)
- {
- engine.remember_cpp_custom_property_environment(node, custom_property_environment);
- }
- FfiStyleRecordDelta {
- old_style_record: publication
- .previous_style_record_identity
- .map_or(0, super::computed::FinalStyleRecordID::raw),
- new_style_record: publication.style_record_identity.raw(),
- }
+ let record = engine.install_record_derived(record, &payloads, None);
+ record.raw()
}
/// What the winners a node's records were computed from read beyond their cascade, one bit per
-/// kind, as a row's `record_reads` carries them.
+/// kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum FfiNodeRecordReads {
/// An `attr()` substitution, in the element's winners, its pseudo-elements' or the custom
/// properties it declares: an attribute change reaches the records.
Attributes = 1 << 0,
- /// A tree-counting function, in the element's winners or its pseudo-elements', written or
- /// substituted: a change among the element's siblings reaches the records.
- SiblingPosition = 1 << 1,
/// An `inherit()` substitution, in the element's winners, its pseudo-elements' or the custom
/// properties either declares: a moved environment of the parent reaches the records.
InheritFunction = 1 << 2,
@@ -2114,944 +1652,21 @@ pub enum FfiNodeRecordReads {
CustomFunction = 1 << 4,
}
-/// Computes what moving an element from one final style record to another damages, from the
-/// records and the facts the engine holds of the element. The counter styles its box was built
-/// with are the host's to compare.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_element_record_damage(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- node: u32,
- old_style_record: u64,
- new_style_record: u64,
-) -> u32 {
- with_engine(read, host, |engine| {
- let Some(node) = StyleNodeID::from_raw(node) else {
- return super::style_invalidation::unreadable_record_damage();
- };
- engine.element_record_damage(node, false, old_style_record, new_style_record)
- })
-}
-
-/// Computes what moving one of an element's pseudo-elements from one final style record to another
-/// damages, where either record can be zero. `counter_styles_changed` is the host's comparison of
-/// the counter styles the pseudo-element's box was built with.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_pseudo_element_record_damage(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- node: u32,
- pseudo_kind: u8,
- old_style_record: u64,
- new_style_record: u64,
- originating_style_record: u64,
- counter_styles_changed: bool,
-) -> u32 {
- with_engine(read, host, |engine| {
- let Some(node) = StyleNodeID::from_raw(node) else {
- return super::style_invalidation::unreadable_record_damage();
- };
- engine.pseudo_element_record_damage(
- node,
- pseudo_kind,
- old_style_record,
- new_style_record,
- originating_style_record,
- counter_styles_changed,
- )
- })
-}
-
-/// Whether a candidate animation overlay changes any effective value of the record `installed` views, in place of the
-/// record's own overlay. The host reads it from the record it installed, as the engine would.
-///
-/// # Safety
-/// `installed` must view a record the host holds live, and `animated_overlay` must be null or live, for this call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_animation_overlay_changed(
- installed: &FfiStyleRecordView,
- animated_overlay: *const c_void,
-) -> bool {
- // SAFETY: Guaranteed by the caller.
- let (table, old_overlay, new_overlay) = unsafe {
- (
- installed.longhand_table(),
- installed.animated_overlay(),
- animated_overlay.cast::<AnimatedOverlay>().as_ref(),
- )
- };
- super::style_invalidation::animation_overlay_changed(table, old_overlay, new_overlay)
-}
-
-/// What the host hands over to have an element's sampled animation overlay composed over the record it installed and
-/// published.
-#[repr(C)]
-pub struct FfiAnimationOverlayPublicationInput {
- pub style_node: u32,
- pub pseudo_kind: u8,
- /// The record the element installed, which the overlay was sampled on and composes over.
- pub style_record: u64,
- /// The longhand table the overlay was sampled over.
- pub longhand_table: *const c_void,
- pub animated_overlay: *const c_void,
- /// The identity of the overlay, or 0 where it animates nothing, which releases the target's overlay record.
- pub animation_overlay_identity: u64,
- pub used_color_scheme: u8,
- pub display_before_box_type_transformation_raw: u32,
- pub is_document_element: bool,
- /// What a target the engine holds no overlay slot for is published again whole with, beside the installed record's
- /// base: the number of inherited style groups, and the custom-property environment the target holds, with its
- /// store.
- pub inherited_group_count: usize,
- pub custom_property_environment: u64,
- pub custom_property_store: *const c_void,
- pub callback_context: *mut c_void,
- /// Writes the animated style's platform font, a `ComputedValuesFFI::FfiFontGroupBuildInputs`;
- /// asked only where the font group is rebuilt.
- pub font_group_inputs: unsafe extern "C" fn(*mut c_void, *mut c_void),
-}
-
-/// What publishing an element's sampled animation overlay answers: what replacing the installed record with it damages,
-/// the record the target held and the one it holds now, with the view of the latter, which is missing where the engine
-/// holds no record the overlay was sampled on.
-#[repr(C)]
-pub struct FfiAnimationOverlayPublication {
- pub invalidation: FfiAnimationInvalidation,
- pub publication: FfiStyleRecordDelta,
- pub view: FfiStyleRecordView,
- /// Whether the overlay named a value the groups could not be told from, or nothing at all.
- pub rebuilt_every_group: bool,
-}
-
-impl FfiAnimationOverlayPublication {
- fn missing() -> Self {
- Self {
- invalidation: FfiAnimationInvalidation::default(),
- publication: FfiStyleRecordDelta::default(),
- view: FfiStyleRecordView::missing(),
- rebuilt_every_group: false,
- }
- }
-}
-
-/// Composes each element's sampled animation overlay over the record it installed, rebuilding only the groups the
-/// overlay writes (see `RetainedState::build_animation_overlay_payloads`), compares it with that record, and publishes
-/// it as the target's record, writing what it answers to the same index of `out`: every element in one call of the
-/// engine. An element whose overlay rebuilds the font group is published again in a call of its own: resolving the
-/// animated font may read the engine, so the host resolves it between the two. The host keeps the view of each record
-/// it answers, which it installs next.
-///
-/// # Safety
-/// `host` must be a live document host, on its document's thread, `inputs` and `out` must point to `count` entries, and
-/// everything an input points to must be live for the call, its table non-null.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_publish_sampled_animation_overlays(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- inputs: *const FfiAnimationOverlayPublicationInput,
- count: usize,
- out: *mut FfiAnimationOverlayPublication,
-) {
- use crate::css::table_group_builder::FfiFontGroupBuildInputs;
-
- // SAFETY: Guaranteed by the caller.
- let (inputs, out) = unsafe {
- (
- ak::slice_from_raw_parts(inputs, count),
- ak::slice_from_raw_parts_mut(out, count),
- )
- };
- with_engine(read, host, |engine| {
- for (input, out) in inputs.iter().zip(out.iter_mut()) {
- // SAFETY: Guaranteed by the caller.
- *out = unsafe { publish_sampled_animation_overlay(engine, input, None) }
- .unwrap_or_else(|super::engine_sample::NeedsHostFont| FfiAnimationOverlayPublication::missing());
- }
- });
- for (input, out) in inputs.iter().zip(out.iter_mut()) {
- if !out.view.present {
- // A publication the first call could not make, for want of the font or of a record, is tried again with
- // the font.
- let mut font = std::mem::MaybeUninit::<FfiFontGroupBuildInputs>::uninit();
- // SAFETY: Guaranteed by the caller. The host writes the whole font.
- let font = unsafe {
- (input.font_group_inputs)(input.callback_context, font.as_mut_ptr().cast());
- font.assume_init()
- };
- // SAFETY: Guaranteed by the caller.
- *out = with_engine(read, host, |engine| unsafe {
- publish_sampled_animation_overlay(engine, input, Some(&font))
- })
- .unwrap_or_else(|super::engine_sample::NeedsHostFont| FfiAnimationOverlayPublication::missing());
- }
- if out.view.present {
- host.engine_memo().views.set(out.publication.new_style_record, out.view);
- }
- }
-}
-
-/// [`style_engine_publish_sampled_animation_overlays`]'s call of `engine` for one element, which answers `Err` where it
-/// needs the animated font, `font`, it was not given.
-///
-/// # Safety
-/// As for [`style_engine_publish_sampled_animation_overlays`], for one input.
-unsafe fn publish_sampled_animation_overlay(
- engine: &mut StyleEngine,
- input: &FfiAnimationOverlayPublicationInput,
- font: Option<&crate::css::table_group_builder::FfiFontGroupBuildInputs>,
-) -> Result<FfiAnimationOverlayPublication, super::engine_sample::NeedsHostFont> {
- use crate::css::table_group_builder::group_index;
-
- let Some(node) = StyleNodeID::from_raw(input.style_node) else {
- return Ok(FfiAnimationOverlayPublication::missing());
- };
- let Some(installed_style_record) = super::computed::FinalStyleRecordID::from_raw(input.style_record) else {
- return Ok(FfiAnimationOverlayPublication::missing());
- };
- // SAFETY: Guaranteed by the caller.
- let (table, overlay) = unsafe {
- (
- &*input.longhand_table.cast::<ComputedLonghandTable>(),
- input.animated_overlay.cast::<AnimatedOverlay>().as_ref(),
- )
- };
- let mut payloads = [std::ptr::null(); group_index::COUNT];
- let Some(rebuilt) = engine.build_animation_overlay_payloads(
- node,
- input.pseudo_kind,
- input.style_record,
- table,
- overlay,
- input.used_color_scheme,
- input.display_before_box_type_transformation_raw,
- font,
- &mut payloads,
- ) else {
- return Ok(FfiAnimationOverlayPublication::missing());
- };
- let rebuilt = rebuilt?;
- // Compared before the publication, which may release the installed record: nothing else keeps a pseudo-element's.
- let invalidation = engine.compare_animation_overlay(
- input.style_record,
- input.animated_overlay.cast(),
- SharedPayload::from_pointer_slice(&payloads),
- input.is_document_element,
- );
- let (animated_overlay, overlay_payloads) = match input.animation_overlay_identity {
- 0 => (std::ptr::null(), &[][..]),
- _ => (input.animated_overlay, &payloads[..]),
- };
- let publication = match engine.publish_animation_overlay_impl(
- super::computed::ComputedStyleTarget::new(node, input.pseudo_kind),
- installed_style_record,
- input.animation_overlay_identity,
- HostShared::new(animated_overlay).cast(),
- SharedPayload::from_pointer_slice(overlay_payloads),
- ) {
- Some(publication) => FfiStyleRecordDelta {
- old_style_record: publication.previous_style_record.raw(),
- new_style_record: publication.style_record.raw(),
- },
- // A pseudo-element the engine holds no assignment for owns no overlay slot, so the record is published again
- // whole, with the overlay over the same base.
- None => {
- let base = style_record_view(engine, input.style_record);
- // SAFETY: Guaranteed by the caller, and the base's arrays are live.
- unsafe {
- publish_computed_groups(
- engine,
- input.style_node,
- input.pseudo_kind,
- base.base_payloads,
- base.payload_count,
- input.inherited_group_count,
- input.custom_property_environment,
- false,
- base.counter_style_environment_identity,
- input.animation_overlay_identity,
- animated_overlay,
- overlay_payloads.as_ptr(),
- overlay_payloads.len(),
- base.longhand_table,
- input.custom_property_store,
- )
- }
- }
- };
- super::engine_sample::release_rebuilt_overlay_payloads(&payloads, rebuilt.groups);
- Ok(FfiAnimationOverlayPublication {
- invalidation,
- publication,
- view: style_record_view(engine, publication.new_style_record),
- rebuilt_every_group: rebuilt.every_group,
- })
-}
-
-/// The style groups from `first_group` up to `end_group` whose payloads differ between two records, through their
-/// base payloads or their composed ones, or every group when either view is missing or holds fewer groups.
-///
-/// # Safety
-/// Both views must be views of live records.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_changed_style_groups(
- old: &FfiStyleRecordView,
- new: &FfiStyleRecordView,
- first_group: usize,
- end_group: usize,
-) -> u32 {
- let payloads = |view: &FfiStyleRecordView| {
- if !view.present || view.payloads.is_null() || view.base_payloads.is_null() {
- return None;
- }
- // SAFETY: Guaranteed by the caller: a live record's view holds `payload_count` payloads of each kind.
- Some(unsafe {
- [
- SharedPayload::from_pointer_slice(ak::slice_from_raw_parts(view.base_payloads, view.payload_count)),
- SharedPayload::from_pointer_slice(ak::slice_from_raw_parts(view.payloads, view.payload_count)),
- ]
- })
- };
- let (Some(old), Some(new)) = (payloads(old), payloads(new)) else {
- return u32::MAX;
- };
- // SAFETY: Published style-group payloads stay live while their records do.
- unsafe { crate::css::computed_values::changed_style_groups(old, new, first_group..end_group) }.unwrap_or(u32::MAX)
-}
-
-/// Returns a synchronous borrowed view of a base or live animation-overlay record.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_style_record_view(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- style_record: u64,
-) -> FfiStyleRecordView {
- if let Some(view) = super::engine_calls::known_style_record_view(host, style_record) {
- return view;
- }
- let view = with_engine(read, host, |engine| style_record_view(engine, style_record));
- if view.present {
- host.engine_memo().views.set(style_record, view);
- }
- view
-}
-
-/// [`style_engine_style_record_view`] on `engine`.
-pub fn style_record_view(engine: &mut StyleEngine, style_record: u64) -> FfiStyleRecordView {
- let view = engine.style_record_view(style_record);
- match &view {
- None => FfiStyleRecordView::missing(),
- Some(view) => FfiStyleRecordView {
- payloads: SharedPayload::as_pointer_slice(view.payloads).as_ptr(),
- base_payloads: SharedPayload::as_pointer_slice(view.base_payloads).as_ptr(),
- longhand_table: HostShared::from_option(view.longhand_table).cast().as_ptr(),
- animated_overlay: HostShared::from_option(view.animated_overlay).cast().as_ptr(),
- payload_count: view.payloads.len(),
- pseudo_element_styles: view.pseudo_element_styles,
- counter_style_environment_identity: view.counter_style_environment_identity,
- animation_overlay_identity: view.animation_overlay_identity,
- dependency_flags: view.dependency_flags,
- present: true,
- },
- }
-}
-
-/// Removes the retained computed-input assignment for one pseudo-element kind.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_remove_computed_pseudo(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- node: u32,
- pseudo_kind: u8,
-) -> FfiStyleRecordDelta {
- with_engine(read, host, |engine| remove_computed_pseudo(engine, node, pseudo_kind))
-}
-
-/// [`style_engine_remove_computed_pseudo`] on `engine`.
-pub fn remove_computed_pseudo(engine: &mut StyleEngine, node: u32, pseudo_kind: u8) -> FfiStyleRecordDelta {
- let Some(node) = StyleNodeID::from_raw(node) else {
- return FfiStyleRecordDelta::default();
- };
- FfiStyleRecordDelta {
- old_style_record: engine
- .remove_computed_pseudo(node, pseudo_kind)
- .map_or(0, super::computed::FinalStyleRecordID::raw),
- new_style_record: 0,
- }
-}
-pub(crate) fn publish_rule_declarations(
- engine: &mut StyleEngine,
- rule: u32,
- data: &crate::css::declaration_block::DeclarationBlockData,
-) -> bool {
- if rule == 0 {
- return false;
- }
- let mut has_transitions = false;
- let declared = data
- .properties
- .iter()
- .map(|declaration| {
- use crate::css::property_metadata::property_defines_a_css_transition;
- has_transitions |= property_defines_a_css_transition(declaration.property_id);
- engine.intern_declared_property(declaration)
- })
- .collect::<Vec<_>>();
- let written_values: Vec<_> = data
- .properties
- .iter()
- .map(|declaration| RetainedStyleValueData::from_arc(declaration.value.clone()))
- .collect();
- let (custom_declarations, custom_written_values) =
- collect_native_custom_declarations(engine, &data.custom_properties)
- .into_iter()
- .unzip::<_, _, Vec<_>, Vec<_>>();
- engine.set_rule_declared_properties_with_written_values(
- RuleID(rule - 1),
- &declared,
- written_values,
- custom_declarations,
- custom_written_values,
- );
- has_transitions
-}
-
-/// Moves a node's record to the custom-property environment C++ refreshed it to, keeping the
-/// store behind the environment, and returns the new record's identity; zero when the node holds
-/// no record to move. Only a base record moves: an environment move computes an element holding a
-/// record that composes animated values again instead of having C++ refresh it.
-///
-/// # Safety
-/// `host` must be a live document host, on its document's thread, and `store` must be null or a
-/// live raw `Arc` pointer.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_republish_record_environment(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- node: u32,
- environment: u64,
- store: *const c_void,
-) -> u64 {
- // SAFETY: Guaranteed by the caller.
- let (style_record, view) = with_engine(read, host, |engine| {
- let Some(node) = StyleNodeID::from_raw(node) else {
- return (0, None);
- };
- unsafe { engine.custom_property_environments.retain_raw(environment, store) };
- let Some(style_record) = engine.republish_record_environment(node, environment) else {
- return (0, None);
- };
- (style_record, Some(style_record_view(engine, style_record)))
- });
- if let Some(view) = view
- && view.present
- {
- host.engine_memo().views.set(style_record, view);
- }
- style_record
-}
-
-/// An environment the host holds, as a custom-property environment move names it: its identity and
-/// the store behind it, both zero for the empty environment.
-#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct FfiNamedEnvironment {
- pub identity: u64,
- pub store: *const c_void,
-}
-
-/// A move of one element's custom-property environment, as the host made it: what it handed its
-/// children before and hands them now, with the host's object for the latter and whether that
-/// declares custom properties of its own.
-#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct FfiEnvironmentMove {
- pub old_environment: FfiNamedEnvironment,
- pub new_environment: FfiNamedEnvironment,
- pub old_inheritable: u64,
- pub new_inheritable: FfiNamedEnvironment,
- pub new_inheritable_data: *const c_void,
- pub new_inheritable_declares: bool,
-}
-
-/// What a read of one element's style the host makes before the next style update asks of the
-/// engine; see `StyleEngine::answer_record_demand`. A read-only demand leaves the engine as it
-/// was: its record is only for the host to read. Any other is installed and acknowledged as a
-/// style update's would be.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-#[expect(dead_code, reason = "C++ constructs the variants")]
-pub enum FfiRecordDemand {
- /// A targeted style update of the element: its record, driven in full against the parent as it
- /// is now.
- TargetedElement,
- /// A read-only read of the element's record.
- ElementRead,
- /// A read-only read of what the element computes to as though it had no inline declaration,
- /// driven in full against the parent as it is now.
- ElementReadWithoutInlineStyle,
- /// A read-only read of the element's record, driven in full against the parent as it is now,
- /// which the reader assigned a record of its own.
- ElementReadAgainstParent,
-}
-
-/// What a read of one of an element's pseudo-elements the host makes before the next style update
-/// asks of the engine, as `FfiRecordDemand` does of an element.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-#[cfg_attr(not(test), expect(dead_code, reason = "C++ constructs the variants"))]
-pub enum FfiPseudoElementRecordDemand {
- /// A CSSOM read of the pseudo-element, settled against its element's installed record.
- CssomRead,
- /// A read-only read of what the pseudo-element computes to, whether or not it generates a box.
- ReadOnly,
-}
-
-/// A pseudo-element a record demand may read: a synthetic one, which the engine settles beside its
-/// element, or, for a read-only read, one an element in the shadow tree backs or a named view
-/// transition one, which it computes from the element's rules for it. Each is numbered as its kind.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-#[expect(dead_code, reason = "C++ constructs the variants")]
-pub enum FfiDemandedPseudoElement {
- After = 0,
- Backdrop = 1,
- Before = 2,
- FirstLetter = 3,
- FirstLine = 4,
- Marker = 5,
- SearchText = 6,
- SearchTextCurrent = 7,
- Selection = 8,
- SpellingError = 9,
- ViewTransition = 10,
- DetailsContent = 11,
- FileSelectorButton = 12,
- Placeholder = 13,
- SliderFill = 14,
- SliderThumb = 15,
- SliderTrack = 16,
- ViewTransitionGroup = 20,
- ViewTransitionImagePair = 21,
- ViewTransitionNew = 22,
- ViewTransitionOld = 23,
-}
-
-/// The answer to a record demand: the record, or that the pseudo-element read generates no box
-/// with the custom-property environment its rules resolve to (zero where none styles it). A zero
-/// `style_record` that is not absent leaves the read to C++.
-#[derive(Clone, Copy, Debug, Default)]
-#[repr(C)]
-pub struct FfiRecordDemandAnswer {
- pub record: FfiEngineComputedRecord,
- pub is_absent: bool,
- pub custom_property_environment: u64,
-}
-
-/// Answer a read of one element's style, or one of its pseudo-elements', the host makes before
-/// the next style update.
-pub(crate) fn answer_record_demand(
- engine: &mut StyleEngine,
- style_node: StyleNodeID,
- demand: super::publication::RecordDemand,
-) -> FfiRecordDemandAnswer {
- let answer = engine.answer_record_demand(style_node, demand);
- ffi_record_demand_answer(engine, style_node, demand.is_read_only(), answer)
-}
-
-/// The FFI form of `answer`, what a demand of `style_node`'s record answered.
-pub(in crate::css::style) fn ffi_record_demand_answer(
- engine: &mut StyleEngine,
- style_node: StyleNodeID,
- read_only: bool,
- answer: Result<super::publication::RecordDemandAnswer, super::publication::Unanswered>,
-) -> FfiRecordDemandAnswer {
- match answer {
- Ok(super::publication::RecordDemandAnswer::Record {
- record,
- uses_substitution,
- }) => FfiRecordDemandAnswer {
- record: FfiEngineComputedRecord {
- style_record: record.style_record,
- uses_substitution,
- // A read-only answer is the host's to read, never to install.
- record_reads: if record.style_record != 0 && !read_only {
- engine.node_record_reads(style_node)
- } else {
- 0
- },
- explicitly_inherited_groups: record.explicitly_inherited_groups,
- owes_an_animation_plan: record.owes_an_animation_plan,
- owes_a_transition_step: record.owes_a_transition_step,
- composed_by_the_host: record.composed_by_the_host,
- pseudo_records_present: record.pseudo_records_present,
- pseudo_records: record.pseudo_records,
- },
- is_absent: false,
- custom_property_environment: 0,
- },
- Ok(super::publication::RecordDemandAnswer::Absent {
- custom_property_environment,
- }) => FfiRecordDemandAnswer {
- record: FfiEngineComputedRecord::default(),
- is_absent: true,
- custom_property_environment,
- },
- Err(_) => FfiRecordDemandAnswer::default(),
- }
-}
-
-/// The record of an element no rule reaches, computed from its presentational hints and its
-/// inline style alone over the initial values, its custom properties among them; see
-/// `declared_only_record`. `subject` is the
-/// document's style node. Returns a pinned record the host unpins, or zero where the engine
-/// leaves the computation to C++.
-///
-/// # Safety
-/// `host` must be a live document host, on its document's thread. `hints` must borrow `hint_count`
-/// `FfiDeclaredProperty` entries whose values point at live, Arc-backed `StyleValueData` roots. A
-/// non-null `inline_block` must borrow a live `DeclarationBlock`.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_declared_only_record(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- subject: u32,
- facts: u32,
- hint_kind: FfiElementDeclarationKind,
- hints: *const c_void,
- hint_count: usize,
- inline_block: *const c_void,
-) -> u64 {
- // SAFETY: Guaranteed by the caller.
- with_engine(read, host, |engine| {
- use crate::css::declaration_block::{DeclarationBlock, FfiDeclaredProperty, declaration_from_view};
- abort_on_panic(|| {
- let Some(subject) = StyleNodeID::from_raw(subject) else {
- return 0;
- };
- let hints = if hint_count == 0 {
- &[]
- } else {
- unsafe { ak::slice_from_raw_parts(hints.cast::<FfiDeclaredProperty>(), hint_count) }
- };
- let hints = hints
- .iter()
- .map(|hint| unsafe { declaration_from_view(hint) })
- .collect::<Vec<_>>();
- let inline_data = unsafe { inline_block.cast::<DeclarationBlock>().as_ref() }.map(DeclarationBlock::data);
- let hint_kind = decode_element_declaration_kind(hint_kind);
- let declarations = hints
- .iter()
- .map(|hint| (hint_kind, hint))
- .chain(inline_data.iter().flat_map(|data| {
- data.properties
- .iter()
- .map(|declaration| (ElementDeclarationKind::InlineStyle, declaration))
- }))
- .collect::<Vec<_>>();
- let custom_declarations = collect_native_custom_declarations(
- engine,
- inline_data
- .as_ref()
- .map_or(&[], |data| data.custom_properties.as_slice()),
- );
- engine
- .declared_only_record(subject, facts, &declarations, &custom_declarations)
- .map_or(0, super::computed::FinalStyleRecordID::raw)
- })
- })
-}
-
-/// Settle the synthetic pseudo-element records of an element whose record the host just installed.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_settle_pseudo_records_after_host_record(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- node: u32,
- old_is_list_item: bool,
-) -> FfiSettledPseudoRecords {
- with_engine(read, host, |engine| {
- settle_pseudo_records_after_host_record(engine, node, old_is_list_item)
- })
-}
-
-/// [`style_engine_settle_pseudo_records_after_host_record`] on `engine`.
-pub fn settle_pseudo_records_after_host_record(
- engine: &mut StyleEngine,
- node: u32,
- old_is_list_item: bool,
-) -> FfiSettledPseudoRecords {
- abort_on_panic(|| {
- let Some(style_node) = StyleNodeID::from_raw(node) else {
- return FfiSettledPseudoRecords::default();
- };
- let mut result = engine.settle_pseudo_records_after_host_record(style_node, old_is_list_item);
- if !result.refused {
- result.record_reads = engine.node_record_reads(style_node);
- }
- result
- })
-}
-
-/// The store of an environment the engine resolved, with one strong reference transferred to the
-/// caller, and the environment it was resolved over; null for an environment C++ published.
-///
-/// # Safety
-/// `host` must be a live document host, on its document's thread, and `parent` must be writable.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_borrow_engine_custom_property_environment(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- identity: u64,
- parent: *mut u64,
-) -> *const c_void {
- // SAFETY: Guaranteed by the caller.
- with_engine(read, host, |engine| {
- let Some((store, parent_identity)) = engine.custom_property_environments.engine_environment(identity) else {
- return std::ptr::null();
- };
- unsafe { *parent = parent_identity };
- std::sync::Arc::into_raw(std::sync::Arc::clone(store)).cast()
- })
-}
-
-#[repr(C)]
-pub struct FfiNativeRuleTarget {
- pub identity: u64,
- pub declaration_version: u32,
- pub source_identity: u64,
- pub declarations: *const c_void,
- pub layer_name: *const u16,
- pub layer_name_length: usize,
- pub has_container_conditions: bool,
- pub origin: FfiCascadeOrigin,
-}
-
-/// Issue a new identity for changed declaration contents, independently of CSSOM wrappers.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_next_declaration_block_version(host: &DocumentHost) -> u32 {
- host.next_declaration_block_version()
-}
-
-/// Queues a native declaration edit for the rule that owns the declarations, where the host published that rule to the
-/// sheet `sheet`, and answers whether they declare transitions. The host is told first, with no engine borrowed.
-///
-/// # Safety
-/// The callback must not mutate the native rule graph, and must remain valid for this call.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_native_rule_declarations_changed(
- host: &DocumentHost,
- sheet: u32,
- rule: &crate::css::rule::NativeRule,
- context: *mut c_void,
- notify: unsafe extern "C" fn(*mut c_void),
-) -> bool {
- let Some(identity) = rule
- .declaration_owner_identity()
- .filter(|&identity| host.published_rules().contains(sheet, identity))
- else {
- return false;
- };
- // SAFETY: Guaranteed by the caller.
- unsafe { notify(context) };
- let declarations = rule.cascade_declarations();
- let transitions = declarations
- .as_ref()
- .is_some_and(|declarations| declares_transitions(&declarations.properties));
- host.write_rules(RuleWrite::RuleDeclarations { identity, declarations });
- transitions
-}
-
-/// The native identity of the first rule after an inserted native subtree that the host published to the sheet
-/// `sheet`, or 0 for none, without creating CSSOM objects.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_native_rule_successor(
- host: &DocumentHost,
- sheet: u32,
- native: &crate::css::style_sheet::NativeStyleSheet,
- identity: u64,
-) -> u64 {
- host.published_rules().successor(sheet, native, identity)
-}
-
-/// Retires a native subtree from the sheet `sheet`, with host callbacks only for document and cascade-cache
-/// notifications, and queues the removal of the rules the host published there.
-///
-/// # Safety
-/// `host` must be a live document host, on its document's thread, and the native sheet, rule, callbacks, and any
-/// non-null detached import must be live. Native rules must belong to Rc allocations. No graph borrow spans a host
-/// callback.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_remove_native_rule(
- host: &DocumentHost,
- native: *const c_void,
- rule: *const c_void,
- detached_import: *const c_void,
- sheet: u32,
- context: *mut c_void,
- begin: unsafe extern "C" fn(*mut c_void, bool, bool),
- notify: unsafe extern "C" fn(*mut c_void, bool),
-) {
- use crate::css::rule::{NativeRule, NativeRuleType, mutation, read::RuleRef};
- use crate::css::style_sheet::NativeStyleSheet;
- // SAFETY: Guaranteed by the caller.
- let removed = unsafe {
- mutation::removed_rules(
- &*rule.cast::<NativeRule>(),
- &*native.cast::<NativeStyleSheet>(),
- detached_import.cast::<NativeStyleSheet>().as_ref(),
- )
- };
- let changes_environment =
- RuleRef::Materialized(unsafe { &*rule.cast::<NativeRule>() }).change_needs_style_environment_bump();
- let has_counter_style = removed
- .iter()
- .any(|rule| RuleRef::Materialized(rule).rule_type() == NativeRuleType::CounterStyle);
- unsafe { begin(context, changes_environment, has_counter_style) };
- let mut published = Vec::new();
- for rule in removed {
- unsafe { notify(context, mutation::declares_layer(&rule)) };
- let identity = RuleRef::Materialized(&rule).identity();
- if host.published_rules().remove(sheet, identity) {
- published.push(identity);
- }
- }
- if !published.is_empty() {
- host.write_rules(RuleWrite::RemoveRules(published.into()));
- }
-}
-
-/// Read a rule's native cascade data without a CSSOM facade.
-///
-/// On success the caller owns declarations and must release it with
-/// rust_declaration_data_release. Layer text is borrowed until the next rule mutation; callers must
-/// copy any text needed across such a mutation. Source identity never retains a native sheet.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_native_rule_target(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- rule: u32,
- result: &mut FfiNativeRuleTarget,
-) -> bool {
- with_engine(read, host, |engine| native_rule_target(engine, rule, result))
-}
-
-/// [`style_engine_native_rule_target`] on `engine`.
-pub fn native_rule_target(engine: &mut StyleEngine, rule: u32, result: &mut FfiNativeRuleTarget) -> bool {
- let Some(target) = rule
- .checked_sub(1)
- .and_then(|id| engine.native_rules.targets.get(&RuleID(id)))
- else {
- return false;
- };
- let Some(declarations) = target.declarations() else {
- return false;
- };
- let origin = engine.program.sheet_origin(engine.program.rule_sheet(RuleID(rule - 1)));
- *result = FfiNativeRuleTarget {
- identity: target.identity.get(),
- declaration_version: engine
- .current_rule_version(RuleID(rule - 1))
- .declaration_block
- .map_or(0, |version| version.0),
- source_identity: target.source_identity,
- declarations: std::sync::Arc::into_raw(declarations.clone()).cast(),
- layer_name: target.layer_name().as_ptr(),
- layer_name_length: target.layer_name().len(),
- has_container_conditions: !target.containers().is_empty(),
- origin: match origin {
- CascadeOrigin::Author => FfiCascadeOrigin::Author,
- CascadeOrigin::AuthorPresentationalHint => FfiCascadeOrigin::AuthorPresentationalHint,
- CascadeOrigin::User => FfiCascadeOrigin::User,
- CascadeOrigin::UserAgent => FfiCascadeOrigin::UserAgent,
- },
- };
- true
-}
-
-/// What a container condition the engine evaluated read of a container or its subject, which the
-/// host records as it records its own evaluation's.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-pub enum FfiContainerEffectKind {
- /// The node is a container a size or scroll-state query asks about.
- SizeContainerUsage,
- /// The node is a container a style query asks about.
- StyleContainerUsage,
- /// The node is a scroll-state container a query asks about, whose state is snapshotted.
- ScrollStateContainerUsage,
- /// The node has no box yet, and the query is evaluated again after layout.
- NeedsEvaluationAfterLayout,
- /// The subject's style resolved a viewport-relative length in the query.
- SubjectViewportDependency,
- /// A container-relative length resolved against the node, which has no box yet, and is
- /// resolved again after layout, a partial relayout included.
- UnitsNeedEvaluationAfterLayout,
-}
-
-#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct FfiContainerEffect {
- pub node: u32,
- pub kind: FfiContainerEffectKind,
-}
-
-/// What the container conditions of a row the engine answered read of its containers, besides the
-/// effects: whether the row's style depends on a size or scroll-state query or a style query, and
-/// the custom properties its style queries read, null or the host's to take with
-/// `rust_style_query_dependencies_take`.
-#[repr(C)]
-pub struct FfiContainerEffects {
- pub depends_on_size: bool,
- pub depends_on_style: bool,
- pub style_query_references: *mut c_void,
-}
-
-/// Takes what the container conditions of the row the host is installing for `node` read of its
-/// containers, for the host to record as it records its own evaluation's. Each effect is handed to
-/// `record` with no engine borrow held, so recording may call the engine.
-///
-/// # Safety
-/// `host` must be a live document host, on its document's thread.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_take_container_effects(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- node: u32,
- context: *mut c_void,
- record: unsafe extern "C" fn(*mut c_void, FfiContainerEffect),
-) -> FfiContainerEffects {
- let verdict = StyleNodeID::from_raw(node)
- .filter(|_| host.container_effects_may_be_held())
- .and_then(|node| with_engine(read, host, |engine| engine.take_container_effects_for_host(node)))
- .unwrap_or_default();
- for (node, kind) in verdict.effects {
- unsafe { record(context, FfiContainerEffect { node: node.raw(), kind }) };
- }
- FfiContainerEffects {
- depends_on_size: verdict.depends_on_size,
- depends_on_style: verdict.depends_on_style,
- style_query_references: verdict
- .style_query_references
- .map_or(std::ptr::null_mut(), |references| Box::into_raw(references).cast()),
- }
-}
-
/// Interns the UTF-16 name `units` in `engine` as a native style atom.
pub(crate) fn intern_native_text(engine: &mut StyleEngine, units: &[u16]) -> StyleAtomID {
let name = ak::Utf16FlyString::from_utf16(units);
engine.atoms.intern_raw(name.raw_identity())
}
-/// Takes the pending style transaction under `root` and answers its versioned semantic match answers.
+/// Takes the pending style update under `root` and answers its rows.
///
/// # Safety
/// The host lends the buffers `computation_inputs` names for this call.
-pub(crate) unsafe fn take_style_transaction(
+pub(crate) unsafe fn run_style_update(
engine: &mut StyleEngine,
root: StyleNodeID,
mut computation_inputs: FfiDocumentStyleComputationInputs,
- closes_beside: Option<&super::HashSet<StyleNodeID>>,
-) -> FfiStyleTransactionOutput {
+) -> FfiStyleUpdateOutput {
// SAFETY: Guaranteed by the caller.
unsafe { engine.document_resource_contexts.take_in(&mut computation_inputs) };
// SAFETY: The host lends the media environment the inputs name for this call.
@@ -3070,22 +1685,17 @@ pub(crate) unsafe fn take_style_transaction(
.custom_property_registration_generation
!= computation_inputs.custom_property_registration_generation;
if engine.custom_property_registrations_changed {
- engine.custom_property_environments.registrations_changed();
let previous_registry = engine.custom_property_registry.clone();
- engine.animation_effect_descriptions.registrations_changed(
- previous_registry
- .as_deref()
- .unwrap_or_else(|| CustomPropertyRegistry::shared_empty()),
- computation_inputs.custom_property_registry(),
- );
- }
- if engine.document_style_computation_inputs != computation_inputs {
- // Persistent records are derived from every document computation input, not only the
- // font generation carried in their keys. None reads a resource context, so a move of those
- // keeps them (`ReadsNoResourceContexts`).
- engine.engine_cold_record_cache.clear();
- engine.engine_cold_record_donors.clear();
- engine.engine_pseudo_record_cache.clear();
+ let previous_registry = previous_registry
+ .as_deref()
+ .unwrap_or_else(|| CustomPropertyRegistry::shared_empty());
+ engine
+ .animation_effect_descriptions
+ .registrations_changed(previous_registry, computation_inputs.custom_property_registry());
+ engine
+ .host
+ .program_staging
+ .note_registry_moved(previous_registry, computation_inputs.custom_property_registry());
}
// SAFETY: The inputs name the document's live registry, or none.
engine.custom_property_registry = unsafe {
@@ -3094,28 +1704,17 @@ pub(crate) unsafe fn take_style_transaction(
)
};
engine.document_style_computation_inputs = computation_inputs;
- let mut output = FfiStyleTransactionOutput::default();
- output.scoped = engine.take_style_transaction(root, |transaction_version, program_version, answers| {
- assert!(
- output.answers.is_empty(),
- "a style transaction emitted more than one batch"
- );
+ let mut output = FfiStyleUpdateOutput::default();
+ output.scoped = engine.run_style_update(root, |transaction_version, answers| {
+ assert!(output.answers.is_empty(), "a style update emitted more than one batch");
output.transaction_version = transaction_version.0;
- output.program_version = program_version.0;
output.answers.extend_from_slice(answers);
});
output.reclaimed_style_atoms = std::mem::take(&mut engine.host.reclaimed_style_atoms);
- output.only_derived_child_reactions = engine.take_only_derived_child_reactions();
- if let Some(beside_flown_transaction) = closes_beside {
- close_style_reactions_over_inheritance(engine, &mut output.answers, beside_flown_transaction);
- }
- // The host applies the rows in this order, so the transaction answers them in it.
- sort_style_deltas_for_direct_application(engine, &mut output.answers);
- output.connected_element_count = engine.connected_element_count();
output
}
-impl FfiStyleTransactionOutput {
+impl FfiStyleUpdateOutput {
/// The rows the transaction answered.
pub(crate) fn answers(&self) -> &[FfiStyleDelta] {
&self.answers
@@ -3125,163 +1724,6 @@ impl FfiStyleTransactionOutput {
pub(crate) fn reclaimed_style_atoms(&self) -> &[super::atoms::ReclaimedStyleAtom] {
&self.reclaimed_style_atoms
}
-
- /// The output as C++ reads it, for as long as the output stays where it is.
- pub(crate) fn view(&self) -> FfiStyleTransactionView {
- FfiStyleTransactionView {
- transaction_version: self.transaction_version,
- program_version: self.program_version,
- answers: self.answers.as_ptr(),
- count: self.answers.len(),
- scoped: self.scoped,
- only_derived_child_reactions: self.only_derived_child_reactions,
- connected_element_count: self.connected_element_count,
- }
- }
-}
-
-/// Closes `reactions` over the elements they inherit through, and answers whether that added rows, which then need
-/// ordering for application. While the host drains the transaction that flew, the elements it noted
-/// `beside_flown_transaction` are left to the next transaction.
-pub(super) fn close_style_reactions_over_inheritance(
- engine: &mut StyleEngine,
- reactions: &mut Vec<FfiStyleDelta>,
- beside_flown_transaction: &super::HashSet<StyleNodeID>,
-) -> bool {
- let InheritanceClosure {
- left_to_next_transaction,
- mut unstyled_ancestors,
- gaps,
- } = engine.close_over_inheritance(reactions, Some(beside_flown_transaction));
- if !left_to_next_transaction.is_empty() {
- reactions.retain(|reaction| !left_to_next_transaction.contains(&delta_node(reaction)));
- }
- if unstyled_ancestors.is_empty() && gaps.is_empty() {
- return false;
- }
- reactions.extend(
- unstyled_ancestors
- .iter()
- .map(|&element| FfiStyleDelta::unsettled(element, super::transaction::STYLE_REACTION_RECOMPUTE_STYLE)),
- );
- reactions.extend(gaps.iter().map(|&element| FfiStyleDelta::unsettled(element, 0)));
- unstyled_ancestors.extend(gaps);
- assert!(
- engine
- .complete_published_match_answers_for_closure(&unstyled_ancestors)
- .is_ok(),
- "the engine answers the elements a reaction batch closes over"
- );
- true
-}
-
-fn delta_node(delta: &FfiStyleDelta) -> StyleNodeID {
- StyleNodeID::from_raw(delta.style_node).expect("a style delta must name an element")
-}
-
-/// What a reaction batch closes over: an element without style that a reaction inherits from computes its style ahead
-/// of it, and a reaction whose ancestor reacts too keeps a row without a reaction of its own for each element in
-/// between, for the reactions the ancestor derives to reach it. Neither applies to a reaction the engine answered as
-/// hidden, which needs no style to inherit from.
-///
-/// The transaction that flew computed its reactions under the ancestors the elements had as it was sealed, so a
-/// reaction inheriting from an element without style that arrived beside it is the next transaction's, which styles
-/// it under that, and the elements an element that arrived, moved or retired beside it inherits through are not
-/// closed over.
-#[derive(Debug, Default, PartialEq)]
-pub(super) struct InheritanceClosure {
- pub(super) left_to_next_transaction: super::HashSet<StyleNodeID>,
- pub(super) unstyled_ancestors: Vec<StyleNodeID>,
- pub(super) gaps: Vec<StyleNodeID>,
-}
-
-impl super::RetainedState {
- pub(super) fn close_over_inheritance(
- &self,
- reactions: &[FfiStyleDelta],
- beside_flown_transaction: Option<&super::HashSet<StyleNodeID>>,
- ) -> InheritanceClosure {
- let is_beside_flown_transaction = |node| beside_flown_transaction.is_some_and(|beside| beside.contains(&node));
- let ancestors = |node| {
- std::iter::successors(self.tree.inheritance_parent(node), |&ancestor| {
- self.tree.inheritance_parent(ancestor)
- })
- };
- let reacting_elements = || {
- reactions
- .iter()
- .filter(|reaction| reaction.gap != FfiStyleDeltaGap::Hidden)
- .map(delta_node)
- .filter(|&reacting| !is_beside_flown_transaction(reacting))
- };
- let mut in_batch: super::HashSet<StyleNodeID> = reactions.iter().map(delta_node).collect();
- let mut closure = InheritanceClosure::default();
-
- for reacting in reacting_elements() {
- let start = closure.unstyled_ancestors.len();
- for ancestor in ancestors(reacting).take_while(|ancestor| !self.held_style_records.contains_key(ancestor)) {
- if is_beside_flown_transaction(ancestor) {
- for truncated in closure.unstyled_ancestors.drain(start..) {
- in_batch.remove(&truncated);
- }
- closure.left_to_next_transaction.insert(reacting);
- break;
- }
- if in_batch.insert(ancestor) {
- closure.unstyled_ancestors.push(ancestor);
- }
- }
- }
- for reacting in &closure.left_to_next_transaction {
- in_batch.remove(reacting);
- }
-
- let mut between = Vec::new();
- let kept = reacting_elements().filter(|reacting| !closure.left_to_next_transaction.contains(reacting));
- for reacting in kept.chain(closure.unstyled_ancestors.iter().copied()) {
- between.clear();
- for ancestor in ancestors(reacting) {
- if is_beside_flown_transaction(ancestor) {
- break;
- }
- if in_batch.contains(&ancestor) {
- closure
- .gaps
- .extend(between.iter().copied().filter(|&element| in_batch.insert(element)));
- break;
- }
- between.push(ancestor);
- }
- }
- closure
- }
-}
-
-/// Orders `deltas` for direct application in C++: each inheritance branch contiguously in preorder, an element's own
-/// delta ahead of the pseudo-element deltas settled beside it.
-pub(super) fn sort_style_deltas_for_direct_application(engine: &StyleEngine, deltas: &mut [FfiStyleDelta]) {
- let pseudo_rank = |delta: &FfiStyleDelta| {
- if delta.pseudo_kind == u8::MAX {
- 0
- } else {
- 1 + u16::from(delta.pseudo_kind)
- }
- };
- let node =
- |delta: &FfiStyleDelta| StyleNodeID::from_raw(delta.style_node).expect("a style delta must name an element");
- // Small batches cost less to compare directly. A large batch names its dependency order once instead of walking
- // both ancestor chains in every sort comparison.
- if engine.tree.style_reaction_order_ranks_pay_off(deltas.len()) {
- let ranks = engine.tree.style_reaction_order_ranks(deltas.iter().map(node));
- deltas.sort_unstable_by_key(|delta| (ranks[&node(delta)], pseudo_rank(delta)));
- return;
- }
- deltas.sort_unstable_by(|first, second| {
- engine
- .tree
- .compare_style_reaction_order(node(first), node(second))
- .then_with(|| pseudo_rank(first).cmp(&pseudo_rank(second)))
- });
}
pub(crate) unsafe fn borrow<'a, T>(pointer: *const T, count: usize) -> &'a [T] {
@@ -3295,9 +1737,17 @@ pub(crate) unsafe fn borrow<'a, T>(pointer: *const T, count: usize) -> &'a [T] {
#[cfg(test)]
mod tests {
use super::*;
- use crate::css::style::Lookup;
+ use crate::css::style::index::AttributeFact;
use crate::css::style::instrumentation::Counter;
- use crate::css::style::transaction::InputKind;
+ use crate::css::style::pipeline::projection::ElementChange;
+
+ fn arrived(engine: &StyleEngine, node: StyleNodeID) -> bool {
+ engine
+ .projection
+ .changes()
+ .iter()
+ .any(|&(changed, change)| changed == node && matches!(change, ElementChange::Relations(None, Some(_))))
+ }
fn no_relations() -> FfiTreeRelations {
FfiTreeRelations {
@@ -3349,21 +1799,16 @@ mod tests {
let root = StyleNodeID::from_raw(nodes[0]).unwrap();
let child = StyleNodeID::from_raw(nodes[1]).unwrap();
let grandchild = StyleNodeID::from_raw(nodes[2]).unwrap();
+
+ let transaction = engine.take_transaction();
assert_eq!(
- engine.tree().preorder(root).collect::<Vec<_>>(),
+ engine.projection.preorder(root).collect::<Vec<_>>(),
vec![root, child, grandchild]
);
-
- let transaction = engine.take_transaction();
- assert_eq!(transaction.inputs.len(), 2);
- assert!(transaction.inputs.iter().all(|input| matches!(
- input.key,
- InputKey::TreeRelations(node) | InputKey::LocalFeature(node, LocalFeatureKey::ArrivingFacts) if node == root
- )));
+ assert!(transaction.has_no_element_inputs());
+ assert!([root, child, grandchild].into_iter().all(|node| arrived(&engine, node)));
engine.release_transaction(transaction);
- assert_eq!(engine.counters().get(Counter::InitialBulkLoads), 1);
- assert_eq!(engine.counters().get(Counter::InitialBulkTreeRows), 3);
assert_eq!(engine.counters().get(Counter::RawMutationRecords), 3);
assert_eq!(engine.counters().get(Counter::TreeDeltas), 3);
@@ -3380,26 +1825,18 @@ mod tests {
}];
engine.apply_transaction_batch(&later_arrival, (&[], &[]), &[], &[], &[], &[]);
let transaction = engine.take_transaction();
- assert_eq!(transaction.inputs.len(), 3);
let later = StyleNodeID::from_raw(nodes[3]).unwrap();
- assert!(transaction.inputs.iter().any(|input| matches!(
- input.key,
- InputKey::TreeRelations(node) if node == child
- )));
assert_eq!(
- transaction
- .inputs
+ engine
+ .projection
+ .changes()
.iter()
- .filter(|input| matches!(
- input.key,
- InputKey::TreeRelations(node) | InputKey::LocalFeature(node, LocalFeatureKey::ArrivingFacts) if node == later
- ))
- .count(),
- 2
+ .map(|&(node, _)| node)
+ .collect::<Vec<_>>(),
+ vec![child, later]
);
+ assert!(arrived(&engine, later));
engine.release_transaction(transaction);
- assert_eq!(engine.counters().get(Counter::InitialBulkLoads), 1);
- assert_eq!(engine.counters().get(Counter::InitialBulkTreeRows), 3);
}
#[test]
@@ -3443,27 +1880,15 @@ mod tests {
let chunk_size = if split_batches { 1 } else { arrivals.len() };
for chunk in arrivals.chunks(chunk_size) {
engine.apply_transaction_batch(chunk, (&[], &[]), &[], &[], &[], &[]);
- // Applying the staged tree between batches must not lose a row's before side.
- engine.apply_staged_tree_deltas();
+ // Settling the tree between batches must not lose a row's before side.
+ engine.settle_tree_at_barrier();
}
let transaction = engine.take_transaction();
for raw in &nodes[1..] {
- let node = StyleNodeID::from_raw(*raw).unwrap();
- let input = transaction
- .inputs
- .iter()
- .find(|input| input.key == InputKey::TreeRelations(node))
- .unwrap();
- assert_eq!(input.old, InputValue::TreeRelations(None));
- assert!(
- transaction
- .inputs
- .iter()
- .any(|input| input.key == InputKey::LocalFeature(node, LocalFeatureKey::ArrivingFacts))
- );
+ assert!(arrived(&engine, StyleNodeID::from_raw(*raw).unwrap()));
}
assert_eq!(
- engine.tree().preorder(root).collect::<Vec<_>>(),
+ engine.projection.preorder(root).collect::<Vec<_>>(),
nodes.map(|raw| StyleNodeID::from_raw(raw).unwrap())
);
engine.release_transaction(transaction);
@@ -3472,7 +1897,7 @@ mod tests {
#[test]
fn element_arrival_rows_install_intrinsic_facts() {
- assert_eq!(size_of::<FfiElementArrival>(), 36);
+ assert_eq!(size_of::<FfiElementArrival>(), 64);
let mut engine = StyleEngine::new();
let mut nodes = [0_u32; 2];
engine.allocate_style_nodes(&mut nodes);
@@ -3498,61 +1923,82 @@ mod tests {
let arrivals = [
FfiElementArrival {
node: nodes[0],
+ tag_atom: 41,
+ folded_tag_atom: 42,
namespace_atom: 11,
language_atom: 12,
directionality_atom: 13,
- adjustment_facts: 0,
- construction_facts: 0,
- custom_state_offset: 0,
custom_state_count: 2,
+ class_count: 2,
+ attribute_count: 1,
heading_level: 4,
is_slot: true,
- associated_pseudo_kind_plus_one: 0,
- box_kind: 0,
+ states: 1 << StateFact::Checked as u32,
+ ..arrival_for(0, 0)
},
FfiElementArrival {
node: nodes[1],
+ tag_atom: 51,
+ folded_tag_atom: 51,
namespace_atom: 21,
language_atom: 22,
directionality_atom: 23,
- adjustment_facts: 0,
- construction_facts: 0,
- custom_state_offset: 2,
custom_state_count: 1,
- heading_level: 0,
- is_slot: false,
- associated_pseudo_kind_plus_one: 0,
- box_kind: 0,
+ has_text_content: true,
+ ..arrival_for(0, 0)
},
];
- engine.apply_transaction_batch(&tree, (&arrivals, &[31, 32, 33]), &[], &[], &[], &[]);
+ engine.apply_transaction_batch(&tree, (&arrivals, &[31, 32, 62, 61, 71, 72, 33]), &[], &[], &[], &[]);
let transaction = engine.take_transaction();
let root = StyleNodeID::from_raw(nodes[0]).unwrap();
let child = StyleNodeID::from_raw(nodes[1]).unwrap();
- assert_eq!(engine.facts.namespace_of(root), StyleAtomID(11));
- assert_eq!(engine.facts.language_of(root), StyleAtomID(12));
- assert_eq!(engine.facts.directionality_of(root), StyleAtomID(13));
- assert_eq!(engine.facts.heading_level_of(root), 4);
- assert!(engine.facts.is_slot(root));
- assert_eq!(engine.facts.custom_states_of(root), &[StyleAtomID(31), StyleAtomID(32)]);
- assert_eq!(engine.facts.namespace_of(child), StyleAtomID(21));
- assert_eq!(engine.facts.custom_states_of(child), &[StyleAtomID(33)]);
+ let root_facts = engine.projection.facts(root).unwrap();
+ assert_eq!(root_facts.namespace(), StyleAtomID(11));
+ assert_eq!(root_facts.language(), StyleAtomID(12));
+ assert_eq!(root_facts.directionality(), StyleAtomID(13));
+ assert_eq!(root_facts.heading_level(), 4);
+ assert!(root_facts.is_slot());
+ assert_eq!(root_facts.custom_states(), &[StyleAtomID(31), StyleAtomID(32)]);
+ assert_eq!(root_facts.tag(), StyleAtomID(41));
+ assert_eq!(root_facts.folded_tag(), StyleAtomID(42));
+ assert_eq!(root_facts.classes(), &[StyleAtomID(61), StyleAtomID(62)]);
+ assert_eq!(
+ root_facts.attributes(),
+ &[AttributeFact {
+ name: StyleAtomID(71),
+ value: StyleAtomID(72),
+ }]
+ );
+ assert!(root_facts.states().contains(StateFact::Checked));
+ assert!(!root_facts.has_text_content());
+ let child_facts = engine.projection.facts(child).unwrap();
+ assert_eq!(child_facts.namespace(), StyleAtomID(21));
+ assert_eq!(child_facts.custom_states(), &[StyleAtomID(33)]);
+ assert_eq!(child_facts.folded_tag(), StyleAtomID::NONE);
+ assert!(child_facts.classes().is_empty());
+ assert!(child_facts.has_text_content());
engine.release_transaction(transaction);
}
- fn arrival_for(node: u32, custom_state_offset: u32, custom_state_count: u32) -> FfiElementArrival {
+ fn arrival_for(node: u32, custom_state_count: u32) -> FfiElementArrival {
FfiElementArrival {
+ states: 0,
node,
+ tag_atom: 4,
+ folded_tag_atom: 4,
+ id_atom: 0,
namespace_atom: 1,
language_atom: 2,
directionality_atom: 3,
+ custom_state_count,
+ class_count: 0,
+ attribute_count: 0,
adjustment_facts: 0,
construction_facts: 0,
- custom_state_offset,
- custom_state_count,
heading_level: 0,
is_slot: false,
+ has_text_content: false,
associated_pseudo_kind_plus_one: 0,
box_kind: 0,
}
@@ -3562,127 +2008,20 @@ mod tests {
#[should_panic(expected = "an element arrival named an invalid style node")]
fn malformed_element_arrival_rejects_an_invalid_node() {
let mut engine = StyleEngine::new();
- engine.apply_transaction_batch(&[], (&[arrival_for(0, 0, 0)], &[]), &[], &[], &[], &[]);
+ engine.apply_transaction_batch(&[], (&[arrival_for(0, 0)], &[]), &[], &[], &[], &[]);
}
#[test]
- #[should_panic(expected = "an element arrival custom-state range overflowed")]
- fn malformed_element_arrival_rejects_an_overflowing_custom_state_range() {
+ #[should_panic(expected = "an element arrival named atoms outside the shared atom column")]
+ fn malformed_element_arrival_rejects_an_out_of_bounds_atom_range() {
let mut engine = StyleEngine::new();
let mut nodes = [0];
engine.allocate_style_nodes(&mut nodes);
- engine.apply_transaction_batch(&[], (&[arrival_for(nodes[0], u32::MAX, 1)], &[]), &[], &[], &[], &[]);
- }
-
- #[test]
- #[should_panic(expected = "an element arrival named custom states outside the shared atom column")]
- fn malformed_element_arrival_rejects_an_out_of_bounds_custom_state_range() {
- let mut engine = StyleEngine::new();
- let mut nodes = [0];
- engine.allocate_style_nodes(&mut nodes);
- engine.apply_transaction_batch(&[], (&[arrival_for(nodes[0], 0, 2)], &[1]), &[], &[], &[], &[]);
- }
-
- #[test]
- fn initial_tree_bulk_load_publishes_match_answers_before_traversal() {
- let mut engine = StyleEngine::new();
- let mut nodes = [0_u32; 3];
- engine.allocate_style_nodes(&mut nodes);
- let initial_tree = [
- FfiTreeDelta {
- node: nodes[0],
- old_connected: false,
- new_connected: true,
- old_relations: no_relations(),
- new_relations: no_relations(),
- },
- FfiTreeDelta {
- node: nodes[1],
- old_connected: false,
- new_connected: true,
- old_relations: no_relations(),
- new_relations: FfiTreeRelations {
- parent: nodes[0],
- ..no_relations()
- },
- },
- FfiTreeDelta {
- node: nodes[2],
- old_connected: false,
- new_connected: true,
- old_relations: no_relations(),
- new_relations: FfiTreeRelations {
- parent: nodes[1],
- ..no_relations()
- },
- },
- ];
- let initial_features = nodes.map(|node| FfiLocalFeatureDelta {
- node,
- feature_kind: FfiFeatureKind::TagName,
- name_atom: 0,
- old_kind: FfiFeatureValueKind::Absent,
- old_atom: 0,
- new_kind: FfiFeatureValueKind::Atom,
- new_atom: 1,
- });
- engine.apply_transaction_batch(&initial_tree, (&[], &[]), &initial_features, &[], &[], &[]);
-
- let root = StyleNodeID::from_raw(nodes[0]).unwrap();
- let mut published = Vec::new();
- let mut emission_count = 0;
- // The engine of a test computes no records, so each row waits for the host to install the
- // one above it, in a wave of its own.
- for _ in 0..nodes.len() {
- assert!(!engine.take_style_transaction(root, |_, _, answers| {
- emission_count += 1;
- published.extend_from_slice(answers);
- }));
- }
- assert!(!engine.has_pending_transaction());
- assert_eq!(emission_count, 3);
- assert_eq!(
- published.iter().map(|delta| delta.style_node).collect::<Vec<_>>(),
- nodes
- );
- assert!(published.iter().all(|delta| {
- delta.pseudo_kind == u8::MAX
- && delta.old_style_record == 0
- && delta.new_style_record == 0
- && delta.damage == FfiStyleDeltaDamage::None
- }));
- assert_eq!(
- published.iter().map(|delta| delta.gap).collect::<Vec<_>>(),
- [FfiStyleDeltaGap::Materialize; 3]
- );
- assert_eq!(engine.counters().get(Counter::InitialBulkMatchLoads), 1);
- assert_eq!(engine.counters().get(Counter::InitialBulkMatchRows), 3);
- assert_eq!(engine.counters().get(Counter::PublishedMatchAnswerRecords), 3);
- assert_eq!(engine.counters().get(Counter::PreparedMatchingBatchRowsCloned), 3);
-
- let upqueries = engine.counters().get(Counter::MatchAnswerUpqueries);
- assert!(engine.begin_cold_matching_batch(root));
- for raw in nodes[..2].iter().copied() {
- let node = StyleNodeID::from_raw(raw).unwrap();
- assert_eq!(engine.consume_published_match_answer(node), Some(Vec::new()));
- }
- engine.end_cold_matching_batch();
- assert!(matches!(
- engine.retained_match_answer(StyleNodeID::from_raw(nodes[0]).unwrap()),
- Lookup::Known(_)
- ));
- // An answer nothing consumed stays retained for the node's first read.
- assert!(matches!(
- engine.retained_match_answer(StyleNodeID::from_raw(nodes[2]).unwrap()),
- Lookup::Known(_)
- ));
- assert_eq!(engine.counters().get(Counter::MatchAnswerUpqueries), upqueries);
- assert_eq!(
- engine
- .counters()
- .get(Counter::MatchElementCallsDuringPublishedStyleTransaction),
- 0
- );
+ let arrival = FfiElementArrival {
+ attribute_count: 1,
+ ..arrival_for(nodes[0], 0)
+ };
+ engine.apply_transaction_batch(&[], (&[arrival], &[1]), &[], &[], &[], &[]);
}
#[test]
@@ -3732,8 +2071,6 @@ mod tests {
node: nodes[1],
feature_kind: FfiFeatureKind::Class,
name_atom: 42,
- old_kind: FfiFeatureValueKind::Absent,
- old_atom: 0,
new_kind: FfiFeatureValueKind::Present,
new_atom: 0,
}];
@@ -3751,7 +2088,7 @@ mod tests {
let style_inputs = [FfiElementStyleInput {
style_node: nodes[1],
- reaction: crate::css::style::transaction::STYLE_REACTION_RECOMPUTE_STYLE,
+ reaction: crate::css::style::input_types::STYLE_REACTION_RECOMPUTE_STYLE,
inherited_style_groups: 0,
}];
engine.apply_transaction_batch(&tree, (&[], &[]), &features, &states, &declarations, &style_inputs);
@@ -3760,13 +2097,35 @@ mod tests {
let node0 = StyleNodeID::from_raw(nodes[0]).unwrap();
let node1 = StyleNodeID::from_raw(nodes[1]).unwrap();
let node2 = StyleNodeID::from_raw(nodes[2]).unwrap();
- assert_eq!(engine.tree().children(node0).collect::<Vec<_>>(), vec![node1, node2]);
- let kinds: Vec<InputKind> = transaction.inputs.iter().map(|input| input.key.kind()).collect();
- assert!(kinds.contains(&InputKind::TreeRelations));
- assert!(kinds.contains(&InputKind::LocalFeature));
- assert!(kinds.contains(&InputKind::State));
- assert!(kinds.contains(&InputKind::ElementDeclaration));
- assert!(kinds.contains(&InputKind::ElementStyleInput));
+ assert_eq!(
+ engine.projection.children(node0).collect::<Vec<_>>(),
+ vec![node1, node2]
+ );
+ let changes = engine.projection.changes();
+ assert!(
+ changes
+ .iter()
+ .any(|(_, change)| matches!(change, ElementChange::Relations(..)))
+ );
+ assert!(
+ changes
+ .iter()
+ .any(|(_, change)| matches!(change, ElementChange::Feature(_) | ElementChange::ArrivingFacts))
+ );
+ assert!(
+ changes
+ .iter()
+ .any(|(_, change)| matches!(change, ElementChange::State(_) | ElementChange::ArrivingFacts))
+ );
+ assert_eq!(transaction.declarations, vec![node1]);
+ assert_eq!(
+ transaction
+ .style_inputs
+ .iter()
+ .map(|&(node, _)| node)
+ .collect::<Vec<_>>(),
+ vec![node1]
+ );
engine.release_transaction(transaction);
assert_eq!(engine.counters().get(Counter::TreeDeltas), 4);
diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge/container_effects.rs b/Libraries/LibWeb/Rust/src/css/style/bridge/container_effects.rs
new file mode 100644
index 00000000000..360206908a6
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/bridge/container_effects.rs
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::*;
+
+/// What a container condition the engine evaluated read of a container or its subject, which the
+/// host records as it records its own evaluation's.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum FfiContainerEffectKind {
+ /// The node is a container a size or scroll-state query asks about.
+ SizeContainerUsage,
+ /// The node is a container a style query asks about.
+ StyleContainerUsage,
+ /// The node is a scroll-state container a query asks about, whose state is snapshotted.
+ ScrollStateContainerUsage,
+ /// The node has no box yet, and the query is evaluated again after layout.
+ NeedsEvaluationAfterLayout,
+ /// The subject's style resolved a viewport-relative length in the query.
+ SubjectViewportDependency,
+ /// A container-relative length resolved against the node, which has no box yet, and is
+ /// resolved again after layout, a partial relayout included.
+ UnitsNeedEvaluationAfterLayout,
+}
+
+#[derive(Clone, Copy)]
+#[repr(C)]
+pub struct FfiContainerEffect {
+ pub node: u32,
+ pub kind: FfiContainerEffectKind,
+}
+
+/// What the container conditions of a row the engine answered read of its containers, besides the
+/// effects: whether the row's style depends on a size or scroll-state query or a style query.
+#[repr(C)]
+pub struct FfiContainerEffects {
+ pub depends_on_size: bool,
+ pub depends_on_style: bool,
+}
+
+/// Takes what the container conditions of the row the host is installing for `node` read of its
+/// containers, for the host to record as it records its own evaluation's. Each effect is handed to
+/// `record` with no engine borrow held, so recording may call the engine.
+///
+/// # Safety
+/// `host` must be a live document host, on its document's thread.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_take_container_effects(
+ host: &DocumentHost,
+ read: &crate::render_state::BegunRead,
+ node: u32,
+ context: *mut c_void,
+ record: unsafe extern "C" fn(*mut c_void, FfiContainerEffect),
+) -> FfiContainerEffects {
+ let verdict = StyleNodeID::from_raw(node)
+ .filter(|_| host.container_effects_may_be_held())
+ .and_then(|node| with_engine(read, host, |engine| engine.take_container_effects_for_install(node)))
+ .unwrap_or_default();
+ for &(node, kind) in &verdict.effects {
+ unsafe { record(context, FfiContainerEffect { node: node.raw(), kind }) };
+ }
+ FfiContainerEffects {
+ depends_on_size: verdict.depends_on_size,
+ depends_on_style: verdict.depends_on_style,
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge/native_rules.rs b/Libraries/LibWeb/Rust/src/css/style/bridge/native_rules.rs
new file mode 100644
index 00000000000..a262b494bfd
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/bridge/native_rules.rs
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::*;
+
+#[repr(C)]
+pub struct FfiNativeRuleTarget {
+ pub identity: u64,
+ pub declaration_version: u32,
+ pub source_identity: u64,
+ pub declarations: *const c_void,
+ pub layer_name: *const u16,
+ pub layer_name_length: usize,
+ pub has_container_conditions: bool,
+ pub origin: FfiCascadeOrigin,
+}
+
+/// Issue a new identity for changed declaration contents, independently of CSSOM wrappers.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_next_declaration_block_version(host: &DocumentHost) -> u32 {
+ host.next_declaration_block_version()
+}
+
+/// Queues a native declaration edit for the rule that owns the declarations, where the host published that rule to the
+/// sheet `sheet`, and answers whether they declare transitions. The host is told first, with no engine borrowed.
+///
+/// # Safety
+/// The callback must not mutate the native rule graph, and must remain valid for this call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_native_rule_declarations_changed(
+ host: &DocumentHost,
+ sheet: u32,
+ rule: &crate::css::rule::NativeRule,
+ context: *mut c_void,
+ notify: unsafe extern "C" fn(*mut c_void),
+) -> bool {
+ let Some(identity) = rule
+ .declaration_owner_identity()
+ .filter(|&identity| host.published_rules().contains(sheet, identity))
+ else {
+ return false;
+ };
+ // SAFETY: Guaranteed by the caller.
+ unsafe { notify(context) };
+ let declarations = rule.cascade_declarations();
+ let transitions = declarations
+ .as_ref()
+ .is_some_and(|declarations| declares_transitions(declarations.properties()));
+ host.write_rules(RuleWrite::RuleDeclarations { identity, declarations });
+ transitions
+}
+
+/// The native identity of the first rule after an inserted native subtree that the host published to the sheet
+/// `sheet`, or 0 for none, without creating CSSOM objects.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_native_rule_successor(
+ host: &DocumentHost,
+ sheet: u32,
+ native: &crate::css::style_sheet::NativeStyleSheet,
+ identity: u64,
+) -> u64 {
+ host.published_rules().successor(sheet, native, identity)
+}
+
+/// Retires a native subtree from the sheet `sheet`, with host callbacks only for document and cascade-cache
+/// notifications, and queues the removal of the rules the host published there.
+///
+/// # Safety
+/// `host` must be a live document host, on its document's thread, and the native sheet, rule, callbacks, and any
+/// non-null detached import must be live. Native rules must belong to Rc allocations. No graph borrow spans a host
+/// callback.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_remove_native_rule(
+ host: &DocumentHost,
+ native: *const c_void,
+ rule: *const c_void,
+ detached_import: *const c_void,
+ sheet: u32,
+ context: *mut c_void,
+ begin: unsafe extern "C" fn(*mut c_void, bool, bool),
+ notify: unsafe extern "C" fn(*mut c_void, bool),
+) {
+ use crate::css::rule::{NativeRule, NativeRuleType, mutation, read::RuleRef};
+ use crate::css::style_sheet::NativeStyleSheet;
+ // SAFETY: Guaranteed by the caller.
+ let removed = unsafe {
+ mutation::removed_rules(
+ &*rule.cast::<NativeRule>(),
+ &*native.cast::<NativeStyleSheet>(),
+ detached_import.cast::<NativeStyleSheet>().as_ref(),
+ )
+ };
+ let changes_environment =
+ RuleRef::Materialized(unsafe { &*rule.cast::<NativeRule>() }).change_needs_style_environment_bump();
+ let has_counter_style = removed
+ .iter()
+ .any(|rule| RuleRef::Materialized(rule).rule_type() == NativeRuleType::CounterStyle);
+ unsafe { begin(context, changes_environment, has_counter_style) };
+ let mut published = Vec::new();
+ for rule in removed {
+ unsafe { notify(context, mutation::declares_layer(&rule)) };
+ let identity = RuleRef::Materialized(&rule).identity();
+ if host.published_rules().remove(sheet, identity) {
+ published.push(identity);
+ }
+ }
+ if !published.is_empty() {
+ host.write_rules(RuleWrite::RemoveRules(published.into()));
+ }
+}
+
+/// Read a rule's native cascade data without a CSSOM facade.
+///
+/// On success the caller owns declarations and must release it with
+/// rust_declaration_data_release. Layer text is borrowed until the next rule mutation; callers must
+/// copy any text needed across such a mutation. Source identity never retains a native sheet.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_native_rule_target(
+ host: &DocumentHost,
+ read: &crate::render_state::BegunRead,
+ rule: u32,
+ result: &mut FfiNativeRuleTarget,
+) -> bool {
+ with_engine(read, host, |engine| native_rule_target(engine, rule, result))
+}
+
+/// [`style_engine_native_rule_target`] on `engine`.
+pub fn native_rule_target(engine: &mut StyleEngine, rule: u32, result: &mut FfiNativeRuleTarget) -> bool {
+ let Some(target) = rule
+ .checked_sub(1)
+ .and_then(|id| engine.rules.native_target(RuleID(id)))
+ else {
+ return false;
+ };
+ let Some(declarations) = engine.current_rule_block(RuleID(rule - 1)) else {
+ return false;
+ };
+ let origin = engine.rules.sheet_origin(engine.rules.rule_sheet(RuleID(rule - 1)));
+ *result = FfiNativeRuleTarget {
+ identity: target.identity.get(),
+ declaration_version: engine
+ .current_rule_version(RuleID(rule - 1))
+ .declaration_block
+ .map_or(0, |version| version.raw()),
+ source_identity: target.source_identity,
+ declarations: crate::css::declaration_block::SharedDeclarationBlock::into_raw(declarations).cast(),
+ layer_name: target.layer_name().as_ptr(),
+ layer_name_length: target.layer_name().len(),
+ has_container_conditions: !target.containers().is_empty(),
+ origin: match origin {
+ CascadeOrigin::Author => FfiCascadeOrigin::Author,
+ CascadeOrigin::AuthorPresentationalHint => FfiCascadeOrigin::AuthorPresentationalHint,
+ CascadeOrigin::User => FfiCascadeOrigin::User,
+ CascadeOrigin::UserAgent => FfiCascadeOrigin::UserAgent,
+ },
+ };
+ true
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge/records.rs b/Libraries/LibWeb/Rust/src/css/style/bridge/records.rs
new file mode 100644
index 00000000000..7fa9b040026
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/bridge/records.rs
@@ -0,0 +1,386 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::*;
+
+/// The record the host holds for a base or live animation-overlay record, which the engine holds while it holds the
+/// identity, or null for an identity it does not hold. The host counts a reference to it to hold it longer.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_host_record(
+ host: &DocumentHost,
+ read: &crate::render_state::BegunRead,
+ style_record: u64,
+) -> *const c_void {
+ if let Some(record) = crate::css::style::engine_calls::known_host_record(host, style_record) {
+ return record;
+ }
+ let record = with_engine(read, host, |engine| host_record(engine, style_record));
+ if !record.is_null() {
+ host.engine_memo().views.set(style_record, record);
+ }
+ record
+}
+
+/// The record `engine` holds for the host for `style_record`, or null.
+pub(in crate::css::style) fn host_record(engine: &StyleEngine, style_record: u64) -> *const c_void {
+ engine
+ .computed_group_sets
+ .host_record(style_record)
+ .map_or(std::ptr::null(), |record| std::sync::Arc::as_ptr(record).cast())
+}
+
+/// The groups beneath the animation overlay of the record `view` views, which are its own groups
+/// where it carries none, or null where the view is missing.
+///
+/// # Safety
+/// `view` must be a view of a record the host holds live.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_view_base_groups(view: &FfiStyleRecordView) -> *const c_void {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { view.base_groups() }.map_or(std::ptr::null(), |groups| std::ptr::from_ref(groups).cast())
+}
+
+/// Whether the element of the record `view` views would compute `display` to `none` when ignoring its animations:
+/// those composed over the record, and the custom properties they sampled, which the record substitutes.
+///
+/// # Safety
+/// `view` must be a view of a record the host holds live.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_view_display_is_none_ignoring_animations(view: &FfiStyleRecordView) -> bool {
+ // SAFETY: Guaranteed by the caller.
+ let Some(groups) = (unsafe { view.base_groups() }) else {
+ return false;
+ };
+ // SAFETY: Guaranteed by the caller.
+ let display_none_is_animated = unsafe {
+ view.longhand_table_record
+ .cast::<crate::css::style::pipeline::Record>()
+ .as_ref()
+ }
+ .is_some_and(|record| record.rare().reads.display_none_is_animated);
+ crate::css::computed_value_views::ComputedValuesView::of(groups)
+ .display()
+ .is_none()
+ && !display_none_is_animated
+}
+
+/// The view of `record`, a record the host holds, which reads nothing but the record.
+///
+/// # Safety
+/// `record` must be a record the caller holds a reference to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_record_view(record: *const c_void) -> FfiStyleRecordView {
+ // SAFETY: Guaranteed by the caller.
+ FfiStyleRecordView::of_record(unsafe { &*record.cast::<crate::css::style::pipeline::Record>() })
+}
+
+/// The identity the engine names `record`, a record the host holds, by: that of the slot holding
+/// it, or of the sample it is, or zero for a record no slot holds any longer.
+///
+/// # Safety
+/// As for [`style_engine_record_view`].
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_record_identity(record: *const c_void) -> u64 {
+ // SAFETY: Guaranteed by the caller.
+ host_record_identity(unsafe { &*record.cast::<crate::css::style::pipeline::Record>() })
+}
+
+/// The identity the engine names `record`, a record the host holds, by, as
+/// [`style_engine_record_identity`] answers it.
+pub(in crate::css::style) fn host_record_identity(record: &crate::css::style::pipeline::Record) -> u64 {
+ match record.sample_of_animations() {
+ Some(sample) => sample.identity.raw(),
+ None => record.installed_record().map_or(0, |installed| {
+ crate::css::style::computed::FinalStyleRecordID::installed(installed).raw()
+ }),
+ }
+}
+
+/// The identity of the custom-property environment `record`, a record the host holds, was
+/// resolved in: that of the store it holds, or of the store of the record a sample samples over.
+///
+/// # Safety
+/// As for [`style_engine_record_view`].
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_record_custom_property_environment(record: *const c_void) -> u64 {
+ // SAFETY: Guaranteed by the caller.
+ let record = unsafe { &*record.cast::<crate::css::style::pipeline::Record>() };
+ record
+ .sample_of_animations()
+ .map_or(record, |sample| &sample.base)
+ .custom_property_environment()
+}
+
+/// Takes one more reference to `record`, a style record a view named.
+///
+/// # Safety
+/// `record` must be the `longhand_table_record` of a view of a record the host holds live, or one
+/// the caller holds a reference to.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_record_retain(record: *const c_void) {
+ // SAFETY: Guaranteed by the caller: the record lives in an Arc.
+ unsafe { std::sync::Arc::increment_strong_count(record.cast::<crate::css::style::pipeline::Record>()) };
+}
+
+/// A reference of the engine's own to `record`, a record the host holds, or none for null.
+///
+/// # Safety
+/// `record` must be null or a record the host holds a reference to.
+pub(crate) unsafe fn retain_host_record(
+ record: *const c_void,
+) -> Option<std::sync::Arc<crate::css::style::pipeline::Record>> {
+ let record = record.cast::<crate::css::style::pipeline::Record>();
+ // SAFETY: Guaranteed by the caller: the record lives in an Arc.
+ (!record.is_null()).then(|| unsafe {
+ std::sync::Arc::increment_strong_count(record);
+ std::sync::Arc::from_raw(record)
+ })
+}
+
+/// Lets go of a reference taken with `style_engine_record_retain`.
+///
+/// # Safety
+/// `record` must be a record the caller took a reference to with `style_engine_record_retain`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_record_release(record: *const c_void) {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { std::sync::Arc::decrement_strong_count(record.cast::<crate::css::style::pipeline::Record>()) };
+}
+
+/// Whether the `transition-*` values of the record `view` views give any longhand a matching
+/// entry, as [`crate::css::transition::has_matching_transition_entries`] says.
+///
+/// # Safety
+/// `view` must be a view of a live record.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_view_has_matching_transition_entries(
+ view: &FfiStyleRecordView,
+ has_existing_transitions: bool,
+) -> bool {
+ // SAFETY: Guaranteed by the caller.
+ unsafe { view.longhands() }.is_some_and(|longhands| {
+ crate::css::transition::has_matching_transition_entries(longhands, has_existing_transitions)
+ })
+}
+
+pub(crate) fn publish_rule_declarations(
+ engine: &mut StyleEngine,
+ rule: u32,
+ data: &crate::css::declaration_block::SharedDeclarationBlock,
+) -> bool {
+ if rule == 0 {
+ return false;
+ }
+ let has_transitions = data
+ .properties()
+ .entries()
+ .iter()
+ .any(|entry| crate::css::property_metadata::property_defines_a_css_transition(entry.property()));
+ engine.publish_block_declarations(RuleID(rule - 1), data);
+ has_transitions
+}
+
+/// What a read of one element's style the host makes before the next style update asks of the
+/// engine; see `StyleEngine::answer_record_demand`. A read-only demand leaves the engine as it
+/// was: its record is only for the host to read. Any other is installed and acknowledged as a
+/// style update's would be.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+#[expect(dead_code, reason = "C++ constructs the variants")]
+#[expect(clippy::enum_variant_names, reason = "each is a read of the element")]
+pub enum FfiRecordDemand {
+ /// A read-only read of the element's record.
+ ElementRead,
+ /// A read-only read of what the element computes to as though it had no inline declaration,
+ /// driven in full against the parent as it is now.
+ ElementReadWithoutInlineStyle,
+ /// A read-only read of the element's record, driven in full against the parent as it is now,
+ /// which the reader assigned a record of its own.
+ ElementReadAgainstParent,
+}
+
+/// What a read of one of an element's pseudo-elements the host makes before the next style update
+/// asks of the engine, as `FfiRecordDemand` does of an element.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+#[expect(dead_code, reason = "C++ constructs the variants")]
+pub enum FfiPseudoElementRecordDemand {
+ /// A CSSOM read of the pseudo-element, settled against its element's installed record.
+ CssomRead,
+ /// A read-only read of what the pseudo-element computes to, whether or not it generates a box.
+ ReadOnly,
+}
+
+/// A pseudo-element a record demand may read: a synthetic one, which the engine settles beside its
+/// element, or, for a read-only read, one an element in the shadow tree backs or a named view
+/// transition one, which it computes from the element's rules for it. Each is numbered as its kind.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+#[expect(dead_code, reason = "C++ constructs the variants")]
+pub enum FfiDemandedPseudoElement {
+ After = 0,
+ Backdrop = 1,
+ Before = 2,
+ FirstLetter = 3,
+ FirstLine = 4,
+ Marker = 5,
+ SearchText = 6,
+ SearchTextCurrent = 7,
+ Selection = 8,
+ SpellingError = 9,
+ ViewTransition = 10,
+ DetailsContent = 11,
+ FileSelectorButton = 12,
+ Placeholder = 13,
+ SliderFill = 14,
+ SliderThumb = 15,
+ SliderTrack = 16,
+ ViewTransitionGroup = 20,
+ ViewTransitionImagePair = 21,
+ ViewTransitionNew = 22,
+ ViewTransitionOld = 23,
+}
+
+/// The answer to a record demand: the record, or that the pseudo-element read generates no box
+/// with the custom-property environment its rules resolve to (zero where none styles it). A zero
+/// `style_record` that is not absent leaves the read to C++.
+#[derive(Clone, Copy, Debug, Default)]
+#[repr(C)]
+pub struct FfiRecordDemandAnswer {
+ pub record: FfiEngineComputedRecord,
+ pub is_absent: bool,
+ pub custom_property_environment: u64,
+}
+
+/// Answer a read of one element's style, or one of its pseudo-elements', the host makes before
+/// the next style update.
+pub(crate) fn answer_record_demand(
+ engine: &mut StyleEngine,
+ style_node: StyleNodeID,
+ demand: crate::css::style::publication::RecordDemand,
+) -> FfiRecordDemandAnswer {
+ let answer = engine.answer_record_demand(style_node, demand);
+ ffi_record_demand_answer(engine, answer)
+}
+
+/// The FFI form of `answer`, what a demand of an element's record answered, with the records
+/// `engine` holds for the host for the records it names.
+pub(in crate::css::style) fn ffi_record_demand_answer(
+ engine: &StyleEngine,
+ answer: crate::css::style::publication::RecordDemandAnswer,
+) -> FfiRecordDemandAnswer {
+ match answer {
+ crate::css::style::publication::RecordDemandAnswer::Record { record } => FfiRecordDemandAnswer {
+ record: FfiEngineComputedRecord {
+ style_record: record.style_record,
+ host_record: host_record(engine, record.style_record),
+ },
+ is_absent: false,
+ custom_property_environment: 0,
+ },
+ crate::css::style::publication::RecordDemandAnswer::Absent {
+ custom_property_environment,
+ } => FfiRecordDemandAnswer {
+ record: FfiEngineComputedRecord::default(),
+ is_absent: true,
+ custom_property_environment,
+ },
+ }
+}
+
+/// The record of an element no rule reaches, computed from its presentational hints and its
+/// inline style alone over the initial values, its custom properties among them; see
+/// `declared_only_record`. `subject` is the document's style node. Returns the record with a
+/// reference the host takes over, or null where the engine computes none.
+///
+/// # Safety
+/// `host` must be a live document host, on its document's thread. `hints` must borrow `hint_count`
+/// `FfiDeclaredProperty` entries whose values point at live, Arc-backed `StyleValueData` roots. A
+/// non-null `inline_block` must borrow a live `DeclarationBlock`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_declared_only_record(
+ host: &DocumentHost,
+ read: &crate::render_state::BegunRead,
+ subject: u32,
+ facts: u32,
+ hint_kind: FfiElementDeclarationKind,
+ hints: *const c_void,
+ hint_count: usize,
+ inline_block: *const c_void,
+) -> *const c_void {
+ // SAFETY: Guaranteed by the caller.
+ let record = with_engine(read, host, |engine| {
+ use crate::css::declaration_block::{DeclarationBlock, FfiDeclaredProperty, declaration_from_view};
+ abort_on_panic(|| {
+ let subject = StyleNodeID::from_raw(subject)?;
+ let hints = if hint_count == 0 {
+ &[]
+ } else {
+ unsafe { ak::slice_from_raw_parts(hints.cast::<FfiDeclaredProperty>(), hint_count) }
+ };
+ let hints = hints
+ .iter()
+ .map(|hint| unsafe { declaration_from_view(hint) })
+ .collect::<Vec<_>>();
+ let inline_data = unsafe { inline_block.cast::<DeclarationBlock>().as_ref() }.map(DeclarationBlock::data);
+ let hint_kind = decode_element_declaration_kind(hint_kind);
+ let mut by_kind: [Vec<_>; ElementDeclarationKind::COUNT] = Default::default();
+ by_kind[hint_kind.index()] = crate::css::style::specified_value::element_declared_properties(
+ hints
+ .iter()
+ .map(crate::css::declaration_block::DeclaredProperty::borrowed),
+ );
+ if let Some(data) = &inline_data {
+ by_kind[ElementDeclarationKind::InlineStyle.index()] =
+ crate::css::style::specified_value::element_declared_properties(data.properties().iter());
+ }
+ let custom_declarations = collect_native_custom_declarations(
+ engine,
+ inline_data
+ .as_ref()
+ .map_or(Default::default(), |data| data.custom_properties()),
+ );
+ let declared = crate::css::style::pipeline::DeclaredOnly {
+ declarations: crate::css::style::element_declarations::ElementDeclarationRow::new(
+ by_kind,
+ custom_declarations,
+ ),
+ // An element outside the document is no document element.
+ facts: facts & !element_adjustment_fact::IS_DOCUMENT_ELEMENT,
+ };
+ // FIXME: A shape in a window whose document has no document element has a path and should measure, but an
+ // engine owns its document from its first style update with a document element, so no initial
+ // style exists yet to compute the record over.
+ if !engine.has_live_style() {
+ return None;
+ }
+ engine.declared_only_record(subject, declared).ok()
+ })
+ });
+ record.map_or(std::ptr::null(), |record| std::sync::Arc::into_raw(record).cast())
+}
+
+/// The store of an environment the engine resolved, with one strong reference transferred to the
+/// caller, and the environment it was resolved over; null for an environment C++ published.
+///
+/// # Safety
+/// `host` must be a live document host, on its document's thread, and `parent` must be writable.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_borrow_engine_custom_property_environment(
+ host: &DocumentHost,
+ read: &crate::render_state::BegunRead,
+ identity: u64,
+ parent: *mut u64,
+) -> *const c_void {
+ // SAFETY: Guaranteed by the caller.
+ with_engine(read, host, |engine| {
+ let Some((store, parent_identity)) = engine.custom_property_environments.engine_environment(identity) else {
+ return std::ptr::null();
+ };
+ unsafe { *parent = parent_identity };
+ std::sync::Arc::into_raw(std::sync::Arc::clone(store)).cast()
+ })
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/computed.rs b/Libraries/LibWeb/Rust/src/css/style/computed.rs
index fac514b0724..4945d97f881 100644
--- a/Libraries/LibWeb/Rust/src/css/style/computed.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/computed.rs
@@ -330,6 +330,12 @@ impl<'a> ViewLonghands<'a> {
self.0.facts().declares_transitions()
}
+ /// Whether `display` computed to `none` only through the custom properties the element's
+ /// animations sampled.
+ pub(crate) fn display_none_is_animated(self) -> bool {
+ self.0.rare().reads.display_none_is_animated
+ }
+
/// The computed `display` with what `overlay` composes over it.
pub(crate) fn effective_display(
self,
diff --git a/Libraries/LibWeb/Rust/src/css/style/dom_reads.rs b/Libraries/LibWeb/Rust/src/css/style/dom_reads.rs
index 799685beb27..a125bf5868b 100644
--- a/Libraries/LibWeb/Rust/src/css/style/dom_reads.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/dom_reads.rs
@@ -107,6 +107,38 @@ impl RetainedState {
self.projection.assigned_nodes_of(slot)[index]
}
+ /// The nodes assigned to the slot, in assignment order.
+ #[must_use]
+ pub fn assigned_nodes_of(&self, slot: StyleNodeID) -> &[StyleNodeID] {
+ self.projection.assigned_nodes_of(slot)
+ }
+
+ /// The element a node inherits from: the slot it is assigned to, its parent, or the host of the shadow root it is a
+ /// child of.
+ #[must_use]
+ pub fn inheritance_parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ if node.text_index().is_none() {
+ return self.projection.inheritance_parent(node);
+ }
+ if let Some(slot) = self.assigned_slot_of(node) {
+ return Some(slot);
+ }
+ let parent = self.text_parent(node)?;
+ Some(self.host_of(parent).unwrap_or(parent))
+ }
+
+ /// Whether the text node is in a user agent shadow tree.
+ #[must_use]
+ pub fn text_is_in_user_agent_shadow_tree(&self, node: StyleNodeID) -> bool {
+ self.tree.text_is_in_user_agent_shadow_tree(node)
+ }
+
+ /// The characters the text node holds.
+ #[must_use]
+ pub fn text_data(&self, node: StyleNodeID) -> Option<&ak::Utf16String> {
+ self.tree.text_data(node)
+ }
+
/// The node's DOM children in order, text nodes included.
pub fn dom_children(&self, node: StyleNodeID) -> impl Iterator<Item = StyleNodeID> + '_ {
self.tree.dom_children(node)
diff --git a/Libraries/LibWeb/Rust/src/css/style/engine.rs b/Libraries/LibWeb/Rust/src/css/style/engine.rs
index 212e5fe34b4..6268aef1a2d 100644
--- a/Libraries/LibWeb/Rust/src/css/style/engine.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/engine.rs
@@ -38,129 +38,8 @@ impl StyleEngine {
self.mint_style_nodes(out);
}
- #[inline]
- #[cfg(test)]
- pub(super) fn matches_for_cascade(
- &mut self,
- all: Vec<RuleMatch>,
- can_have_scope_duplicates: bool,
- publish_winners_for: Option<StyleNodeID>,
- ) -> Vec<RuleMatch> {
- self.matches_for_cascade_immediately(all, can_have_scope_duplicates, publish_winners_for)
- }
-
- /// Repair only the winner properties named by signed match changes.
- ///
- /// The retained exact answer supplies every contender, so deletion repair is a property-level
- /// upquery over rule identities rather than another selector match or whole-cascade reduction.
- #[inline]
- #[cfg(test)]
- pub(super) fn apply_cascade_winner_match_deltas(
- &mut self,
- node: StyleNodeID,
- matches: &[RuleMatch],
- deltas: &[SelectorTruthDelta],
- candidates: &mut Vec<OrderedCascadeCandidate>,
- ) -> bool {
- let mut effects = AnswerEffects::default();
- let result = self
- .retained
- .apply_cascade_winner_match_deltas(&mut effects, node, matches, deltas, candidates);
- self.install_answer_effects(effects);
- result
- }
-
/// Leaves the atom sweep of the transactions taken until the next call to a later one, where `defers`.
pub(crate) fn defer_atom_sweep(&mut self, defers: bool) {
self.host.defers_atom_sweep = defers;
}
-
- /// Apply a complete signed match delta directly to one retained exact answer.
- ///
- /// Entries with dynamic scope proximity still use the cold patch: their match row contains a
- /// value that the prefix match-set delta does not carry yet.
- #[inline]
- #[cfg(test)]
- pub(super) fn apply_retained_match_answer_deltas(
- &mut self,
- node: StyleNodeID,
- patch: &mut RetainedAnswerPatch,
- old_identity: MatchAnswerID,
- old_cascade_input: MatchAnswerID,
- deltas: &[SelectorTruthDelta],
- ) -> Option<RetainedAnswerPatchOutcome> {
- let mut effects = AnswerEffects::default();
- let result = self.retained.apply_retained_match_answer_deltas(
- &mut effects,
- node,
- patch,
- old_identity,
- old_cascade_input,
- deltas,
- );
- self.install_answer_effects(effects);
- result
- }
-
- /// Patch one retained exact answer by re-evaluating only the rules reached by this transaction.
- ///
- /// `None` means the optional old side was absent or exact evaluation could not complete. The
- /// caller then retires the answer and publishes an ordinary exact reaction.
- #[inline]
- #[cfg(test)]
- pub(super) fn patch_retained_match_answer(
- &mut self,
- node: StyleNodeID,
- patch: &mut RetainedAnswerPatch,
- truth_patch: SelectorTruthPatch<'_>,
- ) -> Option<RetainedAnswerPatchOutcome> {
- let mut effects = AnswerEffects::default();
- let result = self
- .retained
- .patch_retained_match_answer(&mut effects, node, patch, truth_patch);
- self.install_answer_effects(effects);
- result
- }
-
- /// Complete a node from a matching node's already compacted cascade input and winner rows.
- #[inline]
- #[cfg(test)]
- pub(super) fn complete_published_match_answer_from_cascade_input(
- &mut self,
- node: StyleNodeID,
- source: StyleNodeID,
- cascade_input: MatchAnswerID,
- cascade_winners_are_complete: bool,
- ) -> Option<PublishedMatchAnswer> {
- let mut effects = AnswerEffects::default();
- let result = self.retained.complete_published_match_answer_from_cascade_input(
- &mut effects,
- node,
- source,
- cascade_input,
- cascade_winners_are_complete,
- );
- self.install_answer_effects(effects);
- result
- }
-
- #[inline]
- #[cfg(test)]
- pub(super) fn retained_closure_cascade_input(&self, node: StyleNodeID) -> Option<MatchAnswerID> {
- let empty = AnswerEffects::default();
- let traversal = self.retained.batch_matching_traversal.as_ref();
- let effects = traversal.map_or(&empty, |traversal| &traversal.answer_effects);
- self.retained.retained_closure_cascade_input(effects, node)
- }
-
- #[inline]
- #[cfg(test)]
- pub(super) fn verify_retained_cascade_input(&mut self, node: StyleNodeID, cascade_input: MatchAnswerID) {
- let traversal = self.retained.batch_matching_traversal.take();
- let empty = AnswerEffects::default();
- let effects = traversal.as_ref().map_or(&empty, |traversal| &traversal.answer_effects);
- self.retained
- .verify_retained_cascade_input(effects, node, cascade_input);
- self.retained.batch_matching_traversal = traversal;
- }
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
index 9d9c6643509..0908c90c788 100644
--- a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs
@@ -14,12 +14,14 @@ use super::StyleEngine;
use super::atoms::{AtomKey, AtomLease};
use super::bridge::{
FfiDemandedPseudoElement, FfiElementArrival, FfiElementDeclarationDelta, FfiLocalFeatureDelta,
- FfiPseudoElementRecordDemand, FfiRecordDemand, FfiRecordDemandAnswer, FfiStateDelta, FfiTreeDelta, borrow,
+ FfiPseudoElementRecordDemand, FfiRecordDemand, FfiRecordDemandAnswer, FfiStateDelta, FfiTreeDelta,
+ FfiTreeRelations, borrow,
};
use super::font_resolution::{FontResolverHost, PublishedFontFaces};
use super::inputs::RetainedCustomPropertyData;
use super::instrumentation::Counter;
-use super::publication::{RecordDemand, RecordDemandAnswer, Unanswered};
+use super::pipeline::projection::ProjectionPublication;
+use super::publication::RecordDemand;
use super::random_bases::ParkedBaseValues;
use super::tree::{StyleNodeID, TreeScopeID};
use super::{HashMap, StyleAtomID};
@@ -42,7 +44,6 @@ pub(crate) enum EngineWrite {
data: Option<RetainedCustomPropertyData>,
identity: u64,
sampled_over: Option<u64>,
- declares: bool,
},
/// The custom-property environment one of an element's synthetic pseudo-elements holds, or none.
PseudoElementCustomPropertyData {
@@ -50,17 +51,37 @@ pub(crate) enum EngineWrite {
pseudo: u8,
data: Option<RetainedCustomPropertyData>,
identity: u64,
+ /// The environment its animation overlay lies over, where it holds one.
+ sampled_over: Option<u64>,
},
- /// The host minted these identities, which the engine makes live ahead of anything recorded about them.
+ /// The host minted these identities, which the engine's tree makes live ahead of anything recorded about them.
MintStyleNodes(Box<[u32]>),
- /// The tree, arrival, feature, state and declaration deltas the host staged, as one batch.
- ApplyTransaction(Box<StagedInput>),
- /// The parts an element exposes, each with the shadow host it is exposed to.
- ElementParts { node: StyleNodeID, pairs: ElementParts },
+ /// The unique node ids the document names the elements of an arriving subtree by.
+ ElementUniqueNodeIds(Box<[(StyleNodeID, i64)]>),
+ /// The text nodes of an arriving subtree, with what each holds.
+ TextArrivals(Box<[TextArrival]>),
+ /// The host ended the style update it took last: the engine lets go of the records it pinned for the host's
+ /// layout, and releases the identities no reader can name any more, which the job that applies it pays the host
+ /// to mint again.
+ EndStyleUpdate { pinned: Box<[u64]> },
+ /// What the host wrote of its elements since its last barrier, published at this one.
+ Publish(Box<HostPublication>),
+ /// The hover moves to the element, or off the document for none, once what the host wrote before is in place.
+ MoveHover(Option<StyleNodeID>),
+ /// The host wrote a shadow host's root, which it did not have before where `attached`.
+ ShadowRoot { host: StyleNodeID, attached: bool },
+ /// A slot's assigned nodes moved, which can hide or show its fallback content under the hover.
+ SlotAssignedNodes,
+ /// The element moved into or out of the top layer, as its host facts the host published say.
+ TopLayerMove { node: StyleNodeID },
+ /// The element asks for another principal box, as its host facts the host published say.
+ BoxKindChange { node: StyleNodeID },
+ /// Text identities retire as their nodes disconnect.
+ RetireTexts(Box<[StyleNodeID]>),
+ /// The root of a shadow tree's scope.
+ TreeScopeRoot { tree_scope: TreeScopeID, root: StyleNodeID },
/// The characters a text node holds.
TextData { node: u32, data: ak::Utf16String },
- /// The language an element resolves to, and the tag a `:lang()` range compares against.
- ElementLanguage { node: u32, language: u32, text: Box<[u16]> },
/// The presentational hints of one kind an element declares, expanded to the longhands they decide.
PresentationalHints {
node: StyleNodeID,
@@ -70,23 +91,10 @@ pub(crate) enum EngineWrite {
/// An element's inline declaration block, or none.
InlineStyle {
node: StyleNodeID,
- data: Option<Arc<crate::css::declaration_block::DeclarationBlockData>>,
+ data: Option<crate::css::declaration_block::SharedDeclarationBlock>,
},
/// A name the host interned, which the engine adopts as the atom the host's lease holds.
AdoptAtom(AtomLease),
- /// The other names the attribute name `name` answers to, and the local name an `attr()` reads it by where it is in
- /// no namespace.
- AttributeNameForms {
- name: StyleAtomID,
- forms: super::index::AttributeNameForms,
- substitution_name: Option<Box<[u16]>>,
- },
- /// What a value of the attribute name `name` spells, which the engine keeps where something reads it.
- AttributeValueText {
- name: StyleAtomID,
- value: StyleAtomID,
- text: crate::css::retained_fly_string::RetainedUtf16FlyString,
- },
/// An element loses its style node, and keeps the random base values of the keys that name it in `slot`.
ParkRandomBaseValues { node: StyleNodeID, slot: ParkedBaseValues },
/// An element's new style node takes back the random base values the element kept in `slot`.
@@ -95,23 +103,13 @@ pub(crate) enum EngineWrite {
/// store.
NoteCustomPropertyEnvironment {
identity: u64,
- store: Option<super::custom_property_environments::RetainedCustomPropertyStore>,
+ store: Option<std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>>,
inheritable: u64,
- inheritable_store: Option<super::custom_property_environments::RetainedCustomPropertyStore>,
- },
- /// The host folded the style input `node` owes into the reaction it applies to it, as it knew it would fold
- /// (see [`DeferredInputs::absorb`]), which `absorbed` answered: the engine folds it the same.
- AbsorbElementStyleInput {
- node: StyleNodeID,
- reaction: u8,
- inherited_style_groups: u8,
- absorbs_any: bool,
- absorbed: u32,
+ inheritable_store: Option<std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>>,
},
/// The `@keyframes` row of one style scope, named by the shadow root's pointer identity as well where it is one.
AnimationKeyframes {
tree_scope: TreeScopeID,
- shadow_root_identity: usize,
row: super::animations::KeyframesRow,
},
/// The `@position-try` row of one style scope.
@@ -133,55 +131,45 @@ pub(crate) enum EngineWrite {
},
}
-/// The tree, arrival, feature, state and declaration deltas the host recorded since it last submitted them, which reach
-/// the engine as one batch.
-#[derive(Default)]
-pub(crate) struct StagedInput {
- tree: Vec<FfiTreeDelta>,
- arrivals: Vec<FfiElementArrival>,
- /// The custom states of every arrival, which each names by its offset and count.
- arrival_custom_state_atoms: Vec<u32>,
- features: Vec<FfiLocalFeatureDelta>,
- states: Vec<FfiStateDelta>,
- declarations: Vec<FfiElementDeclarationDelta>,
- /// The element the hover moves to once the rest is in place, or none for a move off the document, where the input
- /// moves it.
- hover: Option<Option<StyleNodeID>>,
+/// What the host publishes at a barrier: its projection rows, and what its elements arrived with and declare beside
+/// them, which the render owner keeps elsewhere.
+pub(crate) struct HostPublication {
+ projection: ProjectionPublication,
+ /// The elements published standing for an element-backed pseudo-element of their shadow host, which the render
+ /// owner finds them by.
+ backing_elements: Box<[StyleNodeID]>,
+ declarations: Box<[FfiElementDeclarationDelta]>,
}
-impl StagedInput {
- /// How many tree deltas the batch holds, each of which may deepen the tree by a level.
- pub(crate) fn tree_delta_count(&self) -> usize {
- self.tree.len()
- }
-
- fn is_empty(&self) -> bool {
- self.tree.is_empty()
- && self.arrivals.is_empty()
- && self.features.is_empty()
- && self.states.is_empty()
- && self.declarations.is_empty()
- && self.hover.is_none()
+impl HostPublication {
+ /// How many elements' links the publication wrote, each of which may deepen the tree by a level.
+ pub(crate) fn link_rows_written(&self) -> usize {
+ self.projection.link_rows_written()
}
+}
- /// Stages the move of the hover to `target`, or off the document for none.
- pub(crate) fn stage_hover(&mut self, target: Option<StyleNodeID>) {
- self.hover = Some(target);
- }
+/// What the host writes beside its projection rows until its next barrier publishes them.
+#[derive(Default)]
+pub(crate) struct UnpublishedInputs {
+ backing_elements: Vec<StyleNodeID>,
+ declarations: Vec<FfiElementDeclarationDelta>,
}
impl EngineWrite {
/// Whether the write may move a fact the host knows of the render state. What a text, an attribute name or an
/// attribute value spells never does: it stages no style input and touches no layout box.
pub(crate) fn may_move_facts(&self) -> bool {
- !matches!(
- self,
- Self::TextData { .. } | Self::AttributeNameForms { .. } | Self::AttributeValueText { .. }
- )
+ !matches!(self, Self::TextData { .. } | Self::EndStyleUpdate { .. })
}
pub(crate) fn apply(self, engine: &mut StyleEngine) {
match self {
+ Self::EndStyleUpdate { pinned } => {
+ for record in pinned {
+ engine.unpin_layout_style_record(record);
+ }
+ engine.release_style_update_identities();
+ }
Self::PublishFontFaces {
font_faces,
feature_values_shadow_scopes,
@@ -190,67 +178,86 @@ impl EngineWrite {
Some(resolver) => resolver.publish(font_faces),
None => engine.host.font_resolver = Some(FontResolverHost::new(font_faces)),
}
- engine
- .retained
- .font_resolution
- .get_or_insert_default()
- .publish_feature_values_shadow_scopes(feature_values_shadow_scopes);
+ let font_resolution = engine.retained.font_resolution.get_or_insert_default();
+ font_resolution.forget_earlier_generations();
+ font_resolution.publish_feature_values_shadow_scopes(feature_values_shadow_scopes);
}
Self::ElementCustomPropertyData {
node,
data,
identity,
sampled_over,
- declares,
- } => engine.set_element_custom_property_data(node, data, identity, sampled_over, declares),
+ } => {
+ // The children of an element style styles inherit what its animations
+ // sample into its custom properties. Where an installation let go of its
+ // composition, what moved is told once the host settled it again.
+ let held_composition = match engine.composition_released(node) {
+ true => None,
+ false => engine.hold_composition(node),
+ };
+ engine.set_element_custom_property_data(node, data, identity, sampled_over);
+ if let Some(held_composition) = held_composition {
+ engine.note_composition_moved(node, held_composition);
+ }
+ }
Self::PseudoElementCustomPropertyData {
node,
pseudo,
data,
identity,
- } => engine.set_pseudo_element_custom_property_data(node, pseudo, data, identity),
+ sampled_over,
+ } => engine.set_pseudo_element_custom_property_data(node, pseudo, data, identity, sampled_over),
Self::MintStyleNodes(nodes) => engine.mint_style_nodes(&nodes),
- Self::ApplyTransaction(input) => {
- engine.apply_transaction_batch(
- &input.tree,
- (&input.arrivals, &input.arrival_custom_state_atoms),
- &input.features,
- &input.states,
- &input.declarations,
- &[],
- );
- // The hover moves where the host asks, and its chain follows the tree where the tree moved under it.
- let hover = input
- .hover
- .or_else(|| (!input.tree.is_empty()).then(|| engine.hover_target()));
- if let Some(target) = hover {
- engine.set_hover(target);
+ Self::ElementUniqueNodeIds(ids) => {
+ for &(node, unique_node_id) in &ids {
+ engine.set_element_unique_node_id(node, unique_node_id);
}
}
- Self::ElementParts { node, pairs } => engine.set_element_parts(node, &pairs),
- Self::TextData { node, data } => {
- if let Some(node) = StyleNodeID::from_raw(node) {
- engine.set_text_data(node, data);
+ Self::TextArrivals(texts) => {
+ for text in texts {
+ engine.set_text_is_ascii_whitespace(text.node, text.is_ascii_whitespace);
+ engine.set_text_is_in_user_agent_shadow_tree(text.node, text.is_in_user_agent_shadow_tree);
+ engine.set_text_is_password_input(text.node, text.is_password_input);
+ engine.set_text_data(text.node, text.data);
}
}
- Self::ElementLanguage { node, language, text } => {
- if language != 0 && !text.is_empty() {
- // A range is not a name, so `:lang()` compares against the tag itself. It is recorded once per
- // language rather than once per element.
- engine.set_element_language_text(StyleAtomID(language), &text);
+ Self::Publish(publication) => {
+ let HostPublication {
+ projection,
+ backing_elements,
+ declarations,
+ } = *publication;
+ engine.adopt_host_publication(projection, &backing_elements, &declarations);
+ }
+ Self::MoveHover(target) => engine.set_hover(target),
+ Self::ShadowRoot { host, attached } => engine.note_shadow_root(host, attached),
+ Self::RetireTexts(nodes) => engine.retire_text_style_nodes(nodes),
+ Self::TopLayerMove { node } => engine.note_top_layer_move(node),
+ Self::BoxKindChange { node } => engine.note_box_kind_change(node),
+ Self::TreeScopeRoot { tree_scope, root } => engine.set_tree_scope_root(tree_scope, root),
+ Self::SlotAssignedNodes => {
+ // Text-only assignments do not carry element tree deltas, but can hide or restore fallback content.
+ if let Some(target) = engine.hover_target() {
+ engine.set_hover(Some(target));
}
+ }
+ Self::TextData { node, data } => {
if let Some(node) = StyleNodeID::from_raw(node) {
- engine.set_element_language(node, StyleAtomID(language));
+ engine.set_text_data(node, data);
}
}
Self::PresentationalHints { node, kind, properties } => {
- super::bridge::register_element_declared_properties(engine, node, kind, &properties, &[]);
+ super::bridge::register_element_declared_properties(
+ engine,
+ node,
+ kind,
+ properties
+ .iter()
+ .map(crate::css::declaration_block::DeclaredProperty::borrowed),
+ Default::default(),
+ );
}
- Self::AnimationKeyframes {
- tree_scope,
- shadow_root_identity,
- row,
- } => engine.animation_keyframes.set(tree_scope, shadow_root_identity, row),
+ Self::AnimationKeyframes { tree_scope, row } => engine.animation_keyframes.set(tree_scope, row),
Self::PositionTryRules { tree_scope, row } => engine.position_try_rules.set(tree_scope, row),
Self::AnimationEffectDescriptions { node, slot, effects } => {
engine.animation_effect_descriptions.set(node, slot, effects);
@@ -267,11 +274,15 @@ impl EngineWrite {
engine,
node,
super::bridge::FfiElementDeclarationKind::InlineStyle,
- data.as_ref().map_or(&[], |data| data.properties.as_slice()),
- data.as_ref().map_or(&[], |data| data.custom_properties.as_slice()),
+ data.as_ref()
+ .map_or_else(Default::default, |data| data.properties())
+ .iter(),
+ data.as_ref()
+ .map_or(Default::default(), |data| data.custom_properties()),
);
}
Self::AdoptAtom(lease) => {
+ debug_assert!(lease.is_of(engine.retained.atoms.process_atoms()));
let atom = match lease.key() {
AtomKey::Raw(raw) => engine.intern_atom(raw).0,
AtomKey::Qualified(namespace, name) => engine.intern_qualified_atom(namespace, name).0,
@@ -279,21 +290,6 @@ impl EngineWrite {
// The engine took a reference of its own, so the global atom stays the one the lease held.
assert_eq!(atom, lease.atom().0, "a document adopts the atom its host interned");
}
- Self::AttributeNameForms {
- name,
- forms,
- substitution_name,
- } => {
- engine.note_attribute_name_forms(name, forms);
- if let Some(local_name) = substitution_name {
- engine.note_attribute_substitution_name(name, &local_name);
- }
- }
- Self::AttributeValueText { name, value, text } => {
- if engine.attribute_name_requires_value_text(name) {
- engine.set_attribute_value_text(value, &text.to_utf16());
- }
- }
Self::ParkRandomBaseValues { node, slot } => {
*slot.lock().expect("a parked row is never poisoned") =
engine.random_base_values.take_element_values(node);
@@ -311,41 +307,17 @@ impl EngineWrite {
super::bridge::note_custom_property_environment(
engine,
identity,
- store
- .as_ref()
- .map(super::custom_property_environments::RetainedCustomPropertyStore::store),
+ store.as_ref(),
inheritable,
- inheritable_store
- .as_ref()
- .map(super::custom_property_environments::RetainedCustomPropertyStore::store),
- );
- }
- Self::AbsorbElementStyleInput {
- node,
- reaction,
- inherited_style_groups,
- absorbs_any,
- absorbed,
- } => {
- let engine_absorbed =
- engine.absorb_element_style_input(node, reaction, inherited_style_groups, absorbs_any);
- // A fold that merges nothing into the reaction answers the same as none.
- debug_assert!(
- engine_absorbed == absorbed
- || (absorbed == 0
- && engine_absorbed == u32::from(reaction) | (u32::from(inherited_style_groups) << 8)),
- "the engine folds a style input as the host did"
+ inheritable_store.as_ref(),
);
}
}
}
}
-/// The parts an element exposes, each with the shadow host it is exposed to.
-type ElementParts = Box<[(StyleAtomID, StyleNodeID)]>;
-
/// The parts the element `node` exposes, each with the shadow host it is exposed to, or none for no element.
-fn element_parts(node: u32, names: &[u32], hosts: &[u32]) -> Option<(StyleNodeID, ElementParts)> {
+fn element_parts(node: u32, names: &[u32], hosts: &[u32]) -> Option<(StyleNodeID, Vec<(StyleAtomID, StyleNodeID)>)> {
let node = StyleNodeID::from_raw(node)?;
let pairs = names
.iter()
@@ -393,8 +365,7 @@ pub unsafe extern "C" fn style_engine_publish_font_faces(
}
/// Keeps the custom-property environment an element now holds, named by `identity`: for the element's animation
-/// overlay, the environment `base` its style resolved to beneath it, and whether `base` declares custom properties of its
-/// own over the one it inherits. A null `data` is none.
+/// overlay, and the environment `base` its style resolved to beneath it. A null `data` is none.
///
/// # Safety
/// `host` must be a live document host, and `data` null or a live `Web::CSS::CustomPropertyData`.
@@ -405,13 +376,15 @@ pub unsafe extern "C" fn style_engine_set_element_custom_property_data(
data: *const c_void,
identity: u64,
is_animation_overlay: bool,
- declares: bool,
base: u64,
) {
let Some(node) = StyleNodeID::from_raw(node) else {
return;
};
- host.engine_memo().held.borrow_mut().follow_element(node, data);
+ host.engine_memo()
+ .held
+ .borrow_mut()
+ .follow_element(node, HeldEnvironment::new(data, is_animation_overlay));
// SAFETY: Guaranteed by the caller.
let data = (!data.is_null()).then(|| unsafe { RetainedCustomPropertyData::retain(data) });
let write = EngineWrite::ElementCustomPropertyData {
@@ -419,13 +392,13 @@ pub unsafe extern "C" fn style_engine_set_element_custom_property_data(
data,
identity,
sampled_over: is_animation_overlay.then_some(base),
- declares,
};
host.queue_change(ArenaChange::Engine(write));
}
/// Keeps the custom-property environment one of an element's synthetic pseudo-elements now holds, named by
-/// `identity`. A null `data` is none.
+/// `identity`: for the pseudo-element's animation overlay, the environment `base` its style resolved to beneath it. A
+/// null `data` is none.
///
/// # Safety
/// `host` must be a live document host, and `data` null or a live `Web::CSS::CustomPropertyData`.
@@ -436,14 +409,17 @@ pub unsafe extern "C" fn style_engine_set_pseudo_element_custom_property_data(
pseudo: u8,
data: *const c_void,
identity: u64,
+ is_animation_overlay: bool,
+ base: u64,
) {
let Some(node) = StyleNodeID::from_raw(node) else {
return;
};
- host.engine_memo()
- .held
- .borrow_mut()
- .follow_pseudo_element(node, pseudo, data);
+ host.engine_memo().held.borrow_mut().follow_pseudo_element(
+ node,
+ pseudo,
+ HeldEnvironment::new(data, is_animation_overlay),
+ );
// SAFETY: Guaranteed by the caller.
let data = (!data.is_null()).then(|| unsafe { RetainedCustomPropertyData::retain(data) });
let write = EngineWrite::PseudoElementCustomPropertyData {
@@ -451,83 +427,205 @@ pub unsafe extern "C" fn style_engine_set_pseudo_element_custom_property_data(
pseudo,
data,
identity,
+ sampled_over: is_animation_overlay.then_some(base),
};
host.queue_change(ArenaChange::Engine(write));
}
-/// Makes the identities `nodes`, which the host minted, live.
+/// Mints an identity into each slot of `nodes`, text identities where `text`, otherwise element ones, and makes them
+/// live in the engine.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_mint_style_nodes(host: &DocumentHost, text: bool, nodes: ak::SpanMut<'_, u32>) {
+ let nodes = nodes.into_slice();
+ host.engine_memo().identities.borrow_mut().mint(text, nodes);
+ host.engine_memo()
+ .projection
+ .borrow_mut()
+ .writes()
+ .mint(nodes.iter().copied().filter_map(StyleNodeID::from_raw));
+ host.queue_change(ArenaChange::Engine(EngineWrite::MintStyleNodes((&*nodes).into())));
+}
+
+/// A text node of an arriving subtree, with what it holds.
+pub(crate) struct TextArrival {
+ node: StyleNodeID,
+ data: ak::Utf16String,
+ is_ascii_whitespace: bool,
+ is_in_user_agent_shadow_tree: bool,
+ is_password_input: bool,
+}
+
+/// An element of an arriving subtree: its identity, the unique node id the document names it by, and how it stands in
+/// the tree.
+#[repr(C)]
+pub struct FfiArrivingElement {
+ pub unique_node_id: u64,
+ pub node: u32,
+ pub relations: FfiTreeRelations,
+}
+
+/// A text node of an arriving subtree: its identity, the characters it holds, as one reference to a live string, and
+/// what it is.
+#[repr(C)]
+pub struct FfiArrivingText {
+ pub data: usize,
+ pub node: u32,
+ pub is_ascii_whitespace: bool,
+ pub is_in_user_agent_shadow_tree: bool,
+ pub is_password_input: bool,
+}
+
+/// Writes the arrival of each element of an arriving subtree into the host's projection rows in one call, as a tree
+/// delta from standing in no tree, and the unique node ids the document names them by.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_stage_element_arrivals(host: &DocumentHost, elements: ak::Span<'_, FfiArrivingElement>) {
+ let elements = elements.as_slice();
+ let detached = FfiTreeRelations {
+ parent: 0,
+ previous_element_sibling: 0,
+ next_element_sibling: 0,
+ tree_scope: 0,
+ assigned_slot: 0,
+ };
+ {
+ let mut projection = host.engine_memo().projection.borrow_mut();
+ let mut writes = projection.writes();
+ for element in elements {
+ writes.record_ffi_tree_delta(&FfiTreeDelta {
+ node: element.node,
+ old_connected: false,
+ new_connected: true,
+ old_relations: detached,
+ new_relations: element.relations,
+ });
+ }
+ }
+ let ids: Box<[(StyleNodeID, i64)]> = elements
+ .iter()
+ .filter_map(|element| {
+ Some((
+ StyleNodeID::from_raw(element.node)?,
+ element.unique_node_id.cast_signed(),
+ ))
+ })
+ .collect();
+ if !ids.is_empty() {
+ host.queue_change(ArenaChange::Engine(EngineWrite::ElementUniqueNodeIds(ids)));
+ }
+}
+
+/// Writes each text node of an arriving subtree, with what it holds, in one write.
+///
+/// # Safety
+/// `host` must be a live document host, and the caller transfers one reference to each text's live string `data`.
#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_mint_style_nodes(host: &DocumentHost, nodes: ak::Span<'_, u32>) {
- host.queue_change(ArenaChange::Engine(EngineWrite::MintStyleNodes(
- nodes.as_slice().into(),
- )));
+pub unsafe extern "C" fn style_engine_stage_text_arrivals(host: &DocumentHost, texts: ak::Span<'_, FfiArrivingText>) {
+ let texts: Box<[TextArrival]> = texts
+ .as_slice()
+ .iter()
+ .filter_map(|text| {
+ // SAFETY: Guaranteed by the caller.
+ let data = unsafe { ak::Utf16String::from_raw_owned(text.data) };
+ Some(TextArrival {
+ node: StyleNodeID::from_raw(text.node)?,
+ data,
+ is_ascii_whitespace: text.is_ascii_whitespace,
+ is_in_user_agent_shadow_tree: text.is_in_user_agent_shadow_tree,
+ is_password_input: text.is_password_input,
+ })
+ })
+ .collect();
+ if !texts.is_empty() {
+ host.queue_change(ArenaChange::Engine(EngineWrite::TextArrivals(texts)));
+ }
}
-/// Stages the tree delta `delta` for the input the host submits next.
+/// Writes the tree delta `delta` into the host's projection rows.
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_stage_tree_delta(host: &DocumentHost, delta: &FfiTreeDelta) {
- host.engine_memo().staged_input.borrow_mut().tree.push(*delta);
+ host.engine_memo()
+ .projection
+ .borrow_mut()
+ .writes()
+ .record_ffi_tree_delta(delta);
}
-/// Stages the arrival of an element with the custom states at `custom_states` for the input the host submits next.
+/// Writes the arrival of an element, with every fact its selectors test, into its projection row in one go, and keeps
+/// what it arrives with beside its row for the host's next barrier.
///
/// # Safety
-/// `host` must be a live document host, on its document's thread, and `custom_states` must point at
-/// `custom_state_count` readable atoms.
+/// `host` must be a live document host, on its document's thread, `custom_states` and `classes` must point at
+/// `arrival.custom_state_count` and `arrival.class_count` readable atoms, and `attributes` at
+/// `2 * arrival.attribute_count` readable atoms, a name and a value per attribute.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn style_engine_stage_element_arrival(
host: &DocumentHost,
arrival: &FfiElementArrival,
custom_states: *const u32,
- custom_state_count: usize,
+ classes: *const u32,
+ attributes: *const u32,
) {
- let mut staged = host.engine_memo().staged_input.borrow_mut();
- let mut arrival = *arrival;
- arrival.custom_state_offset =
- u32::try_from(staged.arrival_custom_state_atoms.len()).expect("an input stages fewer than 2^32 custom states");
- arrival.custom_state_count =
- u32::try_from(custom_state_count).expect("an element has fewer than 2^32 custom states");
+ let Some(node) = StyleNodeID::from_raw(arrival.node) else {
+ debug_assert!(false, "an element arrival named an invalid style node");
+ return;
+ };
+ let mut atoms: smallvec::SmallVec<[u32; 32]> = smallvec::SmallVec::new();
// SAFETY: Guaranteed by the caller.
- staged
- .arrival_custom_state_atoms
- .extend_from_slice(unsafe { borrow(custom_states, custom_state_count) });
- staged.arrivals.push(arrival);
+ unsafe {
+ atoms.extend_from_slice(borrow(custom_states, arrival.custom_state_count as usize));
+ atoms.extend_from_slice(borrow(classes, arrival.class_count as usize));
+ atoms.extend_from_slice(borrow(attributes, 2 * arrival.attribute_count as usize));
+ }
+ let memo = host.engine_memo();
+ memo.projection
+ .borrow_mut()
+ .writes()
+ .record_element_arrival(node, &super::bridge::element_arrival_facts(arrival, &atoms));
+ if arrival.associated_pseudo_kind_plus_one != 0 {
+ memo.unpublished.borrow_mut().backing_elements.push(node);
+ }
}
-/// Stages the local feature delta `delta` for the input the host submits next.
+/// Writes the local feature delta `delta` into the host's projection rows.
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_stage_local_feature_delta(host: &DocumentHost, delta: &FfiLocalFeatureDelta) {
- host.engine_memo().staged_input.borrow_mut().features.push(*delta);
+ host.engine_memo()
+ .projection
+ .borrow_mut()
+ .writes()
+ .record_ffi_local_feature(delta);
}
-/// Stages the state delta `delta` for the input the host submits next.
+/// Writes the state delta `delta` into the host's projection rows.
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_stage_state_delta(host: &DocumentHost, delta: &FfiStateDelta) {
- host.engine_memo().staged_input.borrow_mut().states.push(*delta);
+ host.engine_memo()
+ .projection
+ .borrow_mut()
+ .writes()
+ .record_ffi_state(delta);
}
-/// Stages the element declaration delta `delta` for the input the host submits next.
+/// Keeps the element declaration delta `delta` for the host's next barrier.
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_stage_element_declaration_delta(
host: &DocumentHost,
delta: &FfiElementDeclarationDelta,
) {
- host.engine_memo().staged_input.borrow_mut().declarations.push(*delta);
+ host.engine_memo().unpublished.borrow_mut().declarations.push(*delta);
}
-/// Whether the host staged deltas it has not submitted yet.
+/// Whether the host wrote anything of its elements it has not published yet.
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_has_staged_input(host: &DocumentHost) -> bool {
- !host.engine_memo().staged_input.borrow().is_empty()
+ host.engine_memo().has_unpublished_writes()
}
-/// Submits the deltas the host staged as one batch, which the engine applies in order with the host's other writes.
+/// Publishes what the host wrote of its elements since its last barrier, which the engine takes in order with the
+/// host's other writes.
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_submit_staged_input(host: &DocumentHost) {
- let staged = std::mem::take(&mut *host.engine_memo().staged_input.borrow_mut());
- if !staged.is_empty() {
- host.queue_change(ArenaChange::Engine(EngineWrite::ApplyTransaction(Box::new(staged))));
- }
+ host.publish_element_writes();
}
/// Records the parts the element exposes, each with the shadow host at `hosts` it is exposed to.
@@ -545,7 +643,11 @@ pub unsafe extern "C" fn style_engine_set_element_parts(
// SAFETY: Guaranteed by the caller.
let (names, hosts) = unsafe { (borrow(names, count), borrow(hosts, count)) };
if let Some((node, pairs)) = element_parts(node, names, hosts) {
- host.queue_change(ArenaChange::Engine(EngineWrite::ElementParts { node, pairs }));
+ host.engine_memo()
+ .projection
+ .borrow_mut()
+ .writes()
+ .set_element_parts(node, &pairs);
}
}
@@ -592,10 +694,7 @@ pub(crate) fn with_engine_and_arena<R>(
/// The custom-property environment an element holds, or null.
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_element_custom_property_data(host: &DocumentHost, node: u32) -> *const c_void {
- let Some(node) = StyleNodeID::from_raw(node) else {
- return std::ptr::null();
- };
- host.engine_memo().held.borrow().element(node)
+ held_environment(host, node, None).data()
}
/// The custom-property environment one of an element's synthetic pseudo-elements holds, or null.
@@ -605,22 +704,34 @@ pub extern "C" fn style_engine_pseudo_element_custom_property_data(
node: u32,
pseudo: u8,
) -> *const c_void {
- let Some(node) = StyleNodeID::from_raw(node) else {
- return std::ptr::null();
- };
- host.engine_memo().held.borrow().pseudo_element(node, pseudo)
+ held_environment(host, node, Some(pseudo)).data()
}
-/// Which of an element's synthetic pseudo-elements hold a custom-property environment, as a bit set by kind.
+/// Whether the custom-property environment an element holds, or one of its synthetic pseudo-elements of the kind
+/// `pseudo` where it is not `u8::MAX`, is the overlay of what the holder's own animations sample.
#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_pseudo_elements_with_custom_property_data(host: &DocumentHost, node: u32) -> u64 {
+pub extern "C" fn style_engine_custom_property_data_is_animation_overlay(
+ host: &DocumentHost,
+ node: u32,
+ pseudo: u32,
+) -> bool {
+ let pseudo = pseudo as u8;
+ held_environment(host, node, (pseudo != u8::MAX).then_some(pseudo)).is_animation_overlay()
+}
+
+fn held_environment(host: &DocumentHost, node: u32, pseudo: Option<u8>) -> HeldEnvironment {
let Some(node) = StyleNodeID::from_raw(node) else {
- return 0;
+ return HeldEnvironment::NONE;
};
- host.engine_memo().held.borrow().pseudo_element_kinds(node)
+ let held = host.engine_memo().held.borrow();
+ match pseudo {
+ None => held.element(node),
+ Some(pseudo) => held.pseudo_element(node, pseudo),
+ }
}
-/// The nodes whose style depends on the viewport, handed to `append` one by one.
+/// The nodes whose style depends on the axes of the viewport `moved_axes` names, as `StyleEnvironment` bits, handed
+/// to `append` one by one.
///
/// # Safety
///
@@ -629,13 +740,17 @@ pub extern "C" fn style_engine_pseudo_elements_with_custom_property_data(host: &
pub unsafe extern "C" fn style_engine_viewport_dependent_nodes(
host: &DocumentHost,
read: &crate::render_state::BegunRead,
+ moved_axes: u8,
context: *mut c_void,
append: unsafe extern "C" fn(*mut c_void, u32),
) {
+ let moved = super::input_types::StyleEnvironment::from_bits(moved_axes);
let nodes = with_engine(read, host, |engine| {
- engine
- .computed_group_sets
- .viewport_dependent_nodes(|environment| engine.custom_property_environments.reads_viewport(environment))
+ let mut nodes = engine.computed_group_sets.viewport_dependent_nodes();
+ if let Some(live) = engine.retained.live_style.as_ref() {
+ nodes.retain(|&node| StyleNodeID::from_raw(node).is_none_or(|node| live.reads_viewport_axes(node, moved)));
+ }
+ nodes
});
for node in nodes {
// SAFETY: Guaranteed by the caller.
@@ -732,66 +847,13 @@ fn ask_record_demand(
})
}
-/// What a style record's values depend on.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_style_record_dependency_flags(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- style_record: u64,
-) -> u8 {
- let memo = &host.engine_memo().dependency_flags;
- if let Some(flags) = memo.get(style_record) {
- return flags;
- }
- if let Some(view) = host
- .engine_memo()
- .views
- .get(style_record)
- .or_else(|| host.transaction_record(style_record).map(|(view, _)| view))
- {
- return view.dependency_flags;
- }
- let Some(flags) = with_engine(read, host, |engine| engine.style_record_dependency_flags(style_record)) else {
- return 0;
- };
- memo.set(style_record, flags);
- flags
-}
-
-/// The identity of the custom-property environment a style record was computed in, or 0.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_style_record_custom_property_environment(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- style_record: u64,
-) -> u64 {
- let memo = &host.engine_memo().record_environments;
- if let Some(environment) = memo.get(style_record) {
- return environment;
- }
- if let Some((_, Some(environment))) = host.transaction_record(style_record) {
- memo.set(style_record, environment);
- return environment;
- }
- let Some(environment) = with_engine(read, host, |engine| {
- engine
- .computed_group_sets
- .style_record_custom_property_environment(style_record)
- }) else {
- return 0;
- };
- memo.set(style_record, environment);
- environment
-}
-
/// What the host knows of its document's style engine, which answers the host's reads without asking the render owner.
pub(crate) struct EngineMemo {
- /// The view of each style record the host asked about, the custom-property environment it was computed in, and
- /// what its values depend on: a published record never changes while it is live, and no other record ever takes
- /// its identity, as each identity carries the generation of its slot.
- pub(crate) views: Memo<super::bridge::FfiStyleRecordView>,
- pub(crate) record_environments: Memo<u64>,
- pub(crate) dependency_flags: Memo<u8>,
+ /// The record of each style record identity the host asked about: a published record never changes while it is
+ /// live, and no other record ever takes its identity, as each identity carries the generation of its slot.
+ /// The records the host holds for the records it asked for or a transaction carried, by record, which the engine
+ /// holds while it holds the record.
+ pub(crate) views: Memo<*const c_void>,
/// The custom-property environments the engine holds for elements.
pub(crate) held: std::cell::RefCell<HeldEnvironments>,
/// The element style inputs the engine defers.
@@ -802,11 +864,12 @@ pub(crate) struct EngineMemo {
pub(crate) baselines: std::cell::RefCell<super::TransitionBaselines>,
/// The atoms the host interned for the engine.
pub(crate) atoms: std::cell::RefCell<super::host_atoms::HostAtoms>,
- /// The deltas the host recorded since it last submitted them.
- pub(crate) staged_input: std::cell::RefCell<StagedInput>,
- /// The elements that arrived, moved or retired beside the style transaction that flew, which knows nothing of
- /// them, until the drain of its reactions ends.
- pub(crate) beside_flown_transaction: std::cell::RefCell<super::HashSet<StyleNodeID>>,
+ /// The identity space of the document's style nodes, which the host mints from.
+ identities: std::cell::RefCell<super::identities::StyleNodeIdAllocator>,
+ /// The host's writer of the projection rows of its document's elements, which nothing else writes.
+ pub(in crate::css::style) projection: std::cell::RefCell<super::pipeline::projection::ProjectionWriter>,
+ /// What the host wrote beside the rows since its last barrier.
+ unpublished: std::cell::RefCell<UnpublishedInputs>,
/// While a batch's reactions are applied, a host's own style application may rewrite the declarations of an
/// element in its shadow tree, after the engine computed that element's record from the ones it had. These name
/// the elements whose declarations changed that way, while `applying_reactions` counts the batches being applied.
@@ -815,26 +878,88 @@ pub(crate) struct EngineMemo {
/// Whether the transaction the host takes is one a style update applies, whose reactions close over the elements
/// they inherit through as the engine computes them.
takes_transaction_to_apply: std::cell::Cell<bool>,
- /// The trace of the targeted style update the panic of a layout update that ran out of passes makes of the
- /// element it kept reaching without a style, while the update is traced.
- bound_failure_trace: std::cell::RefCell<Option<String>>,
+ /// What `LIBWEB_STYLE_SELFCHECK` asked for as the host started.
+ pub(super) style_self_check: super::pipeline::SelfCheckSettings,
}
impl EngineMemo {
+ /// Forgets the atoms the engine reclaimed, whose numbers may name other names from now on: those the host interned,
+ /// and what the catalogs its projection rows are spelled with spell of them.
+ pub(crate) fn forget_reclaimed_atoms(&self, reclaimed: &[super::atoms::ReclaimedStyleAtom]) {
+ self.atoms.borrow_mut().forget(reclaimed);
+ if !reclaimed.is_empty() {
+ let reclaimed: Vec<StyleAtomID> = reclaimed.iter().map(|reclaimed| reclaimed.atom).collect();
+ self.projection.borrow_mut().forget_atoms(&reclaimed);
+ }
+ }
+
+ /// Counts what the memo holds toward the host's own owner, but for its projection writer, whose rows count toward
+ /// the projection.
+ pub(crate) fn report_memory(&self, report: &mut super::memory_report::MemoryReport) {
+ use crate::heap_size::{set_bytes, vec_bytes};
+ let unpublished = self.unpublished.borrow();
+ let bytes = size_of::<Memo<*const c_void>>()
+ + self.held.borrow().heap_size()
+ + self.deferred.borrow().heap_size()
+ + self.described.borrow().heap_size()
+ + self.baselines.borrow().heap_size()
+ + self.atoms.borrow().heap_size()
+ + vec_bytes(&unpublished.backing_elements)
+ + vec_bytes(&unpublished.declarations)
+ + set_bytes(&self.declarations_changed_during_apply.borrow());
+ report.add(super::memory_report::MemoryOwner::HostMemo, bytes);
+ }
+
+ /// Note that `node` stands for an element-backed pseudo-element of its shadow host, which the render owner finds it
+ /// by from the next barrier on.
+ pub(crate) fn note_backing_element(&self, node: StyleNodeID) {
+ self.unpublished.borrow_mut().backing_elements.push(node);
+ }
+
+ /// Whether the host wrote anything of its elements since its last barrier.
+ pub(crate) fn has_unpublished_writes(&self) -> bool {
+ let unpublished = self.unpublished.borrow();
+ self.projection.borrow().has_unpublished_writes()
+ || !unpublished.backing_elements.is_empty()
+ || !unpublished.declarations.is_empty()
+ }
+
+ /// Takes what the host wrote of its elements since its last barrier, where it wrote anything, as published at
+ /// this one.
+ pub(crate) fn take_publication(&self) -> Option<HostPublication> {
+ if !self.has_unpublished_writes() {
+ return None;
+ }
+ let unpublished = std::mem::take(&mut *self.unpublished.borrow_mut());
+ Some(HostPublication {
+ projection: self.projection.borrow_mut().publish(),
+ backing_elements: unpublished.backing_elements.into(),
+ declarations: unpublished.declarations.into(),
+ })
+ }
+
+ /// Forgets what the host follows of the style nodes the end of a transaction released, and mints their identities
+ /// again first.
+ pub(crate) fn take_back_released_style_nodes(&self, released: &[u32]) {
+ if released.is_empty() {
+ return;
+ }
+ self.held.borrow_mut().forget(released);
+ self.described.borrow_mut().forget(released);
+ self.baselines.borrow_mut().forget(released);
+ self.identities.borrow_mut().release(released);
+ }
+
pub(crate) fn forget_released_animation_overlay_records(&self, released: &super::ReleasedAnimationOverlayRecords) {
if released.overflowed() {
let is_animation_overlay = |key: u64| {
super::computed::FinalStyleRecordID::from_raw(key).is_some_and(|record| record.is_animation_overlay())
};
self.views.forget_where(is_animation_overlay);
- self.record_environments.forget_where(is_animation_overlay);
- self.dependency_flags.forget_where(is_animation_overlay);
return;
}
for record in released.records() {
self.views.forget(record);
- self.record_environments.forget(record);
- self.dependency_flags.forget(record);
}
}
@@ -855,10 +980,6 @@ impl EngineMemo {
}
}
- pub(crate) fn declarations_changed_during_apply(&self, node: StyleNodeID) -> bool {
- self.declarations_changed_during_apply.borrow().contains(&node)
- }
-
/// Marks the transactions the host takes until the answer is dropped as ones a style update applies.
pub(crate) fn take_transactions_to_apply(&self) -> impl Drop + '_ {
struct Taking<'a>(&'a EngineMemo);
@@ -870,50 +991,24 @@ impl EngineMemo {
self.takes_transaction_to_apply.set(true);
Taking(self)
}
-
- /// The elements a transaction the host takes now leaves to the next transaction as its reactions close over the
- /// elements they inherit through, or none where the host does not apply its reactions.
- pub(crate) fn closes_taken_transaction_beside(&self) -> Option<super::HashSet<StyleNodeID>> {
- self.takes_transaction_to_apply
- .get()
- .then(|| self.beside_flown_transaction.borrow().clone())
- }
-
- /// Notes the elements whose declarations change until the answer is dropped, beside the batches being applied
- /// already.
- pub(crate) fn note_declaration_changes_during_apply(&self) -> impl Drop + '_ {
- struct Noting<'a>(&'a EngineMemo);
- impl Drop for Noting<'_> {
- fn drop(&mut self) {
- let applying = self.0.applying_reactions.get() - 1;
- self.0.applying_reactions.set(applying);
- if applying == 0 {
- self.0.declarations_changed_during_apply.borrow_mut().clear();
- }
- }
- }
- self.applying_reactions.set(self.applying_reactions.get() + 1);
- Noting(self)
- }
}
impl Default for EngineMemo {
fn default() -> Self {
Self {
- views: Memo::new(super::bridge::FfiStyleRecordView::missing()),
- record_environments: Memo::new(0),
- dependency_flags: Memo::new(0),
+ views: Memo::new(std::ptr::null()),
held: Default::default(),
deferred: Default::default(),
described: Default::default(),
baselines: Default::default(),
atoms: Default::default(),
- staged_input: Default::default(),
- beside_flown_transaction: Default::default(),
+ identities: Default::default(),
+ projection: Default::default(),
+ unpublished: Default::default(),
declarations_changed_during_apply: Default::default(),
applying_reactions: Default::default(),
takes_transaction_to_apply: Default::default(),
- bound_failure_trace: Default::default(),
+ style_self_check: super::pipeline::SelfCheckSettings::from_environment(),
}
}
}
@@ -925,67 +1020,79 @@ impl Default for EngineMemo {
/// it.
#[derive(Default)]
pub(crate) struct HeldEnvironments {
- elements: HashMap<StyleNodeID, *const c_void>,
- pseudo_elements: HashMap<StyleNodeID, Vec<(u8, *const c_void)>>,
-}
+ elements: HashMap<StyleNodeID, HeldEnvironment>,
+ pseudo_elements: HashMap<StyleNodeID, Vec<(u8, HeldEnvironment)>>,
+}
+
+/// The custom-property environment an element or one of its synthetic pseudo-elements holds, as the address of the
+/// host's object for it, null for none, with whether it is the overlay of what the holder's own animations sample.
+/// That is the address's lowest bit, which the address of an object never sets.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(crate) struct HeldEnvironment(usize);
+
+impl HeldEnvironment {
+ const IS_ANIMATION_OVERLAY: usize = 1;
+ pub(crate) const NONE: Self = Self(0);
+
+ pub(crate) fn new(data: *const c_void, is_animation_overlay: bool) -> Self {
+ let address = data.expose_provenance();
+ debug_assert_eq!(
+ address & Self::IS_ANIMATION_OVERLAY,
+ 0,
+ "an object's address is aligned"
+ );
+ Self(
+ address
+ | if is_animation_overlay {
+ Self::IS_ANIMATION_OVERLAY
+ } else {
+ 0
+ },
+ )
+ }
-/// An environment a move left an element (`None`) or one of its synthetic pseudo-elements, by the address of the host's
-/// object for it. A moved element's entries come together, its own first.
-pub(crate) type MovedEnvironment = (StyleNodeID, Option<u8>, usize);
+ pub(crate) fn data(self) -> *const c_void {
+ std::ptr::with_exposed_provenance(self.0 & !Self::IS_ANIMATION_OVERLAY)
+ }
+
+ pub(crate) fn is_animation_overlay(self) -> bool {
+ self.0 & Self::IS_ANIMATION_OVERLAY != 0
+ }
+}
impl HeldEnvironments {
- fn element(&self, node: StyleNodeID) -> *const c_void {
- self.elements.get(&node).copied().unwrap_or(std::ptr::null())
+ fn element(&self, node: StyleNodeID) -> HeldEnvironment {
+ self.elements.get(&node).copied().unwrap_or(HeldEnvironment::NONE)
}
- fn pseudo_element(&self, node: StyleNodeID, pseudo: u8) -> *const c_void {
+ fn pseudo_element(&self, node: StyleNodeID, pseudo: u8) -> HeldEnvironment {
self.pseudo_elements
.get(&node)
.and_then(|environments| environments.iter().find(|&&(kind, _)| kind == pseudo))
- .map_or(std::ptr::null(), |&(_, data)| data)
+ .map_or(HeldEnvironment::NONE, |&(_, held)| held)
}
- fn pseudo_element_kinds(&self, node: StyleNodeID) -> u64 {
- self.pseudo_elements.get(&node).map_or(0, |environments| {
- environments.iter().fold(0, |kinds, &(kind, _)| kinds | (1 << kind))
- })
- }
-
- /// Follows `data`, null for none, which the host hands the engine for `node`.
- fn follow_element(&mut self, node: StyleNodeID, data: *const c_void) {
- if data.is_null() {
+ /// Follows `held`, which the host hands the engine for `node`.
+ fn follow_element(&mut self, node: StyleNodeID, held: HeldEnvironment) {
+ if held.data().is_null() {
self.elements.remove(&node);
} else {
- self.elements.insert(node, data);
+ self.elements.insert(node, held);
}
}
- /// Follows `data`, null for none, which the host hands the engine for a synthetic pseudo-element of `node`.
- fn follow_pseudo_element(&mut self, node: StyleNodeID, pseudo: u8, data: *const c_void) {
+ /// Follows `held`, which the host hands the engine for a synthetic pseudo-element of `node`.
+ fn follow_pseudo_element(&mut self, node: StyleNodeID, pseudo: u8, held: HeldEnvironment) {
let environments = self.pseudo_elements.entry(node).or_default();
environments.retain(|&(kind, _)| kind != pseudo);
- if !data.is_null() {
- environments.push((pseudo, data));
+ if !held.data().is_null() {
+ environments.push((pseudo, held));
}
if environments.is_empty() {
self.pseudo_elements.remove(&node);
}
}
- /// Follows what a move left the elements it moved.
- pub(crate) fn follow_moved(&mut self, moved: &[MovedEnvironment]) {
- for &(node, pseudo, address) in moved {
- let data = std::ptr::with_exposed_provenance(address);
- match pseudo {
- None => {
- self.follow_element(node, data);
- self.pseudo_elements.remove(&node);
- }
- Some(pseudo) => self.follow_pseudo_element(node, pseudo, data),
- }
- }
- }
-
/// Forgets what the nodes a transaction retired held, whose identities it `released`.
pub(crate) fn forget(&mut self, released: &[u32]) {
for node in released.iter().filter_map(|&raw| StyleNodeID::from_raw(raw)) {
@@ -993,6 +1100,13 @@ impl HeldEnvironments {
self.pseudo_elements.remove(&node);
}
}
+
+ fn heap_size(&self) -> usize {
+ use crate::heap_size::{map_bytes, vec_bytes};
+ map_bytes(&self.elements)
+ + map_bytes(&self.pseudo_elements)
+ + self.pseudo_elements.values().map(vec_bytes).sum::<usize>()
+ }
}
/// What one element owes of the style inputs the engine defers: its reactions and its inherited style groups.
@@ -1013,57 +1127,21 @@ pub(crate) struct DeferredInputs {
}
impl DeferredInputs {
+ fn heap_size(&self) -> usize {
+ crate::heap_size::vec_bytes(&self.inputs)
+ }
+
const ALL: (u8, u8) = (u8::MAX, u8::MAX);
fn search(&self, node: StyleNodeID) -> Result<usize, usize> {
self.inputs.binary_search_by_key(&node, |&(node, ..)| node)
}
- /// Folds the input `node` owes into the reaction the host is about to apply to it, as
- /// [`super::StyleEngine::absorb_element_style_input`] does, where the host knows the answer: `None` where an
- /// input it cannot name may move it.
- fn absorb(
- &mut self,
- node: StyleNodeID,
- reaction: u8,
- inherited_style_groups: u8,
- absorbs_any: bool,
- ) -> Option<u32> {
- use super::transaction::STYLE_REACTION_RECOMPUTE_DESCENDANT_STYLES as RECOMPUTE_DESCENDANTS;
- let known = self.search(node).ok();
- let (unnamed_reaction, unnamed_groups) = self.unnamed;
- if unnamed_reaction | unnamed_groups != 0 {
- let certain = match known {
- // The host knows nothing the element owes: a reaction that does not fold in every reaction an unnamed
- // input may carry answers the same, but for a descendant recompute, which folding adds to it.
- None if absorbs_any => {
- unnamed_reaction & !reaction == 0 && unnamed_groups & !inherited_style_groups == 0
- }
- None => unnamed_reaction & RECOMPUTE_DESCENDANTS == 0 || reaction & RECOMPUTE_DESCENDANTS != 0,
- Some(_) => false,
- };
- if !certain {
- return None;
- }
- }
- let Some(index) = known else {
- return Some(0);
- };
- let (_, owed_reaction, owed_groups) = self.inputs[index];
- if !absorbs_any
- && (owed_reaction & !reaction & !RECOMPUTE_DESCENDANTS != 0 || owed_groups & !inherited_style_groups != 0)
- {
- return Some(0);
- }
- self.inputs.remove(index);
- Some(u32::from(reaction | owed_reaction) | (u32::from(inherited_style_groups | owed_groups) << 8))
- }
-
/// Follows `queued`, in the order the engine applies the writes the host queues: a write held behind the drain of a
- /// style transaction's reactions reaches the engine after the drain's.
+ /// style update's reactions reaches the engine after the drain's.
fn follow(&mut self, queued: crate::render_state::QueuedStyleChange<'_>) {
use super::boundary::StyleChange;
- use super::transaction::{STYLE_REACTION_PUBLISHED_STYLE, STYLE_REACTION_RECOMPUTE_STYLE};
+ use super::input_types::{STYLE_REACTION_PUBLISHED_STYLE, STYLE_REACTION_RECOMPUTE_STYLE};
let (node, reaction, groups) = match *queued.change() {
StyleChange::RecordDerivedElementStyleInput {
node,
@@ -1079,27 +1157,6 @@ impl DeferredInputs {
}
return;
}
- StyleChange::NoteStyleReactionApplied {
- reaction,
- inherited_style_groups_changed,
- facts,
- ..
- } => {
- self.add_unnamed(super::child_reactions::derivable_child_reactions(
- reaction,
- inherited_style_groups_changed,
- facts,
- ));
- return;
- }
- StyleChange::RecordFlatTreeDescendantStyleInputs {
- reaction,
- inherited_style_groups,
- ..
- } => {
- self.add_unnamed((reaction, inherited_style_groups));
- return;
- }
StyleChange::RecordSizeContainerQueryDependents { .. }
| StyleChange::EvaluateSizeContainersNeedingEvaluationAfterLayout => {
self.add_unnamed((STYLE_REACTION_PUBLISHED_STYLE | STYLE_REACTION_RECOMPUTE_STYLE, 0));
@@ -1155,33 +1212,37 @@ impl DeferredInputs {
}
}
-/// The view of `style_record` the host has without asking: one it asked for before, or one the style transaction it
-/// drains carried. A published record never changes while it is live.
-pub(crate) fn known_style_record_view(
- host: &DocumentHost,
- style_record: u64,
-) -> Option<super::bridge::FfiStyleRecordView> {
+/// The record the host holds for `style_record` the host has without asking: one it asked for before, or one the style
+/// transaction it drains carried. A published record never changes while it is live.
+pub(crate) fn known_host_record(host: &DocumentHost, style_record: u64) -> Option<*const c_void> {
let memo = &host.engine_memo().views;
- if let Some(view) = memo.get(style_record) {
- return Some(view);
+ if let Some(style) = memo.get(style_record) {
+ return Some(style);
}
- let (view, _) = host.transaction_record(style_record)?;
- memo.set(style_record, view);
- Some(view)
+ let style = host.transaction_record(style_record)?;
+ memo.set(style_record, style);
+ Some(style)
}
/// The before-change style the current style stabilization epoch decides the transitions of `node`'s element, or of
-/// one of its pseudo-elements, against, or 0 before a pass has recorded one. The host knows it without asking: it
-/// follows every baseline it records in the engine.
+/// one of its pseudo-elements, against, or null before a pass has recorded one: a record the host takes a reference to
+/// before it lets go of the baselines. The host knows it without asking: it follows every baseline it records in the
+/// engine.
#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_transition_baseline(host: &DocumentHost, node: u32, pseudo_kind: u8) -> u64 {
- let Some(node) = StyleNodeID::from_raw(node) else {
- return 0;
- };
- host.engine_memo().baselines.borrow().get(node, pseudo_kind)
+pub extern "C" fn style_engine_transition_baseline(host: &DocumentHost, node: u32, pseudo_kind: u32) -> *const c_void {
+ let pseudo_kind = pseudo_kind as u8;
+ StyleNodeID::from_raw(node)
+ .and_then(|node| {
+ host.engine_memo()
+ .baselines
+ .borrow()
+ .get(node, pseudo_kind)
+ .map(std::sync::Arc::as_ptr)
+ })
+ .map_or(std::ptr::null(), |record| record.cast())
}
-/// Whether the engine has a style transaction pending, which the host knows without asking where it wrote nothing
+/// Whether the engine has a style update pending, which the host knows without asking where it wrote nothing
/// since its last job.
/// Hands the host every custom-property environment the engine holds for an element, with the element's style node,
/// for the host to name again what each hands down. The callbacks run outside the engine, so each may queue a write
@@ -1208,157 +1269,10 @@ pub extern "C" fn style_engine_for_each_element_custom_property_environment(
}
}
-/// What the engine knows of a node a layout update kept reaching without a style, for the panic that reports the
-/// update running out of passes.
-#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct FfiBoundFailureNodeFacts {
- pub is_live: bool,
- pub has_published_record: bool,
- /// The display the node's published record holds: 0 for no record, 1 for none, 2 for contents, 3 for any other.
- pub published_display: u8,
- /// The style nodes the engine inherits the node's style from and places it under in the flat tree, or 0.
- pub inheritance_parent: u32,
- pub flat_tree_parent: u32,
- pub owes_style_input: bool,
- pub ancestor_owes_style_input: bool,
- /// How a read-only demand of the node's record answers: 0 for a record, 1 for absent, 2 for refused, 3 for
- /// suspended, 4 for a parent that holds no record yet.
- pub read_demand_answer: u8,
- /// The records the engine derived for the element that the host has not taken: how many, and the records the
- /// last of the element's own moves between, or 0.
- pub pending_records: u8,
- pub pending_old_record: u64,
- pub pending_new_record: u64,
- /// The record the engine holds the node on and the custom-property environment it holds, or 0, and whether a
- /// cascade state is bound to the node's record.
- pub assigned_record: u64,
- pub environment: u64,
- pub has_cascade_state: bool,
-}
-
-/// Answers what the engine knows of `node` for the panic of a layout update that ran out of passes reaching it without
-/// a style. The demand it makes is read-only, so the engine is left as it was.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_bound_failure_node_facts(
- host: &DocumentHost,
- read: &BegunRead,
- node: u32,
-) -> FfiBoundFailureNodeFacts {
- with_engine(read, host, |engine| {
- let Some(node) = StyleNodeID::from_raw(node) else {
- return FfiBoundFailureNodeFacts {
- is_live: false,
- has_published_record: false,
- published_display: 0,
- inheritance_parent: 0,
- flat_tree_parent: 0,
- owes_style_input: false,
- ancestor_owes_style_input: false,
- read_demand_answer: 2,
- pending_records: 0,
- pending_old_record: 0,
- pending_new_record: 0,
- assigned_record: 0,
- environment: 0,
- has_cascade_state: false,
- };
- };
- let published_display = engine.element_published_box_facts(node).map_or(0, |facts| {
- if facts.display.is_none() {
- 1
- } else if facts.display.is_contents() {
- 2
- } else {
- 3
- }
- });
- let inheritance_parent = engine.retained.tree.inheritance_parent(node);
- let ancestor_owes_style_input = std::iter::successors(inheritance_parent, |&ancestor| {
- engine.retained.tree.inheritance_parent(ancestor)
- })
- .any(|ancestor| engine.host.owes_element_style_input(ancestor));
- let (pending_records, pending_old_record, pending_new_record) =
- engine.retained.bound_failure_pending_records(node);
- let read_demand_answer =
- match engine.answer_record_demand(node, RecordDemand::Element(FfiRecordDemand::ElementRead)) {
- Ok(RecordDemandAnswer::Record { .. }) => 0,
- Ok(RecordDemandAnswer::Absent { .. }) => 1,
- Err(Unanswered::Refused) => 2,
- Err(Unanswered::Suspended(_)) => 3,
- Err(Unanswered::AwaitsParent) => 4,
- };
- FfiBoundFailureNodeFacts {
- is_live: engine.retained.tree.is_live(node),
- has_published_record: engine.published_element_record(node).is_some(),
- published_display,
- inheritance_parent: inheritance_parent.map_or(0, StyleNodeID::raw),
- flat_tree_parent: engine.retained.tree.flat_tree_parent(node).map_or(0, StyleNodeID::raw),
- owes_style_input: engine.host.owes_element_style_input(node),
- ancestor_owes_style_input,
- read_demand_answer,
- pending_records,
- pending_old_record,
- pending_new_record,
- assigned_record: engine
- .retained
- .computed_group_sets
- .assigned_style_record(node)
- .map_or(0, |record| record.raw()),
- environment: engine
- .retained
- .computed_group_sets
- .custom_property_environment_identity(node)
- .unwrap_or(0),
- has_cascade_state: engine
- .retained
- .computed_group_sets
- .cascade_state(super::computed::ComputedStyleTarget::new(node, u8::MAX))
- .is_some(),
- }
- })
-}
-
-/// Appends what `line` says to the trace of a targeted style update of `host`'s document, where one is being
-/// traced.
-pub(crate) fn note_bound_failure_trace(host: &DocumentHost, line: impl FnOnce() -> String) {
- if let Some(trace) = host.engine_memo().bound_failure_trace.borrow_mut().as_mut() {
- if !trace.is_empty() {
- trace.push(' ');
- }
- trace.push_str(&line());
- }
-}
-
-/// Starts tracing the targeted style updates of `host`'s document, for the panic of a layout update that ran out of
-/// passes.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_begin_bound_failure_trace(host: &DocumentHost) {
- *host.engine_memo().bound_failure_trace.borrow_mut() = Some(String::new());
-}
-
-/// Ends the trace and writes it to `buffer`, NUL-terminated and cut to fit, answering its length.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_end_bound_failure_trace(host: &DocumentHost, buffer: ak::SpanMut<'_, u8>) -> usize {
- let trace = host
- .engine_memo()
- .bound_failure_trace
- .borrow_mut()
- .take()
- .unwrap_or_default();
- let buffer = buffer.into_slice();
- let length = trace.len().min(buffer.len().saturating_sub(1));
- buffer[..length].copy_from_slice(&trace.as_bytes()[..length]);
- if let Some(terminator) = buffer.get_mut(length) {
- *terminator = 0;
- }
- length
-}
-
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_has_pending_transaction(host: &DocumentHost, read: &BegunRead) -> bool {
match host.known_engine_facts() {
- Some(facts) => facts.has_pending_style_transaction,
+ Some(facts) => facts.has_pending_style_update,
None => with_engine(read, host, |engine| engine.has_pending_transaction()),
}
}
@@ -1403,6 +1317,13 @@ pub extern "C" fn style_engine_relational_arrival_keys(
/// Whether the engine defers any element style input, which the host knows without asking where it wrote nothing since
/// its last job.
+/// Whether the host knows what the engine answers of itself without asking: no write it queued since the last job may
+/// have moved it.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_knows_engine_facts(host: &DocumentHost) -> bool {
+ host.known_engine_facts().is_some()
+}
+
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_has_deferred_element_style_inputs(host: &DocumentHost, read: &BegunRead) -> bool {
match host.known_engine_facts() {
@@ -1423,28 +1344,6 @@ pub(crate) fn has_deferred_element_style_input(host: &DocumentHost, read: &Begun
with_engine(read, host, |engine| engine.has_deferred_element_style_input(style_node))
}
-/// The synthetic pseudo-elements `node` has rules for, as a C++ record's pseudo-style mask, or no bits when the engine
-/// holds no answer for the node. The host knows it without asking for an element whose row it composes in the
-/// transaction it took last, which answered it beside the row.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_published_pseudo_style_mask(host: &DocumentHost, read: &BegunRead, node: u32) -> u64 {
- host.transaction_pseudo_styles(node).map_or_else(
- || {
- with_engine(read, host, |engine| {
- StyleNodeID::from_raw(node).map_or(0, |node| engine.published_pseudo_style_mask(node))
- })
- },
- |styles| styles.mask,
- )
-}
-
-/// The synthetic pseudo-elements `node` has rules for that settling its pseudo-elements over the composition of its
-/// record leaves alone, where the style transaction the host drains composes its row on the host, and none otherwise.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_inert_pseudo_kinds(host: &DocumentHost, node: u32) -> u64 {
- host.transaction_pseudo_styles(node).map_or(0, |styles| styles.inert)
-}
-
/// Whether a size container waits for layout to be evaluated, which the host knows without asking where it wrote
/// nothing since its last job.
#[unsafe(no_mangle)]
@@ -1460,45 +1359,6 @@ pub extern "C" fn style_engine_has_size_containers_needing_evaluation_after_layo
}
}
-/// Folds the style input `node` owes into the reaction the host is about to apply to it, where the reaction covers it,
-/// and answers the merged reaction in the low byte and the merged inherited style groups in the next, or zero, as
-/// [`super::StyleEngine::absorb_element_style_input`] does. The host answers where it knows the answer, and the
-/// engine folds the input the same as it applies the host's writes.
-pub(crate) fn absorb_element_style_input(
- host: &DocumentHost,
- read: &BegunRead,
- style_node: StyleNodeID,
- reaction: u8,
- inherited_style_groups: u8,
- absorbs_any: bool,
-) -> u32 {
- // A job of the engine, or a frame in flight, moves what it defers beside what the host knows, and a fold held
- // behind the drain of a style transaction's reactions reaches the engine after the drain's writes.
- let known = (host.knows_engine_between_jobs() && !host.holds_style_writes()).then(|| {
- host.engine_memo()
- .deferred
- .borrow_mut()
- .absorb(style_node, reaction, inherited_style_groups, absorbs_any)
- });
- let Some(Some(absorbed)) = known else {
- return with_engine(read, host, |engine| {
- engine.absorb_element_style_input(style_node, reaction, inherited_style_groups, absorbs_any)
- });
- };
- // The engine folds what the host did, and an input the host knows nothing of that folding merges nothing into the
- // reaction, which only an unnamed one is.
- if absorbed != 0 || host.engine_memo().deferred.borrow().may_owe_unnamed() {
- host.queue_change(ArenaChange::Engine(EngineWrite::AbsorbElementStyleInput {
- node: style_node,
- reaction,
- inherited_style_groups,
- absorbs_any,
- absorbed,
- }));
- }
- absorbed
-}
-
/// Notes that the host rewrote the declarations of `node`, which a batch of reactions being applied reads.
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_note_element_declarations_changed(host: &DocumentHost, node: u32) {
@@ -1507,37 +1367,65 @@ pub extern "C" fn style_engine_note_element_declarations_changed(host: &Document
}
}
-/// A direct-mapped memo of one answer per key, which keeps the answers of the keys the host asked about last.
+type MemoSlot<T> = std::cell::Cell<(u64, T)>;
+
+/// A direct-mapped memo of one answer per key, which keeps the answers of the keys the host asked about last. It doubles
+/// with the answers it is told, up to its full size, so that a document of a few elements holds a small one.
pub(crate) struct Memo<T: Copy> {
- slots: [std::cell::Cell<(u64, T)>; Memo::<()>::SLOTS],
+ slots: std::cell::RefCell<Box<[MemoSlot<T>]>>,
+ answers_told: std::cell::Cell<usize>,
+ empty: T,
}
impl<T: Copy> Memo<T> {
- const SLOTS: usize = 256;
+ const FIRST_SLOTS: usize = 8;
+ const MAX_SLOTS: usize = 256;
/// No record has this identity: a base record's leaves the top bit clear, and an overlay's generation is below it.
const NO_KEY: u64 = u64::MAX;
fn new(empty: T) -> Self {
Self {
- slots: std::array::from_fn(|_| std::cell::Cell::new((Self::NO_KEY, empty))),
+ slots: std::cell::RefCell::new(Self::empty_slots(Self::FIRST_SLOTS, empty)),
+ answers_told: std::cell::Cell::new(0),
+ empty,
}
}
- fn slot(&self, key: u64) -> &std::cell::Cell<(u64, T)> {
- &self.slots[(key ^ (key >> 32)) as usize % Self::SLOTS]
+ fn empty_slots(count: usize, empty: T) -> Box<[MemoSlot<T>]> {
+ (0..count)
+ .map(|_| std::cell::Cell::new((Self::NO_KEY, empty)))
+ .collect()
+ }
+
+ fn slot(slots: &[MemoSlot<T>], key: u64) -> &MemoSlot<T> {
+ &slots[(key ^ (key >> 32)) as usize & (slots.len() - 1)]
}
pub(crate) fn get(&self, key: u64) -> Option<T> {
- let (held, answer) = self.slot(key).get();
+ let (held, answer) = Self::slot(&self.slots.borrow(), key).get();
(held == key).then_some(answer)
}
pub(crate) fn set(&self, key: u64, answer: T) {
- self.slot(key).set((key, answer));
+ let told = self.answers_told.get() + 1;
+ self.answers_told.set(told);
+ let mut slots = self.slots.borrow_mut();
+ if told > slots.len() && slots.len() < Self::MAX_SLOTS {
+ let grown = Self::empty_slots(slots.len() * 2, self.empty);
+ for slot in slots.iter() {
+ let (held, kept) = slot.get();
+ if held != Self::NO_KEY {
+ Self::slot(&grown, held).set((held, kept));
+ }
+ }
+ *slots = grown;
+ }
+ Self::slot(&slots, key).set((key, answer));
}
fn forget(&self, key: u64) {
- let slot = self.slot(key);
+ let slots = self.slots.borrow();
+ let slot = Self::slot(&slots, key);
let (held, answer) = slot.get();
if held == key {
slot.set((Self::NO_KEY, answer));
@@ -1545,7 +1433,7 @@ impl<T: Copy> Memo<T> {
}
fn forget_where(&self, forgets: impl Fn(u64) -> bool) {
- for slot in &self.slots {
+ for slot in self.slots.borrow().iter() {
let (held, answer) = slot.get();
if held != Self::NO_KEY && forgets(held) {
slot.set((Self::NO_KEY, answer));
@@ -1566,6 +1454,86 @@ pub extern "C" fn style_engine_native_rule_id(
})
}
+/// The name of the style memory owner at `index`, with its length written out, or null past the last one.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_memory_owner_name(index: usize, out_name_length: &mut usize) -> *const u8 {
+ let Some(owner) = super::memory_report::MemoryOwner::ALL.get(index) else {
+ return std::ptr::null();
+ };
+ let name = owner.name();
+ *out_name_length = name.len();
+ name.as_ptr()
+}
+
+/// What the document's style engine holds on the heap, by owner, as a job on the render owner: the bytes of each owner
+/// in the order `style_engine_memory_owner_name` names them, with the elements the document holds and those of them
+/// holding a style record.
+///
+/// # Safety
+///
+/// `out_bytes` must point at room for `capacity` values.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_memory_report(
+ host: &DocumentHost,
+ read: &crate::render_state::BegunRead,
+ out_bytes: *mut u64,
+ capacity: usize,
+ out_elements: &mut u64,
+ out_styled_elements: &mut u64,
+) -> usize {
+ use super::memory_report::MemoryOwner;
+ let mut report = with_engine_and_arena(read, host, |engine, arena| engine.memory_report(arena));
+ // NB: The host's rows share every chunk they were not written in since the barrier with the
+ // published projection the engine counted.
+ host.engine_memo().projection.borrow().report_memory(&mut report);
+ host.engine_memo().report_memory(&mut report);
+ // SAFETY: Guaranteed by the caller.
+ let out = unsafe { ak::slice_from_raw_parts_mut(out_bytes, capacity) };
+ for (slot, owner) in out.iter_mut().zip(MemoryOwner::ALL) {
+ *slot = report.bytes(*owner) as u64;
+ }
+ *out_elements = report.elements as u64;
+ *out_styled_elements = report.styled_elements as u64;
+ MemoryOwner::COUNT
+}
+
+/// A record of the allocations reports have counted, for [`style_engine_memory_beyond`].
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_memory_sizer_create() -> *mut c_void {
+ Box::into_raw(Box::<crate::heap_size::HeapSizer>::default()).cast()
+}
+
+/// # Safety
+///
+/// `sizer` must come from [`style_engine_memory_sizer_create`], and is not used again.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_memory_sizer_destroy(sizer: *mut c_void) {
+ // SAFETY: Guaranteed by the caller.
+ drop(unsafe { Box::from_raw(sizer.cast::<crate::heap_size::HeapSizer>()) });
+}
+
+/// What the document's style engine holds on the heap that the reports `sizer` has been through have not counted.
+///
+/// # Safety
+///
+/// `sizer` must come from [`style_engine_memory_sizer_create`].
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn style_engine_memory_beyond(
+ host: &DocumentHost,
+ read: &crate::render_state::BegunRead,
+ sizer: *mut c_void,
+) -> u64 {
+ use super::memory_report::{MemoryOwner, MemoryReport};
+ // SAFETY: Guaranteed by the caller.
+ let sizer = unsafe { &mut *sizer.cast::<crate::heap_size::HeapSizer>() };
+ let report = MemoryReport::past(std::mem::take(sizer));
+ let mut report = with_engine_and_arena(read, host, |engine, arena| engine.memory_report_into(report, arena));
+ host.engine_memo().projection.borrow().report_memory(&mut report);
+ host.engine_memo().report_memory(&mut report);
+ *sizer = std::mem::take(&mut report.sizer);
+ MemoryOwner::ALL.iter().map(|&owner| report.bytes(owner) as u64).sum()
+}
+
/// The name of the engine's counter at `index`, with its length and value written out, or null past the last one.
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_counter(
@@ -1592,20 +1560,20 @@ pub extern "C" fn style_engine_counter(
/// Decides what the transition step of `input`'s target does to its transitions, as the target's style changes from the
/// record `before` to the record `after` it installed, and hands `on_actions` one action per property it decided over.
-/// The style transaction the host drains decided the step beside the row of an element whose step nothing but the
+/// The style update the host drains decided the step beside the row of an element whose step nothing but the
/// engine's records decides; any other the render owner decides, reading the transform reference box of the target's
/// element's box as it does.
///
/// # Safety
///
-/// `host` must be a live document host, on its document's thread, and `input` must be valid. The values the actions
-/// point at live until `on_actions` returns.
+/// `host` must be a live document host, on its document's thread, `before` and `after` records the host holds, and
+/// `input` must be valid. The values the actions point at live until `on_actions` returns.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn style_engine_decide_transitions(
host: &DocumentHost,
read: &crate::render_state::BegunRead,
- before: u64,
- after: u64,
+ before: *const c_void,
+ after: *const c_void,
input: &FfiTransitionInput,
on_actions: unsafe extern "C" fn(*mut c_void, *const FfiTransitionAction, usize),
context: *mut c_void,
@@ -1615,6 +1583,13 @@ pub unsafe extern "C" fn style_engine_decide_transitions(
let existing = unsafe { ak::slice_from_raw_parts(input.existing_transitions, input.existing_transition_count) };
// SAFETY: As above.
let hand_over = |actions: &[FfiTransitionAction]| unsafe { on_actions(context, actions.as_ptr(), actions.len()) };
+ // SAFETY: As above.
+ let (Some(before), Some(after)) = (unsafe { super::bridge::retain_host_record(before) }, unsafe {
+ super::bridge::retain_host_record(after)
+ }) else {
+ debug_assert!(false, "a transition step decides over two records");
+ return;
+ };
let decision = TransitionDecision {
before,
after,
@@ -1642,11 +1617,11 @@ pub unsafe extern "C" fn style_engine_decide_transitions(
mod hover_replay_tests {
use super::*;
use crate::css::style::bridge::{FfiTreeRelations, element_adjustment_fact};
+ use crate::css::style::input_types::TreeRelations;
use crate::css::style::tests::{
assert_staged_hover_facts, discard_transaction, staged_hover_pending_shadow_fixture,
staged_hover_shadow_fixture,
};
- use crate::css::style::transaction::TreeRelations;
fn encoded(row: TreeRelations) -> FfiTreeRelations {
FfiTreeRelations {
@@ -1665,25 +1640,22 @@ mod hover_replay_tests {
after: Option<TreeRelations>,
hover: Option<Option<StyleNodeID>>,
) {
- EngineWrite::ApplyTransaction(Box::new(StagedInput {
- tree: vec![FfiTreeDelta {
- node: node.raw(),
- old_connected: true,
- new_connected: after.is_some(),
- old_relations: encoded(before),
- new_relations: encoded(after.unwrap_or(before)),
- }],
- hover,
- ..Default::default()
- }))
- .apply(engine);
+ let delta = FfiTreeDelta {
+ node: node.raw(),
+ old_connected: true,
+ new_connected: after.is_some(),
+ old_relations: encoded(before),
+ new_relations: encoded(after.unwrap_or(before)),
+ };
+ engine.apply_transaction_batch(&[delta], (&[], &[]), &[], &[], &[], &[]);
+ if let Some(target) = hover {
+ EngineWrite::MoveHover(target).apply(engine);
+ }
discard_transaction(engine);
}
fn move_hover(engine: &mut StyleEngine, target: Option<StyleNodeID>) {
- let mut input = StagedInput::default();
- input.stage_hover(target);
- EngineWrite::ApplyTransaction(Box::new(input)).apply(engine);
+ EngineWrite::MoveHover(target).apply(engine);
discard_transaction(engine);
}
@@ -1742,24 +1714,12 @@ mod hover_replay_tests {
let row = engine.settled_tree_relations(nodes[2]);
replay(&mut engine, nodes[2], row, Some(row), None);
assert_staged_hover_facts(&engine, &nodes, &[4, 5, 6]);
- crate::css::style::boundary::StyleChange::SetElementAdjustmentFacts {
- node: Some(nodes[4]),
- facts: 0,
- }
- .apply(&mut engine);
+ engine.set_element_adjustment_facts(nodes[4], 0);
assert_staged_hover_facts(&engine, &nodes, &[]);
- crate::css::style::boundary::StyleChange::SetElementAdjustmentFacts {
- node: Some(nodes[4]),
- facts: element_adjustment_fact::RENDERED_IN_TOP_LAYER,
- }
- .apply(&mut engine);
+ engine.set_element_adjustment_facts(nodes[4], element_adjustment_fact::RENDERED_IN_TOP_LAYER);
assert_staged_hover_facts(&engine, &nodes, &[4, 5, 6]);
move_hover(&mut engine, None);
- crate::css::style::boundary::StyleChange::SetElementAdjustmentFacts {
- node: Some(nodes[4]),
- facts: 0,
- }
- .apply(&mut engine);
+ engine.set_element_adjustment_facts(nodes[4], 0);
assert_eq!(engine.hover_target(), None);
assert_staged_hover_facts(&engine, &nodes, &[]);
}
@@ -1780,10 +1740,8 @@ mod hover_replay_tests {
#[test]
fn staged_hover_pending_document_element_arrival_accepts_the_chain() {
let (mut engine, nodes) = staged_hover_pending_shadow_fixture();
- assert_eq!(engine.tree.parent(nodes[2]), None);
- let mut input = StagedInput::default();
- input.stage_hover(Some(nodes[6]));
- EngineWrite::ApplyTransaction(Box::new(input)).apply(&mut engine);
+ assert_eq!(engine.projection.parent(nodes[2]), None);
+ EngineWrite::MoveHover(Some(nodes[6])).apply(&mut engine);
assert_staged_hover_facts(&engine, &nodes, &[1, 2, 4, 5, 6]);
discard_transaction(&mut engine);
assert_staged_hover_facts(&engine, &nodes, &[1, 2, 4, 5, 6]);
@@ -1795,18 +1753,15 @@ mod hover_replay_tests {
move_hover(&mut engine, Some(nodes[6]));
assert_staged_hover_facts(&engine, &nodes, &[1, 2, 4, 5, 6]);
let before = engine.settled_tree_relations(nodes[1]);
- EngineWrite::ApplyTransaction(Box::new(StagedInput {
- tree: vec![FfiTreeDelta {
- node: nodes[1].raw(),
- old_connected: true,
- new_connected: false,
- old_relations: encoded(before),
- new_relations: encoded(before),
- }],
- ..Default::default()
- }))
- .apply(&mut engine);
- assert!(engine.host.tree_staging.current_row(nodes[1], Some(before)).is_none());
+ let delta = FfiTreeDelta {
+ node: nodes[1].raw(),
+ old_connected: true,
+ new_connected: false,
+ old_relations: encoded(before),
+ new_relations: encoded(before),
+ };
+ engine.apply_transaction_batch(&[delta], (&[], &[]), &[], &[], &[], &[]);
+ assert!(engine.retained.projection.written_relations(nodes[1]).is_none());
assert_staged_hover_facts(&engine, &nodes, &[]);
discard_transaction(&mut engine);
}
@@ -1823,18 +1778,12 @@ mod hover_replay_tests {
let mut text = [0];
engine.allocate_text_style_nodes(&mut text);
let text = StyleNodeID::from_raw(text[0]).unwrap();
- crate::css::style::boundary::StyleChange::SetSlotAssignedNodes {
- slot: Some(nodes[5]),
- assigned: vec![text].into(),
- }
- .apply(&mut engine);
+ engine.set_slot_assigned_nodes(nodes[5], &[text]);
+ EngineWrite::SlotAssignedNodes.apply(&mut engine);
assert_staged_hover_facts(&engine, &nodes, &[]);
assert_eq!(engine.hover_target(), Some(nodes[9]));
- crate::css::style::boundary::StyleChange::SetSlotAssignedNodes {
- slot: Some(nodes[5]),
- assigned: Box::new([]),
- }
- .apply(&mut engine);
+ engine.set_slot_assigned_nodes(nodes[5], &[]);
+ EngineWrite::SlotAssignedNodes.apply(&mut engine);
assert_staged_hover_facts(&engine, &nodes, &[1, 2, 4, 5, 9]);
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
index 7751728d79f..a777622f570 100644
--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
@@ -648,6 +648,7 @@ impl RetainedState {
crate::css::computed_value_views::ComputedValuesView::of(view.base_payloads)
.display()
.is_none()
+ && !view.longhands().display_none_is_animated()
})
})
}
@@ -706,7 +707,6 @@ impl RetainedState {
#[must_use]
pub fn text_collapses_white_space(&self, node: StyleNodeID) -> Option<bool> {
let parent = self
- .tree
.inheritance_parent(node)
.filter(|parent| !self.tree.is_relation_only(*parent))?;
let view = self.published_style_record_view(self.published_element_record(parent))?;
diff --git a/Libraries/LibWeb/Rust/src/css/style/mod.rs b/Libraries/LibWeb/Rust/src/css/style/mod.rs
index 483d2a1d172..f8328c2351a 100644
--- a/Libraries/LibWeb/Rust/src/css/style/mod.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/mod.rs
@@ -59,100 +59,95 @@ macro_rules! define_id {
fn index(self) -> usize {
self.0 as usize
}
+
+ fn from_index(index: usize) -> Self {
+ Self(u32::try_from(index).expect("interned identity exceeds u32"))
+ }
}
};
}
pub(crate) mod animations;
mod atoms;
-pub mod batch_matcher;
pub(crate) mod boundary;
pub mod bridge;
pub mod cascade;
-mod catalog;
-mod child_reactions;
mod column;
pub mod compiler;
+pub(crate) mod component_matching;
mod computed;
mod container_queries;
+pub(in crate::css) mod kept_past_release;
+pub(crate) mod selector_analysis;
pub(crate) use container_queries::ContainerUnitBases;
mod custom_property_cascade;
mod custom_property_environments;
-#[cfg(test)]
-mod differential_tests;
+mod dom_reads;
pub(crate) mod effect_descriptions;
+mod element_declarations;
+mod element_host_facts;
mod engine;
pub mod engine_calls;
pub(crate) mod engine_sample;
-mod environment_move;
+#[cfg(test)]
pub mod exact_matcher;
-pub(crate) mod flight_style_rows;
+mod facts_types;
pub(crate) mod host_atoms;
pub(crate) mod style_job;
pub(crate) use crate::fast_hash;
mod engine_handle;
mod flush;
-mod fnv;
mod font_resolution;
pub(crate) mod hover_lane;
pub mod identities;
-pub mod impact;
pub mod index;
-mod input_routing;
mod inputs;
-pub(crate) use inputs::{give_up_custom_property_data_let_go_beside_the_host, next_declaration_block_version};
+mod installed_records;
+pub(crate) use inputs::next_declaration_block_version;
pub mod instrumentation;
mod intern_table;
pub(crate) mod layout_style;
-mod matching;
-mod native_rules;
+pub(crate) mod memory_report;
pub mod order;
mod ordering;
-mod partial_view;
-mod planning;
+pub(crate) mod pointer_key;
pub(crate) mod position_try;
-mod prefix;
-pub mod program;
-mod program_updates;
+mod process_style;
+mod projection_writes;
mod publication;
mod random_bases;
pub mod reaction_application;
mod resource_contexts;
-mod routing;
pub(crate) mod rule_writes;
-mod sorted_merge;
mod style_invalidation;
pub(crate) use style_invalidation::SampleBounds;
+pub(crate) mod pipeline;
mod transition_baselines;
-mod user_agent_selectors;
-pub(crate) use computed::{ENGINE_INHERITED_GROUP_COUNT, ReleasedAnimationOverlayRecords, StyleRecordLease};
+pub(crate) use atoms::{AtomLease, AtomLeases, ProcessAtoms, process_atoms};
+pub(crate) use computed::{
+ ENGINE_INHERITED_GROUP_COUNT, ReleasedAnimationOverlayRecords, StyleRecordLease, StyleRecordView, ViewLonghands,
+};
+pub(crate) use process_style::ProcessStyle;
pub(crate) use publication::RecordDemand;
pub(crate) use transition_baselines::{InheritedAnimatedValue, TransitionBaselines};
+pub mod input_types;
pub mod relative_selector;
pub mod selector;
pub mod selector_evaluation;
mod shareable;
-mod shared_vector;
-mod sheet_occurrences;
mod size_container_invalidation;
mod specified_value;
-pub mod transaction;
mod transaction_view;
pub mod tree;
mod weak_pool;
use atoms::DocumentAtoms;
use atoms::ReclaimedStyleAtom;
-use catalog::*;
-use column::BitColumn;
use column::Column;
-use container_queries::PublishedContainerVerdict;
use fast_hash::FastMap as HashMap;
use fast_hash::FastSet as HashSet;
-use planning::*;
use smallvec::SmallVec;
-use std::collections::VecDeque;
-use std::hash::{Hash, Hasher};
+use std::hash::Hash;
use std::sync::Arc;
use std::sync::Mutex;
@@ -166,7 +161,7 @@ pub(crate) type SelectorAttributeNames = Arc<HashSet<StyleAtomID>>;
/// elements in a display:none subtree out of the engine's tree for as long as nothing could observe them.
#[derive(Clone, Default)]
pub(crate) struct RelationalArrivalKeys {
- keys: HashSet<RoutingKey>,
+ keys: HashSet<DispatchKey>,
pub(crate) names: Vec<usize>,
pub(crate) states: Vec<u8>,
pub(crate) reached_by_any_arrival: bool,
@@ -176,627 +171,82 @@ use crate::css::cascaded_properties::CascadeOrigin;
#[cfg(test)]
use crate::css::cascaded_properties::CascadedPropertyStore;
use crate::css::computed_values::computed_group_output_mask;
-use crate::css::host_shared::{HostShared, SharedPayload};
-use crate::css::selector::CompiledSelector;
+use crate::css::host_shared::HostShared;
use crate::css::style_value::RetainedStyleValueData;
use crate::css::style_value::StyleValueData;
use bridge::FfiStyleDelta as PublishedStyleDeltaRecord;
-use bridge::FfiStyleDeltaDamage;
-use bridge::FfiStyleDeltaGap;
use instrumentation::Counter;
use instrumentation::Counters;
-use exact_matcher::ExactMatchContext;
-use exact_matcher::ExactMatcher;
-
pub use engine_handle::StyleEngineHandle;
pub use inputs::{NaturalSize, PublishedBoxFacts, PublishedTextSource, ReplacedContentInput, TextStyleParentFacts};
-use batch_matcher::AncestorRequirements;
-use batch_matcher::AncestorRequirementsCache;
-use batch_matcher::BatchMatchState;
-use batch_matcher::BatchMatcher;
-use batch_matcher::CountRuleMatchEmission;
-use batch_matcher::RuleMatch;
-use batch_matcher::RuleMatches;
-use batch_matcher::append_prefix_matches;
-use batch_matcher::append_retained_matches;
-use batch_matcher::scope_dispatch_shape_and_rules;
-use cascade::CascadeCandidate as OrderedCascadeCandidate;
+use crate::css::declaration_block::DeclarationEntry;
use cascade::CascadeOperator;
use cascade::CascadePriority;
-use cascade::CascadeStateID;
-use cascade::CascadeStratum;
use cascade::ElementAttachment;
use cascade::PriorityInputs;
-use cascade::PropertyWinner;
-use cascade::PropertyWinnerUpdate;
-use cascade::SpecifiedValueID;
-use cascade::SpecifiedWinnerKey;
-use cascade::Top1Cascade;
-use cascade::WinnerGroupKey;
-use cascade::WinnerGroups;
use cascade::WinnerSource;
-use compiler::NamespaceScope;
-use compiler::ScopeChain;
-use compiler::SelectorCompiler;
use computed::ComputedGroupSets;
-use impact::AttributionSweep;
-use impact::ImpactRegion;
-use impact::ImpactRegionBatch;
-use impact::ImpactRegions;
-use impact::Plan;
-use impact::SELECTIVE_SHARE_DIVISOR;
-use impact::TransactionTopology;
-use impact::choose_plan;
-use index::DependencyPostingKey;
-use index::DispatchCandidateWorkspace;
use index::DispatchKey;
-use index::ElementFactStore;
-use index::FeaturePostings;
+#[cfg(test)]
use index::FeatureValue;
use index::LocalFeatureKey;
-use index::MatchingFactBatch;
-use index::PostingKey;
-use index::RuleDispatch;
use index::StyleAtomID;
-use index::StyleNodeFacts;
-use input_routing::routing_keys_for_input;
-use partial_view::Lookup;
-use prefix::PrefixDeltaArena;
-use prefix::PrefixEnteringDeltas;
-use prefix::PrefixEvaluation;
-use prefix::PrefixMatchSetID;
-use prefix::PrefixProducer;
-use prefix::PrefixStateCache;
-use prefix::PrefixStates;
-use prefix::PrefixTransitionLookup;
-use program::CascadeLayerID;
-use program::CustomDeclaration;
-use program::DeclarationBlockID;
-use program::DeclaredProperty;
-use program::EntryID;
-use program::RuleID;
-use program::RuleKind;
-use program::RuleVersion;
-use program::SelectorProgramID;
-use program::SheetID;
-use program::StyleSheetObjectID;
-use program::StyleSheetProgram;
-use relative_selector::RelationalWitnessGap;
-use relative_selector::RelationalWitnessKey;
-use relative_selector::RelationalWitnesses;
-use relative_selector::RelativeAxis;
-use relative_selector::RelativeQueryID;
-use relative_selector::WitnessEffect;
-use relative_selector::possible_anchors;
-use relative_selector::possible_hosting_anchors;
-use relative_selector::traversal_anchor;
+use input_types::ElementDeclarationKind;
+use input_types::ElementStyleInput;
+use input_types::InputKey;
+use input_types::InputValue;
+use input_types::PendingElementInputs;
+use input_types::StateFact;
+use input_types::StyleUpdate;
+use input_types::StyleUpdateVersion;
+use input_types::TreeRelations;
+use pipeline::rule_store::CascadeLayerID;
+use pipeline::rule_store::CustomDeclaration;
+use pipeline::rule_store::DeclarationBlockID;
+use pipeline::rule_store::ProgramStaging;
+use pipeline::rule_store::RuleID;
+use pipeline::rule_store::RuleKind;
+use pipeline::rule_store::RuleStore;
+use pipeline::rule_store::RuleVersion;
+use pipeline::rule_store::SheetID;
+use pipeline::rule_store::SheetRuleReplacement;
+use pipeline::rule_store::StyleScopeID;
use selector::Incomplete;
-use selector::InverseStep;
-use selector::LiveRelationalRoute;
-use selector::MatchEvaluationSide;
-use selector::MatchEvaluator;
use selector::MatchScratch;
-use selector::NthPosition;
-use selector::RelativeAnchor;
-use selector::RouteID;
-use selector::RoutingKey;
-use selector::RoutingRegistry;
-use selector::SelectorEntry;
-use selector::SelectorOp;
-use selector::SelectorProgram;
-use selector::SelectorPrograms;
-use selector::SiblingEntry;
-use selector::SiblingSequenceGeometry;
use selector::Specificity;
-use selector::SubjectPosition;
-use specified_value::SpecifiedValues;
-use transaction::ElementDeclarationKind;
-use transaction::InputKey;
-use transaction::InputKind;
-use transaction::InputValue;
-use transaction::NormalizationJournal;
-use transaction::NormalizedInput;
-use transaction::ProgramJoinDelta;
-use transaction::ProgramJoinDeltaKind;
-use transaction::ProgramVersion;
-use transaction::RuleDeclarationChange;
-use transaction::RuleField;
-use transaction::StateFact;
-use transaction::StyleTransaction;
-use transaction::StyleTransactionVersion;
-use transaction::TopologyAxis;
-use transaction::TreeRelations;
-use transaction_view::FeatureFluxColumn;
-use transaction_view::PrefixFactTransition;
+use specified_value::CanonicalValues;
use transaction_view::TransactionFactSide;
-use transaction_view::TransactionFactView;
+use tree::HostTree;
use tree::SegmentedNodeColumn;
use tree::StyleNodeID;
-use tree::StyleNodeTree;
-use tree::TreeRelationStaging;
use tree::TreeScopeID;
-/// A candidate source at most this large is always worth enumerating, whatever share of the
-/// document it is. Proving membership for a handful of candidates cannot lose to streaming a
-/// region whose size is unknown.
-const SMALL_CANDIDATE_SOURCE: usize = 64;
-// Point removal wins for a tiny plan delta. Larger deltas use one linear retain pass instead of
-// repeatedly shifting the remaining posting.
-const MAX_POINT_REMOVED_EXACT_NODES: usize = 64;
-
-/// Missing prefix transitions installed after one selective traversal or during one convergence
-/// pass. This bounds speculative work while letting repeated asks grow retained coverage.
-const PREFIX_TRANSITION_CACHE_COMPLETION_BUDGET: usize = 32;
-
-/// How many previous-sibling steps a retained-witness check walks before giving up and routing
-/// conservatively, which keeps the check constant-time however long a sibling sequence is.
-const RETAINED_WITNESS_SIBLING_STEPS: usize = 64;
-
-/// How much of a sibling sequence the first fact batch asks for. A scan that stops early wastes at
-/// most this many rows, which is cheaper than the restart a smaller window would cost.
-const INITIAL_SIBLING_FACT_WINDOW: usize = 8;
-
-mod verification {
- use super::MatchAnswerID;
- use super::RetainedState;
- use super::RuleMatch;
- use super::StyleNodeID;
- #[cfg(test)]
- use std::cell::Cell;
- use std::sync::OnceLock;
-
- static STYLE_ANSWER_PATCH: OnceLock<bool> = OnceLock::new();
- static SELECTOR_TRUTH_DERIVATION: OnceLock<bool> = OnceLock::new();
- static CASCADE_WINNERS: OnceLock<bool> = OnceLock::new();
- static STYLE_PLAN_PROVENANCE: OnceLock<bool> = OnceLock::new();
- static PUBLISHED_STYLE_TRANSACTION: OnceLock<bool> = OnceLock::new();
- static PREFIX_RELATION: OnceLock<bool> = OnceLock::new();
-
- #[cfg(test)]
- thread_local! {
- static SELECTOR_TRUTH_DERIVATION_OVERRIDE: Cell<bool> = const { Cell::new(false) };
- }
-
- fn enabled(gate: &OnceLock<bool>, variable: &str) -> bool {
- *gate.get_or_init(|| std::env::var_os(variable).is_some())
- }
-
- pub(super) struct StyleAnswerVerifier<'a> {
- engine: &'a mut RetainedState,
- }
-
- impl StyleAnswerVerifier<'_> {
- pub(super) fn verify_match_answer(&mut self, answer: &[RuleMatch], node: StyleNodeID, description: &str) {
- let cold = self
- .engine
- .exact_match_answer_for_verification(node)
- .expect("cold matching must answer wherever a retained answer did");
- assert_eq!(answer, cold, "{description} differs from cold matching for {node:?}");
- }
-
- pub(super) fn verify_cascade_answer(&mut self, answer: &[RuleMatch], node: StyleNodeID, description: &str) {
- let (cold, _) = self
- .engine
- .exact_cascade_answer_for_verification(node)
- .expect("cold matching must answer wherever a retained answer did");
- assert_eq!(answer, cold, "{description} differs from cold matching for {node:?}");
- }
-
- pub(super) fn verify_retained_cascade_input(
- &mut self,
- effects: &super::AnswerEffects,
- node: StyleNodeID,
- cascade_input: MatchAnswerID,
- ) {
- self.engine.verify_retained_cascade_input(effects, node, cascade_input);
- }
- }
-
- /// Re-derive every patched or reused retained answer cold and compare it. The callback receives
- /// only the verifier capability, so it cannot publish through or otherwise mutate the engine.
- pub(super) fn style_answer_patch(engine: &mut RetainedState, check: impl FnOnce(&mut StyleAnswerVerifier<'_>)) {
- if enabled(&STYLE_ANSWER_PATCH, "LIBWEB_VERIFY_STYLE_ANSWER_PATCH") {
- check(&mut StyleAnswerVerifier { engine });
- }
- }
-
- pub(super) fn selector_truth_derivation_is_enabled() -> bool {
- #[cfg(test)]
- if SELECTOR_TRUTH_DERIVATION_OVERRIDE.get() {
- return true;
- }
- *SELECTOR_TRUTH_DERIVATION.get_or_init(|| {
- std::env::var_os("LIBWEB_VERIFY_STYLE_ANSWER_PATCH").is_some()
- || std::env::var_os("LIBWEB_VERIFY_SELECTOR_TRUTH_DERIVATION").is_some()
- })
- }
-
- #[cfg(test)]
- pub(super) fn with_selector_truth_derivation_enabled<T>(run: impl FnOnce() -> T) -> T {
- struct RestoreOverride<'a> {
- value: &'a Cell<bool>,
- previous: bool,
- }
-
- impl Drop for RestoreOverride<'_> {
- fn drop(&mut self) {
- self.value.set(self.previous);
- }
- }
-
- SELECTOR_TRUTH_DERIVATION_OVERRIDE.with(|value| {
- let restore = RestoreOverride {
- previous: value.replace(true),
- value,
- };
- let result = run();
- drop(restore);
- result
- })
- }
-
- /// Compare complete retained cascade winners with the legacy cascade output.
- pub(super) fn cascade_winners(engine: &RetainedState, check: impl FnOnce(&RetainedState)) {
- if enabled(&CASCADE_WINNERS, "LIBWEB_VERIFY_CASCADE_WINNERS") {
- check(engine);
- }
- }
-
- /// Require every scoped style transaction output to name semantic provenance.
- pub(super) fn style_plan_provenance(engine: &RetainedState, check: impl FnOnce(&RetainedState)) {
- if enabled(&STYLE_PLAN_PROVENANCE, "LIBWEB_VERIFY_STYLE_PLAN_PROVENANCE") {
- check(engine);
- }
- }
-
- /// Require a published style transaction to complete without another `match_element()` call.
- pub(super) fn published_style_transaction(engine: &RetainedState, check: impl FnOnce(&RetainedState)) {
- if enabled(
- &PUBLISHED_STYLE_TRANSACTION,
- "LIBWEB_VERIFY_PUBLISHED_STYLE_TRANSACTION",
- ) {
- check(engine);
- }
- }
-
- pub(super) fn prefix_relation_is_enabled() -> bool {
- enabled(&PREFIX_RELATION, "LIBWEB_VERIFY_PREFIX_RELATION")
- }
-}
-
-use verification::{
- cascade_winners as verify_cascade_winners, published_style_transaction as verify_published_style_transaction,
- selector_truth_derivation_is_enabled as verify_selector_truth_derivation_is_enabled,
- style_answer_patch as verify_style_answer_patch, style_plan_provenance as verify_style_plan_provenance,
-};
-
-fn exact_tree_routing_is_selective(changed_nodes: usize, document_nodes: usize) -> bool {
- changed_nodes <= SMALL_CANDIDATE_SOURCE
- || changed_nodes.saturating_mul(SELECTIVE_SHARE_DIVISOR) <= document_nodes.max(1)
-}
-
-/// The posting an entry's candidates can be enumerated from, or `None` for an entry with no
-/// selective rightmost feature.
-/// Which region holds the anchors that can see a witness across one relative axis.
-///
-/// A child query's anchor is the witness's own parent, and a descendant query's is any of its
-/// ancestors; naming the ancestors covers both, and covering is what a plan needs. The two subtree
-/// axes reach an anchor that is a sibling of some ancestor of the witness, which no single region
-/// names, so they are left to the scope.
-fn anchor_region_for(axis: RelativeAxis) -> Option<fn(StyleNodeID) -> ImpactRegion> {
- match axis {
- RelativeAxis::Descendant | RelativeAxis::Child => Some(ImpactRegion::Ancestors),
- RelativeAxis::NextSibling => Some(ImpactRegion::PreviousSibling),
- RelativeAxis::FollowingSibling => Some(ImpactRegion::PrecedingSiblings),
- RelativeAxis::NextSiblingSubtree | RelativeAxis::FollowingSiblingSubtree => None,
- }
-}
-
-/// Which way a child sequence changed for one element.
-#[derive(Clone, Copy, PartialEq, Eq)]
-enum SequenceSide {
- /// The element joined the sequence and publishes its arriving facts.
- Arrived,
- /// An already connected element joined from another parent without republishing its facts.
- Reparented,
- /// The element left it, taking with it any witness it was.
- Departed,
- /// The element stayed in the sequence and moved within it.
- Moved,
-}
-
-fn for_each_matching_scope(
- scope: TreeScopeID,
- inner_scope: Option<TreeScopeID>,
- slotted_scopes: &[TreeScopeID],
- part_scopes: &[TreeScopeID],
- mut ask: impl FnMut(TreeScopeID, ExactMatchContext) -> Result<(), Incomplete>,
-) -> Result<(), Incomplete> {
- ask(scope, ExactMatchContext::Ordinary)?;
- if let Some(inner_scope) = inner_scope {
- ask(inner_scope, ExactMatchContext::Host)?;
- }
- for &slotted_scope in slotted_scopes {
- ask(slotted_scope, ExactMatchContext::Slotted)?;
- }
- for &part_scope in part_scopes {
- ask(part_scope, ExactMatchContext::Part)?;
- }
- Ok(())
-}
-
-#[derive(Clone)]
-struct StagedFieldRow<V> {
- before: V,
- after: V,
- dirty: bool,
-}
-
-/// Sparse staging for one program field. The first write freezes `before`, later writes replace
-/// `after`, and `take_dirty()` applies only the last write while retaining both sides for
-/// `ProgramStaging::delta()`.
-#[derive(Clone)]
-struct StagedField<K, V> {
- rows: HashMap<K, StagedFieldRow<V>>,
- touched: Vec<K>,
- dirty_count: usize,
-}
-
-impl<K, V> Default for StagedField<K, V> {
- fn default() -> Self {
- Self {
- rows: HashMap::default(),
- touched: Vec::new(),
- dirty_count: 0,
- }
- }
-}
-
-impl<K: Copy + Eq + Hash + Ord, V: Clone> StagedField<K, V> {
- fn current(&self, key: K, committed: impl FnOnce() -> V) -> V {
- self.side(key, TransactionFactSide::After, committed)
- }
-
- fn after(&self, key: K) -> Option<&V> {
- self.rows.get(&key).map(|row| &row.after)
- }
-
- fn side(&self, key: K, side: TransactionFactSide, resident: impl FnOnce() -> V) -> V {
- let row = self.rows.get(&key);
- match (side, row) {
- (TransactionFactSide::Before, Some(row)) => row.before.clone(),
- (TransactionFactSide::After, Some(row)) => row.after.clone(),
- _ => resident(),
- }
- }
-
- fn stage(&mut self, key: K, before: impl FnOnce() -> V, after: V) {
- match self.rows.entry(key) {
- std::collections::hash_map::Entry::Occupied(mut entry) => {
- let row = entry.get_mut();
- row.after = after;
- if !row.dirty {
- row.dirty = true;
- self.dirty_count += 1;
- }
- }
- std::collections::hash_map::Entry::Vacant(entry) => {
- entry.insert(StagedFieldRow {
- before: before(),
- after,
- dirty: true,
- });
- self.touched.push(key);
- self.dirty_count += 1;
- }
- }
- }
-
- fn take_dirty(&mut self) -> Vec<(K, V)> {
- if self.is_empty() {
- return Vec::new();
- }
- let mut dirty = Vec::with_capacity(self.dirty_count);
- for &key in &self.touched {
- let row = self.rows.get_mut(&key).unwrap();
- if row.dirty {
- dirty.push((key, row.after.clone()));
- row.dirty = false;
- }
- }
- self.dirty_count = 0;
- dirty.sort_unstable_by_key(|(key, _)| *key);
- dirty
- }
-
- fn is_empty(&self) -> bool {
- self.dirty_count == 0
- }
-
- fn clear(&mut self) {
- self.rows.clear();
- self.touched.clear();
- // Keep small edit buffers warm, but do not retain stylesheet-loading capacity for the
- // lifetime of every document. These rows are only needed until transaction release.
- if self.rows.capacity() * size_of::<(K, StagedFieldRow<V>)>() > 4096 {
- self.rows = HashMap::default();
- }
- if self.touched.capacity() * size_of::<K>() > 4096 {
- self.touched = Vec::new();
- }
- self.dirty_count = 0;
- }
-
- fn pairs(&self) -> impl Iterator<Item = (K, &V, &V)> {
- self.touched.iter().map(|&key| {
- let row = self.rows.get(&key).unwrap();
- (key, &row.before, &row.after)
- })
- }
-}
-
-#[derive(Default)]
-struct ProgramStagingDelta {
- sheets: Vec<SheetID>,
- selector_programs: Vec<SelectorProgramID>,
- arriving_rules: Vec<RuleID>,
- departed_scopes: Vec<(SheetID, TreeScopeID)>,
-}
-
-/// Program transaction staging. Every field preserves its first before value and last-writer
-/// after value until release; `delta()` may read those pairs after the final values are applied.
-#[derive(Clone, Default)]
-struct ProgramStaging {
- rule_conditions: StagedField<RuleID, bool>,
- sheet_conditions: StagedField<SheetID, bool>,
- sheet_enabled: StagedField<SheetID, bool>,
- rule_declarations: StagedField<RuleID, PendingRuleDeclarations>,
- rule_versions: StagedField<RuleID, RuleVersion>,
- rule_in_a_layer: StagedField<RuleID, bool>,
- rule_gated_by_container_query: StagedField<RuleID, bool>,
- rule_liveness: StagedField<RuleID, bool>,
- layer_orders: StagedField<TreeScopeID, HashMap<CascadeLayerID, u32>>,
- scopes_using_document_sheets: StagedField<TreeScopeID, bool>,
- sheets_in_scope: StagedField<TreeScopeID, Vec<SheetID>>,
- rule_change_is_carried_by_sheet: HashMap<SheetID, bool>,
- base_version: Option<ProgramVersion>,
- rule_declaration_changes: Vec<PendingRuleDeclarationChange>,
- rules_with_incomplete_old_declarations: Vec<RuleID>,
- sheet_rule_replacements: Column<Option<SheetRuleReplacement>>,
-}
-
-impl ProgramStaging {
- fn is_dirty(&self) -> bool {
- !self.rule_conditions.is_empty()
- || !self.sheet_conditions.is_empty()
- || !self.sheet_enabled.is_empty()
- || !self.rule_declarations.is_empty()
- || !self.rule_versions.is_empty()
- || !self.rule_in_a_layer.is_empty()
- || !self.rule_gated_by_container_query.is_empty()
- || !self.rule_liveness.is_empty()
- || !self.layer_orders.is_empty()
- || !self.scopes_using_document_sheets.is_empty()
- || !self.sheets_in_scope.is_empty()
- || self.sheet_rule_replacements.iter().any(Option::is_some)
- }
-
- fn clear(&mut self) {
- self.rule_conditions.clear();
- self.sheet_conditions.clear();
- self.sheet_enabled.clear();
- self.rule_declarations.clear();
- self.rule_versions.clear();
- self.rule_in_a_layer.clear();
- self.rule_gated_by_container_query.clear();
- self.rule_liveness.clear();
- self.layer_orders.clear();
- self.scopes_using_document_sheets.clear();
- self.sheets_in_scope.clear();
- self.rule_change_is_carried_by_sheet.clear();
- self.base_version = None;
- self.rule_declaration_changes.clear();
- self.rules_with_incomplete_old_declarations.clear();
- for index in 0..self.sheet_rule_replacements.len() {
- self.sheet_rule_replacements[index] = None;
- }
- }
-
- fn delta(&self) -> ProgramStagingDelta {
- let mut delta = ProgramStagingDelta::default();
- delta
- .sheets
- .extend(self.sheet_conditions.pairs().map(|(sheet, _, _)| sheet));
- delta
- .sheets
- .extend(self.sheet_enabled.pairs().map(|(sheet, _, _)| sheet));
- for (scope, before, after) in self.sheets_in_scope.pairs() {
- for &sheet in before.iter().filter(|sheet| !after.contains(sheet)) {
- delta.sheets.push(sheet);
- delta.departed_scopes.push((sheet, scope));
- }
- delta
- .sheets
- .extend(after.iter().copied().filter(|sheet| !before.contains(sheet)));
- }
- delta.sheets.sort_unstable();
- delta.sheets.dedup();
- delta.departed_scopes.sort_unstable();
- delta.departed_scopes.dedup();
-
- delta.selector_programs.extend(
- self.rule_versions
- .pairs()
- .filter(|(_, before, after)| before.selector_program != after.selector_program)
- .filter_map(|(_, before, _)| before.selector_program),
- );
- delta.selector_programs.sort_unstable_by_key(|program| program.0);
- delta.selector_programs.dedup();
-
- delta.arriving_rules.extend(
- self.rule_liveness
- .pairs()
- .filter_map(|(rule, before, after)| (!before && *after).then_some(rule)),
- );
- delta.arriving_rules.sort_unstable();
- delta.arriving_rules.dedup();
- delta
- }
-}
-
-/// One match of an answer a transaction publishes, as the custom-property cascade reads it.
-#[derive(Clone, Copy)]
-pub(super) struct BatchCustomPropertyMatch {
- rule: RuleID,
- tree_scope: TreeScopeID,
- specificity: Specificity,
- scope_proximity: u32,
- pseudo: Option<u16>,
-}
-
/// Long-lived engine state: the document, its program, derived results and cross-flush
/// caches. This is the whole read side of an evaluation step; it holds no
-/// host handle, no journal intake and no borrowed FFI result storage.
+/// host handle, no pending input intake and no borrowed FFI result storage.
#[derive(Clone)]
pub struct RetainedState {
/// What the engine counts of its own decisions.
counters: Counters,
- deferred_pseudo_elements: u64,
- tree: crate::fork::ForkShared<StyleNodeTree>,
+ /// The elements the host shows each kind of highlight in.
+ highlight_observers: pipeline::highlight_observers::HighlightObservers,
+ tree: crate::fork::ForkShared<HostTree>,
+ /// The depth of the deepest element the tree ever held, which the document's host reads.
+ deepest_element: Arc<std::sync::atomic::AtomicU32>,
/// Where the hover is.
hover: hover_lane::Hover,
- program: crate::fork::ForkShared<StyleSheetProgram>,
- native_rules: crate::fork::ForkShared<native_rules::NativeRuleRegistry>,
+ rules: crate::fork::ForkShared<RuleStore>,
+ /// The style data the engine shares with the other engines of the process.
+ process_style: Arc<process_style::ProcessStyle>,
/// The last declaration block version minted, by the engine or by its document's host, which mints without it.
declaration_block_version: Arc<std::sync::atomic::AtomicU32>,
- /// Whether the last transaction taken planned nothing but derived child reactions.
- last_transaction_only_derived_child_reactions: bool,
- /// Sheets whose rules currently have no entry points in the routing registry. A detached
- /// sheet's rules decide nothing, so routing every input past their entry points is pure cost
- /// that grows with every sheet that ever came and went.
- sheets_excluded_from_routing: BitColumn,
- /// Detached sheets the host keeps compiled because it expects them back. Their routes stay registered, since
- /// shedding them would only have reattachment derive them all again.
- sheets_kept_for_reattachment: BitColumn,
- /// Whether a sheet detached since the last routing shed, so the registry may hold entry
- /// points for rules that can no longer decide.
- routing_needs_detachment_sweep: bool,
- match_workspace: MatchScratch,
- /// Scratch for the fact rows one exact candidate evaluation covers, reused across candidates.
- exact_covered_scratch: Vec<StyleNodeID>,
- cascade_compaction_scratch: ordering::CascadeCompactionWorkspace,
- /// Monotonic identity assigned to each non-empty normalized style transaction.
- next_style_transaction_version: StyleTransactionVersion,
+ /// Monotonic identity assigned to each non-empty normalized style update.
+ next_style_update_version: StyleUpdateVersion,
/// Latest document-wide scalar computation facts, copied at the transaction boundary. The host
/// publishes them with every transaction, before it asks for any row.
document_style_computation_inputs: bridge::FfiDocumentStyleComputationInputs,
- /// The viewport, width and height, the last flush drove records against. A record holding a
- /// value resolved against the viewport cannot stand once it moved, and the viewport is one of
- /// the document's inputs, so comparing it is what tells the engine, not the host naming every
- /// reader.
- driven_viewport: (f64, f64),
/// The base URLs a `url()` resolves against, copied at the transaction boundary with the inputs.
document_resource_contexts: resource_contexts::DocumentResourceContexts,
/// The document's media features, copied from each transaction's inputs.
@@ -813,14 +263,9 @@ pub struct RetainedState {
/// `font-family: monospace`, the family the monospace font-size recascade resolves an
/// ancestor's font-relative lengths against.
monospace_font_family: RetainedStyleValueData,
- layer_topology_version: u64,
- sheet_order_version: u64,
- /// Canonical specified values referenced by dense rule and winner rows.
- specified_values: crate::fork::ForkShared<SpecifiedValues>,
- /// The winning stylesheet declarations last observed for each element, interned by their
- /// property-wise answer. Element identities are dense, so the column is directly indexed.
- winner_groups: crate::fork::ForkShared<WinnerGroups>,
+ /// The values elements' own declarations share, one per content.
+ canonical_values: crate::fork::ForkShared<CanonicalValues>,
/// The shared computed-group payload tuple last published for each live element. This is the
/// computed half of the eventual base style record; custom properties and metadata remain
/// separate inputs until that record is complete.
@@ -829,42 +274,6 @@ pub struct RetainedState {
style_record_view_epoch_depth: u32,
/// The stores behind the custom-property environments live records are published with.
custom_property_environments: crate::fork::ForkShared<custom_property_environments::CustomPropertyEnvironments>,
- /// The nodes whose engine-computed record substituted a custom property into a winner: what
- /// C++ notes as reading custom properties when it installs the record.
- nodes_with_substituted_records: HashSet<StyleNodeID>,
- /// What the custom declarations of an element, or of its pseudo-elements, read beyond the
- /// environment they resolve over, as `FfiNodeRecordReads` bits, for the elements whose
- /// declarations read anything: what the host notes beside their records.
- custom_declaration_reads: HashMap<StyleNodeID, u8>,
- /// The custom properties the custom declarations of an element, or of its pseudo-elements,
- /// declare or read through `var()`. `None` when they cannot be listed.
- custom_declaration_custom_property_reads:
- HashMap<StyleNodeID, Option<custom_property_cascade::CustomPropertyNames>>,
- /// What `custom_declaration_custom_property_reads` notes, by the custom declarations an element cascaded.
- custom_property_reads_by_declarations: custom_property_cascade::CustomPropertyReadsByDeclarations,
- /// The custom-property environments elements resolved to over the environments they inherit, and what their
- /// declarations read, by the match answer the declarations cascaded from: an element alike in its answer, its
- /// tree and what it inherits resolves alike. Cleared wherever a match answer's identity may be handed out again.
- custom_property_environments_by_answer:
- HashMap<custom_property_cascade::EnvironmentByAnswerKey, custom_property_cascade::EnvironmentByAnswer>,
- /// Whether the environment resolved last stands for every element alike in its inputs.
- last_custom_property_environment_memoizable: bool,
- /// Which of a node's records read its place among its siblings, written or produced by a
- /// substitution: a bit for its own record and one per synthetic pseudo-element kind, which
- /// each record the engine derives, or admits from C++, sets or clears as it is installed. A
- /// change among the node's siblings drives a record that reads it again in full, and C++ notes
- /// the node as reading it when it installs the engine's records.
- nodes_with_tree_counting_records: HashMap<StyleNodeID, u16>,
- /// The nodes whose last winner store, for the element or for one of its pseudo-elements (a
- /// bit each, see `rolled_back_bit`), rolled a property back below a revert keyword a
- /// substitution produced: what it rolled back to is a declaration the winners do not name, so
- /// the node's records are its alone and are computed again whatever its winners say.
- nodes_with_rolled_back_records: HashMap<StyleNodeID, u64>,
- /// The nodes whose last winner store, for the element or for one of its pseudo-elements,
- /// substituted a value that resolves against the element: a `random()` it draws or a
- /// container-relative length. No record cache keys on the element, so its records are its
- /// alone.
- nodes_with_element_relative_substitutions: HashMap<StyleNodeID, publication::ElementRelativeSubstitutions>,
/// The custom-property environment each element holds, for the elements that hold one. This is
/// the only copy: the element reads its environment from here.
element_custom_property_data: crate::fork::ForkShared<HashMap<StyleNodeID, inputs::HeldCustomPropertyEnvironment>>,
@@ -872,25 +281,13 @@ pub struct RetainedState {
/// pseudo-element kind, for the elements with a pseudo-element that holds one.
pseudo_element_custom_property_data:
crate::fork::ForkShared<HashMap<StyleNodeID, Vec<(u8, inputs::HeldCustomPropertyEnvironment)>>>,
- /// The elements whose style reads their custom-property environment other than through `var()`,
- /// which a moved environment computes again.
- environment_move_recompute_nodes: HashSet<StyleNodeID>,
+ /// The elements whose animations' keyframes say `inherit` for a property that does not
+ /// inherit, as the host last sampled them: they read their parent's values of properties that
+ /// do not inherit, whether or not their records do.
+ keyframes_reading_parent_reset_values: crate::fork::ForkShared<HashSet<StyleNodeID>>,
/// What the container conditions of the rows the engine answered read of their containers,
/// per element, taken when the host installs the element's record.
container_effects_for_host: container_queries::ContainerEffectsForHost,
- /// Each node's gated rules and whether their conditions held for their targets when its
- /// winners were published, `None` where the engine could not decide them: the winners hold a
- /// gated rule's declarations exactly where it held, and an undecided one leaves the node to
- /// the host.
- published_container_verdicts: HashMap<StyleNodeID, Vec<PublishedContainerVerdict>>,
- /// Nodes whose winners were published while an ancestor's answer was moving in the same
- /// transaction, so their gated rules' conditions could not be decided when they were.
- container_gates_unheld: HashSet<StyleNodeID>,
- /// What moved under the records of the elements the transaction being recorded owes a style
- /// input, which no winner of theirs shows: their containers, or their parent's display.
- row_inputs_moved: flush::RowInputsMoved,
- /// Whether, and as what, each element's published record makes it a query container.
- container_query_inputs: tree::ContainerQueryInputColumns,
/// What the last layout commit and scroll state say of each container's box, for the
/// container queries that ask about it: a size container's, and a scroll-state container's.
layout_style_snapshots: HashMap<StyleNodeID, crate::layout::style_snapshot::LayoutStyleSnapshotRow>,
@@ -900,10 +297,11 @@ pub struct RetainedState {
/// The counter-style registry each tree scope's style scope has, as one identity per scope:
/// what a record whose `list-style-type` names a counter style the registry may define names,
/// so that an edit to `@counter-style` moves it.
- counter_style_environment_identities: HashMap<TreeScopeID, u64>,
+ counter_style_environment_identities: crate::fork::ForkShared<HashMap<TreeScopeID, u64>>,
/// The style record each element holds, for the elements that hold one, as the host reports
/// every record it installs or clears.
- held_style_records: crate::fork::ForkShared<HashMap<StyleNodeID, u64>>,
+ /// Copied on write in chunks of its own, which a fork shares.
+ held_style_records: inputs::HeldStyleRecords,
/// The style record each pseudo-element holds, by its kind, for the elements whose pseudo-elements
/// hold one, as the host reports every record it installs or clears.
held_pseudo_style_records: crate::fork::ForkShared<HashMap<StyleNodeID, Vec<(u8, u64)>>>,
@@ -913,10 +311,7 @@ pub struct RetainedState {
/// Per shadow host, the elements of its shadow tree that stood for one of its element-backed
/// pseudo-elements when the host published them; [`RetainedState::backing_elements`] reads the
/// ones that still do.
- backing_elements: HashMap<StyleNodeID, SmallVec<[StyleNodeID; 2]>>,
- /// The elements and shadow roots the host marked as having a child that explicitly inherits
- /// a non-inherited property: a move of the node's non-inherited groups reaches its children.
- children_explicitly_inherit_marks: HashMap<StyleNodeID, u32>,
+ backing_elements: crate::fork::ForkShared<HashMap<StyleNodeID, SmallVec<[StyleNodeID; 2]>>>,
/// The names of the CSS animations the host holds for each element, which the computation of
/// its animation definitions matches them against.
css_defined_animations: crate::fork::ForkShared<animations::CssDefinedAnimations>,
@@ -930,155 +325,70 @@ pub struct RetainedState {
animation_effect_descriptions: crate::fork::ForkShared<effect_descriptions::AnimationEffectDescriptions>,
/// The font metrics of the record the host holds for the document element, which a `rem` the
/// host resolves reads, once it holds one.
- held_root_font_inputs: Option<publication::RootFontInputs>,
+ held_root_font_inputs: Option<pipeline::compute::RootFontInputs>,
/// The random base value each random caching key has been given, for the random functions the
/// document's styles hold.
random_base_values: random_bases::RandomBaseValues,
/// What each element that has replaced content gives its natural size, which layout resolves
/// against the style of the element's box.
- replaced_content_inputs: HashMap<StyleNodeID, inputs::ReplacedContentInput>,
+ replaced_content_inputs: crate::fork::ForkShared<HashMap<StyleNodeID, inputs::ReplacedContentInput>>,
/// The before-change style each transition target's transitions are decided against for the
/// rest of the style stabilization epoch, pinned until the epoch commits.
transition_baselines: transition_baselines::TransitionBaselines,
/// Whether the registrations used by this transaction differ from the preceding one. A
- /// previously substituted record must then be recomputed by C++, which implements registered
- /// custom properties, even when its cascade winners did not move.
+ /// previously substituted record must then be computed again, even when its cascade winners did
+ /// not move.
custom_property_registrations_changed: bool,
- /// Records the engine derived for published reactions that C++ has not installed yet. Their
- /// columns already moved so descendants in the same flush build on them; the cascade state
- /// and answer consumption follow C++'s acknowledgement, and a discarded transaction reverts
- /// the columns of the ones it never installed. Group records by node so acknowledging or
- /// abandoning one element visits only its own record and pseudo-elements.
- engine_computed_records_pending: HashMap<StyleNodeID, SmallVec<[publication::PendingEngineComputedRecord; 1]>>,
/// The record a private demand last answered for each target it was asked about, pinned for
/// the host to read: no node holds it.
- demand_records: HashMap<computed::ComputedStyleTarget, computed::FinalStyleRecordID>,
- /// First records derived earlier, by what they were derived from, for later elements alike.
- /// Pseudo-element records the engine derived, by what they were derived from, for elements
- /// alike in that to share.
- /// Counts the style transactions taken; the winner rows record which one published them.
- flush_stamp: u64,
- engine_pseudo_record_cache: HashMap<publication::PseudoCohortKey, computed::FinalStyleRecordID>,
- /// Whether the answer the current transaction publishes for each node has winners complete
- /// but for custom properties, read for the record loop: the answers are installed after it.
- batch_answers_complete_but_for_custom_properties: HashMap<StyleNodeID, bool>,
- /// Beside them, the matches in each answer that declare custom properties, read the same way:
- /// what the node's custom-property cascade runs over while its answer is not installed.
- batch_custom_property_matches: HashMap<StyleNodeID, Vec<BatchCustomPropertyMatch>>,
- /// The identity of the answer each node's `batch_custom_property_matches` were read from, where it has one.
- batch_custom_property_answers: HashMap<StyleNodeID, MatchAnswerID>,
- /// Beside them, each published host's matches for the element-backed pseudo-elements, which
- /// the elements backing them cascade from while the host's answer is not installed.
- batch_backing_pseudo_matches: HashMap<StyleNodeID, Vec<RuleMatch>>,
- /// The same matches of each shadow host, as its last published answer held them under the program version beside
- /// them. A host's answer is never retained, and the elements backing its pseudo-elements are styled in the
- /// transactions after the host's, which cascade from these rather than matching the host again.
- shadow_host_backing_pseudo_matches: HashMap<StyleNodeID, (ProgramVersion, Vec<RuleMatch>)>,
- engine_cold_record_cache: crate::fork::ForkShared<HashMap<publication::ColdRecordKey, publication::ColdRecord>>,
- engine_cold_record_donors:
- crate::fork::ForkShared<HashMap<publication::ColdRecordDonorKey, Vec<publication::ColdRecordDonor>>>,
- style_invalidation_cache: HashMap<(u64, u64, bool, bool, bool), u32>,
+ demand_records: crate::fork::ForkShared<HashMap<computed::ComputedStyleTarget, computed::FinalStyleRecordID>>,
- /// One identity per distinct match-answer factor, retained exact factor, or cascade input.
- /// The catalog lives with the document rather than with a traversal, because a per-element ask -
- /// which is what a script reading style gets - opens no traversal, and an identity that only
- /// exists inside one answers the pages that need it least. An id is never reused for a
- /// different answer, so a consumer holding one across a flush is never told the wrong thing.
- match_answers: crate::fork::ForkShared<MatchAnswerCatalog>,
- selector_truth_sets: SelectorTruthSetCatalog,
- retained_match_answers: crate::fork::ForkShared<RetainedMatchAnswers>,
- retained_selector_incidences: RetainedSelectorIncidences,
- /// Whether the current transaction changes activation without changing selector inputs.
- selector_incidence_is_current: bool,
- /// Read-through facts shared by one synchronous style traversal. This is transaction scratch,
- /// not retained matching state. A broad traversal begins with a complete batch; a selective one
- /// promotes only after repeated local packing clears its rebuild-cost hysteresis.
- /// The transaction or host-call adapter owns the box while matching borrows its scratch.
- /// Moving the box at those boundaries leaves the fact batch's vector headers in place.
- batch_matching_traversal: Option<Box<BatchMatchingTraversal>>,
- /// Distinct retained cascade states per dispatch-key posting, shared by every route-pruning
- /// proof in one routing pass. Keyed by the winner-group generation so any winner mutation
- /// invalidates naturally; cleared per transaction so the map cannot grow across flushes. A
- /// `None` entry records that the posting's coverage was incomplete, which is a `false`
- /// verdict for every asker.
- route_pruning_states: crate::fork::ForkReset<Mutex<RoutePruningStateCache>>,
/// The places of the children of parents with many of them, which sibling-counting functions
/// read, kept while the tree's DOM order stands.
sibling_positions: crate::fork::ForkReset<Mutex<publication::SiblingPositionCache>>,
- /// Prefix transitions and their canonical answers have one document-lifetime owner. Matching
- /// traversals and answer patches borrow it synchronously and change its cache-owned lifecycle
- /// between scratch and retained without moving the payload.
- prefix_caches: std::sync::Arc<SharedPrefixCaches>,
- /// Test-only: force the bounded completion window.
- #[cfg(test)]
- force_bounded_prefix_completion: bool,
- /// Current-side scratch an exact transaction already produced for the style consumer
- /// that immediately consumes it. Any intervening engine mutation discards it.
- prepared_batch_matching_traversal: Option<PreparedBatchMatchingTraversal>,
- /// Complete compact answers owned by the scoped style transaction which the next traversal
- /// consumes. This is transaction scratch, not a persistent inverse match relation.
- published_match_answers: PublishedMatchAnswers,
- transaction_fact_view: Option<TransactionFactView>,
- facts: crate::fork::ForkShared<ElementFactStore>,
- programs: SelectorPrograms,
+ /// What the last the engine cold pass measured.
+ cold_pass_report: pipeline::Report,
+ /// The engine kept live beside this engine, when asked for, which a fork goes on keeping.
+ live_style: Option<Box<pipeline::Live>>,
+ /// Whether this is the state the host writes, on which alone the engine starts.
+ live_style_may_start: crate::fork::ForkReset<crate::fork::IsOriginal>,
+ /// How many cold passes the engine started from, on this state and on every fork of it.
+ cold_passes: std::sync::Arc<std::sync::atomic::AtomicU64>,
+ /// What the engine did on this state, for tests to read.
+ live_counters: pipeline::counters::Counters,
+ /// The threads style passes run on, which the process shares where a render state holds the
+ /// engine.
+ style_pool: Option<std::sync::Arc<pipeline::pool::StylePool>>,
+ /// The font longhand values the engine substituted, one value per property and content: the
+ /// font resolver knows a family and its feature values by their values' identities.
+ substituted_font_values: std::sync::Arc<std::sync::Mutex<Vec<(u16, RetainedStyleValueData)>>>,
+ /// The longhand properties each element declares itself, by the kind of declaration they came
+ /// from. An element-attached declaration beats every rule in its context, so the cascade needs
+ /// to know which properties one covers just as it does for a rule.
+ element_declarations: crate::fork::ForkShared<element_declarations::ElementDeclarationStore>,
+ /// The document as the engine reads it: every element fact and link the host publishes.
+ projection: pipeline::projection::Projection,
/// The attribute names whose value text a selector reads, which the host holds a copy of between jobs.
attribute_value_text_names: SelectorAttributeNames,
/// The attribute names a selector tests in any way, which the host holds a copy of between jobs.
tested_attribute_names: SelectorAttributeNames,
attribute_value_text_requirements_version: u64,
+ /// Whether a selector tests `:local-link`, which the host holds a copy of between jobs.
+ selectors_test_local_link: bool,
/// What an arrival has to carry to reach a `:has()` anchor, which the host holds a copy of between jobs.
relational_arrival_keys: Arc<RelationalArrivalKeys>,
/// The keys rules added since, which the host learns of once they are resolved.
- unresolved_relational_arrival_keys: HashSet<RoutingKey>,
+ unresolved_relational_arrival_keys: HashSet<DispatchKey>,
/// Moves whenever `relational_arrival_keys` does.
relational_arrival_keys_version: u64,
- selector_programs_need_sweep: bool,
- routing: Arc<RoutingRegistry>,
- /// The rules of a user-agent sheet being published, in the order they are routed, which are routed together as the
- /// publication ends; see `route_user_agent_rules`.
- deferred_user_agent_routes: Option<Vec<(RuleID, SelectorProgramID)>>,
- /// Exact selector changes and refresh requests emitted by the current transaction.
- selector_truth_changes: SelectorTruthChanges,
- already_planned_selector_truth: DeltaBatch<AlreadyPlannedSelectorTruthCandidate>,
- /// Whether the current plan records attribution at all: without a patch selection nothing
- /// consumes it, so the narrowing paths skip the bookkeeping entirely.
- selector_truth_changes_active: bool,
- /// Previous completed matching outcomes, read by routing and installed at matching boundaries.
- relational_witnesses: RelationalWitnesses,
- pending_witness_effects: Vec<WitnessEffect>,
/// The node that owns each style scope, for the scopes that have one. The document's scope has
/// no node, and a scope with no entry here is treated as the document's - which is the widest
/// answer and therefore the safe one. Tree-scope identities are minted monotonically within one
/// document, so the identity indexes the column directly.
- scope_roots: Column<Option<StyleNodeID>>,
+ scope_roots: crate::fork::ForkShared<Column<Option<StyleNodeID>>>,
/// The inverse of `scope_roots`. Departing ordinary elements vastly outnumber departing scope
/// roots, so retirement must ask this index instead of scanning every historical tree scope.
scope_by_root: crate::fork::ForkShared<SegmentedNodeColumn<TreeScopeID>>,
- /// The immutable selector dispatch of each distinct effective sheet set and encapsulation
- /// depth. Concrete scopes retain only its dense identity.
- scope_programs: intern_table::InternTable<ScopeProgramID, Option<ScopeProgram>>,
- vacant_scope_programs: Vec<ScopeProgramID>,
- /// One representative dispatch for each live selector topology. Ordinary program changes keep
- /// these templates because their topology contains no concrete rule identity; selector-program
- /// sweeping drops templates whose selector programs are no longer live.
- scope_dispatch_templates: HashMap<ScopeDispatchShape, Arc<RuleDispatch>>,
- /// One ranked dispatch for each selector topology and semantic cascade arrangement. Concrete
- /// rule identities differ between equivalent sheets, but their dense static ranks do not.
- scope_cascade_templates: HashMap<ScopeCascadeShape, Arc<RuleDispatch>>,
- /// One ancestor table for each key layout. Selector program growth often leaves this layout
- /// unchanged. Keep only the table so sharing it cannot retain an obsolete selector dispatch.
- ancestor_dispatch_templates:
- crate::fork::ForkShared<HashMap<AncestorDispatchShape, Arc<index::AncestorDispatchTopology>>>,
- /// The shapes of the scope programs removed since the unused templates were last dropped, oldest first, and the
- /// ancestor table of each one's dispatch. The templates of the last one no live program has the shape of outlive
- /// it, so a page that switches back to the sheet set it ranked rebinds them instead of building its dispatch again.
- retired_scope_templates: Vec<(ScopeTemplateShapes, Arc<index::AncestorDispatchTopology>)>,
- /// Whether a scope program was removed or a template was filed since the unused templates were last dropped.
- scope_templates_need_sweep: bool,
- /// The shared program each concrete tree scope resolved to. Program changes clear the table,
- /// while a depth change replaces only this scope's identity. It uses the same direct tree-scope
- /// index as the root column.
- scope_program_by_scope: Column<Option<(u32, ScopeProgramID)>>,
/// Maps names and qualified names to process-global atoms. Selector names and DOM facts use
/// the same owner, so a class in a stylesheet and a class on an element compare as one integer.
///
@@ -1093,8 +403,6 @@ pub struct RetainedState {
/// quirks-mode one does. Selectors are then compiled against the lowercase folding of the name,
/// and the DOM side publishes the folding too, so `.item` and `ITEM` name one atom.
fold_id_and_class_name_case: bool,
- #[cfg(test)]
- diagnostic_plan_capture: Option<DiagnosticPlanCapture>,
}
#[derive(Clone, Copy)]
@@ -1103,21 +411,15 @@ struct DeferredElementStyleInput {
inherited_style_groups: u8,
}
-/// Host-facing engine state: C++ ownership and journal intake.
+/// Host-facing engine state: C++ ownership and input intake.
/// Never reachable from an evaluation step.
#[derive(Clone)]
pub struct HostState {
- /// The style pass the host is installing wave by wave, between two of its waves.
- suspended_style_pass: Option<flush::StylePass>,
- /// The host's synchronous font resolver. A step that misses the cache returns `NeedsInput`;
- /// the round outside the step calls this and the node is retried.
+ /// The host's synchronous font resolver. A step that misses the cache suspends its element;
+ /// the round outside the step calls this and the element is retried.
font_resolver: Option<font_resolution::FontResolverHost>,
- journal: NormalizationJournal,
- /// Local selector facts through the latest geometry read which reused committed layout. A
- /// normal style observation merges this into `journal`; a newly introduced transition can
- /// instead consume it as the preceding style change event.
- deferred_geometry_journal: NormalizationJournal,
- flushing_deferred_geometry_journal: bool,
+ /// The element inputs the next transaction takes beside the projection's changes.
+ element_inputs: PendingElementInputs,
/// Exact element reactions retained across rootless flushes until a style root can consume them.
deferred_element_style_inputs: std::collections::BTreeMap<StyleNodeID, DeferredElementStyleInput>,
/// Whether the deferred element style inputs moved since the document's host last took them.
@@ -1126,18 +428,9 @@ pub struct HostState {
/// held back by a flush without a document root.
deferred_element_style_inputs_are_pending: bool,
/// The custom properties that changed between pairs of environments during this transaction.
- environment_move_changed_names: crate::fork::ForkReset<environment_move::ChangedCustomPropertyNames>,
- /// Whether any tree input batch has crossed into the engine. A first batch consisting entirely
- /// of unique arrivals can install its final relation rows as one bulk load.
- initial_tree_batch_applied: bool,
- /// Whether that bulk load is still part of the transaction awaiting first observation.
- initial_tree_bulk_load_is_pending: bool,
- /// Final relation rows staged until the next observation boundary. Moving one node updates its
- /// affected neighbours here, so those derived changes need no separate journal ingress.
- tree_staging: TreeRelationStaging,
/// Program-family before/after rows retained until the transaction is released.
program_staging: ProgramStaging,
- sheet_occurrences: HashMap<TreeScopeID, sheet_occurrences::ScopeSheetOccurrences>,
+ sheet_occurrences: HashMap<TreeScopeID, pipeline::rule_store::ScopeSheetOccurrences>,
/// The old dense rule sequence while one sheet is synchronously reparsed.
sheet_rule_replacement: Option<SheetRuleReplacement>,
/// Identities released at transaction settlement. The FFI keeps this batch borrowed until C++
@@ -1146,6 +439,14 @@ pub struct HostState {
/// Whether the transaction under way leaves its atom sweep to a later one: it runs beside the host, which may name
/// an atom meanwhile that the sweep would reclaim before the host hears of it.
defers_atom_sweep: bool,
+ /// The records the anonymous boxes an installation styles again derive, by the record each held, its parent's and
+ /// the one it takes its column properties from, while an installation runs.
+ reinherited_records: Option<HashMap<layout_style::Reinheritance, u64>>,
+ /// The style node identities the end of a transaction released since the job began, which the job's end pays the
+ /// host to mint again.
+ released_style_nodes: Vec<u32>,
+ /// The hover seal's last answer, with what it read.
+ hover_seal: pipeline::HoverSealMemo,
}
/// Mutable engine state; operations borrow their instrumentation from the boundary.
@@ -1155,6 +456,13 @@ pub struct StyleEngine {
pub(super) host: HostState,
}
+impl RetainedState {
+ /// The groups of default values every computation starting from nothing starts from.
+ pub(crate) fn default_groups(&self) -> &crate::css::computed_values::DefaultGroups {
+ &self.process_style.default_groups
+ }
+}
+
impl std::ops::Deref for StyleEngine {
type Target = RetainedState;
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
index 2a7ff75ece6..7fc1d41b3b2 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/compute.rs
@@ -1183,6 +1183,7 @@ impl RetainedState {
environment_reads,
reads_attributes: false,
container_units,
+ display_none_is_animated: false,
},
length: crate::css::style_compute::FfiLengthResolutionContext {
resolved_viewport_relative_length: std::ptr::null_mut(),
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs
index 4ec21762b56..719a59c0274 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs
@@ -239,6 +239,9 @@ pub(crate) struct ComputationReads {
/// The container-relative units the element's computation resolved against its query
/// containers, as a `container_relative_length_unit_mask`.
pub(in crate::css::style) container_units: u8,
+ /// Whether the element's `display` computed to `none` only through the custom properties its
+ /// animations sampled, and so to something else when ignoring them.
+ pub(in crate::css::style) display_none_is_animated: bool,
}
/// What a style records of its computation beyond its values: the flags beside its values, what
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
index 0c3791cc12d..c17700408b3 100644
--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs
@@ -1685,6 +1685,49 @@ impl<'a> Scratch<'a> {
return Err(Outcome::ComputeDeclined);
};
computed.element_dependent |= custom_properties_read_subject;
+ // https://drafts.csswg.org/css-animations-2/#owning-element-section
+ // If the display property of an element is set to none and its display value would compute to none when
+ // ignoring the Transitions and Animations cascade origins, then terminate running animations with this
+ // owning element.
+ // NB: The sampled custom properties are part of the Animations origin, so what they make of `display` is
+ // not what ends the animations. Only an element they leave with none computes this again.
+ let display_is_none = |computed: &super::compute::ComputedElement| {
+ crate::css::style_compute::display_of(
+ computed
+ .groups
+ .value(crate::css::property_metadata::property_id::DISPLAY),
+ )
+ .is_none()
+ };
+ if sampled.is_some() && display_is_none(&computed) {
+ let ignoring_animations = state.drive_element(
+ context.records,
+ node,
+ parent,
+ context.initial,
+ &self.cascade.winners,
+ &super::cascade::CascadeBelow {
+ cascade: &self.cascade,
+ state,
+ node,
+ },
+ &mut None,
+ &mut Default::default(),
+ super::custom_properties::CustomPropertyStores {
+ own: substituted.as_ref(),
+ inherited: parent_held.as_deref(),
+ substitutions: &self.substitutions,
+ subject: &subject,
+ },
+ &mut self.groups,
+ &mut self.absolutized,
+ u8::MAX,
+ context.root_font(),
+ group_seeds,
+ );
+ computed.reads.display_none_is_animated =
+ ignoring_animations.is_ok_and(|ignoring_animations| !display_is_none(&ignoring_animations));
+ }
let registered = state.registered_custom_property_store(
node,
parent_store.as_deref(),
diff --git a/Libraries/LibWeb/Rust/src/css/style/publication.rs b/Libraries/LibWeb/Rust/src/css/style/publication.rs
index 23711cd7ed7..e85e56c4c01 100644
--- a/Libraries/LibWeb/Rust/src/css/style/publication.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/publication.rs
@@ -5,117 +5,14 @@
*/
mod demand;
-mod drive;
mod pseudo;
-pub(super) use drive::drive_font_metric;
-mod winner_store;
-use winner_store::{WinnerDeclaration, WinnerStore, WinnerValue, shorthand_longhand_data};
-
-use super::container_queries::VerdictTargets;
+use super::pipeline::compute::RootFontInputs;
use super::*;
-use crate::css::computed_longhand_table::{
- ComputedLonghandTable, DEPENDS_ON_VIEWPORT_METRICS, FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS,
- IN_DISPLAY_NONE_SUBTREE,
-};
+use crate::css::computed_longhand_table::IN_DISPLAY_NONE_SUBTREE;
use crate::css::computed_value_views::QuoteTransfer;
-use crate::css::computed_values::StyleGroupMasks;
use animations::DeclarationScope;
-pub(super) use demand::WinnerRepublication;
pub(crate) use demand::{RecordDemand, RecordDemandAnswer};
-pub(super) use drive::{Drive, OrRefused, Suspension, Unanswered};
-use drive::{DrivenTable, FontDriveGoal, FullDrive, PartialDrive};
-
-/// Root-relative computation reads these inputs independently of its inheritance parent.
-/// Bitwise keys keep equality exact without using an invalidation generation as a substitute
-/// for the values. The viewport-dependence bit matters even when today's metrics agree.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub(super) struct RootFontInputs {
- metrics: [u64; 5],
- depends_on_viewport: bool,
- /// https://drafts.csswg.org/css-viewport/#effective-zoom
- /// The bits of the effective zoom of the document element, which the metrics are zoomed by.
- effective_zoom: u64,
-}
-
-/// An element's old and new style records.
-pub(super) type RecordDelta = (computed::FinalStyleRecordID, computed::FinalStyleRecordID);
-
-/// What the computation of an element's record answers: its record delta, or, for the root-input
-/// probe, the document element's font inputs where the probe proved them.
-pub(super) enum ElementAnswer {
- Delta(RecordDelta),
- RootInputs(Option<RootFontInputs>),
-}
-
-/// How much of an element's held record a row drives again.
-#[derive(Clone, Copy, PartialEq, Eq)]
-enum DriveScope {
- /// Nothing the record was computed from moved: it stands.
- Stands,
- /// Only the custom-property environment the record resolves under moved: it takes this one.
- Environment(u64),
- /// The moved winners are driven again over the record.
- Partial,
- /// Every phase is driven again from the current inputs, against the parent as it is now.
- Full,
-}
-
-impl ElementAnswer {
- /// The delta of a computation that was no root-input probe.
- fn delta(self) -> RecordDelta {
- match self {
- Self::Delta(delta) => delta,
- Self::RootInputs(_) => unreachable!("only the root-input probe answers with root inputs"),
- }
- }
-}
-
-impl RootFontInputs {
- /// The metrics a `rem` resolves against, and whether they read the viewport.
- pub(super) fn font_metrics(self) -> (crate::css::style_compute::FfiFontMetrics, bool) {
- let [font_size, x_height, cap_height, zero_advance, line_height] = self.metrics.map(f64::from_bits);
- (
- crate::css::style_compute::FfiFontMetrics {
- font_size,
- x_height,
- cap_height,
- zero_advance,
- line_height,
- },
- self.depends_on_viewport,
- )
- }
-
- /// https://drafts.csswg.org/css-viewport/#effective-zoom
- pub(super) fn effective_zoom(self) -> f64 {
- f64::from_bits(self.effective_zoom)
- }
-
- fn apply_to(self, inputs: &mut bridge::FfiDocumentStyleComputationInputs) {
- inputs.root_font_size = f64::from_bits(self.metrics[0]);
- inputs.root_font_x_height = f64::from_bits(self.metrics[1]);
- inputs.root_font_cap_height = f64::from_bits(self.metrics[2]);
- inputs.root_font_zero_advance = f64::from_bits(self.metrics[3]);
- inputs.root_line_height = f64::from_bits(self.metrics[4]);
- inputs.root_font_metrics_depend_on_viewport_metrics = self.depends_on_viewport;
- inputs.root_effective_zoom = f64::from_bits(self.effective_zoom);
- }
-
- pub(super) fn from_document(inputs: &bridge::FfiDocumentStyleComputationInputs) -> Self {
- Self {
- metrics: [
- inputs.root_font_size.to_bits(),
- inputs.root_font_x_height.to_bits(),
- inputs.root_font_cap_height.to_bits(),
- inputs.root_font_zero_advance.to_bits(),
- inputs.root_line_height.to_bits(),
- ],
- depends_on_viewport: inputs.root_font_metrics_depend_on_viewport_metrics,
- effective_zoom: inputs.root_effective_zoom.to_bits(),
- }
- }
-}
/// What a subtree does to the generated-content state that the boxes after it read.
#[derive(Clone, Copy, Default)]
@@ -133,10 +30,6 @@ pub(crate) struct SubtreeGeneratedContentEffects {
}
impl RetainedState {
- pub(super) fn pseudo_element_style_is_deferred(&self, kind: tree::PseudoElementKind) -> bool {
- u32::from(kind.0) < u64::BITS && self.deferred_pseudo_elements & (1 << kind.0) != 0
- }
-
/// The record a highlight pseudo-element inherits from: the same pseudo-element's record on its
/// nearest flat-tree ancestor holding one, as the engine has it assigned.
pub(crate) fn retained_highlight_inheritance_parent_style_record(
@@ -144,141 +37,16 @@ impl RetainedState {
node: StyleNodeID,
pseudo_kind: u8,
) -> Option<computed::FinalStyleRecordID> {
- let mut ancestor = self.tree.inheritance_parent(node);
+ let mut ancestor = self.projection.inheritance_parent(node);
while let Some(candidate) = ancestor {
if let Some(record) = self.computed_group_sets.pseudo_style_record(candidate, pseudo_kind) {
return Some(record);
}
- ancestor = self.tree.inheritance_parent(candidate);
+ ancestor = self.projection.inheritance_parent(candidate);
}
None
}
- /// The inheritance parent a node's record is computed from, none for the document element. A
- /// parent without a record is one the host styles before it applies the row, which waits for
- /// it.
- pub(super) fn record_inheritance_parent(&self, node: StyleNodeID) -> Drive<Option<StyleNodeID>> {
- let Some(parent) = self.tree.inheritance_parent(node) else {
- return Ok(None);
- };
- if self.computed_group_sets.assigned_style_record(parent).is_none() {
- return Err(Unanswered::AwaitsParent);
- }
- Ok(Some(parent))
- }
-
- /// The custom-property environment of a node the drive reads as an inheritance parent, which
- /// holds a record. Every record is assigned with its environment, so it holds one; should it
- /// not, the row waits for the parent as for one without a record.
- ///
- /// What the node's animations sampled into its custom properties is what it hands down, over
- /// the record's environment. The host lays the samples over a record as it installs it, so a
- /// child of a record moved beneath them waits for the parent.
- fn held_custom_property_environment(&self, node: StyleNodeID) -> Drive<u64> {
- let environment = self.computed_group_sets.custom_property_environment_identity(node);
- debug_assert!(environment.is_some(), "an inheritance parent without an environment");
- let Some(environment) = environment else {
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
- return Err(Unanswered::AwaitsParent);
- };
- let Some(held) = self
- .element_custom_property_data
- .get(&node)
- .filter(|held| held.sampled_over.is_some())
- else {
- return Ok(environment);
- };
- // The record names the overlay once the host composed the samples into it, or the
- // environment beneath them before.
- if environment == held.identity || held.sampled_over == Some(environment) {
- Ok(held.identity)
- } else {
- Err(Unanswered::AwaitsParent)
- }
- }
-
- /// A node's custom-property environment as this flush leaves it. A row this flush settles
- /// holds its new environment already, but an ancestor between it and a first record may be one
- /// the host refreshes only once the batch applies, so the first record would resolve over the
- /// environment that ancestor held before. Each ancestor's is resolved again over its parent's
- /// as it is now, and kept for the rows after it. A node whose animations compose keeps the
- /// environment it holds. `None` for a node holding no environment.
- fn current_custom_property_environment(
- &mut self,
- node: StyleNodeID,
- inputs: &bridge::FfiDocumentStyleComputationInputs,
- scratch: &mut EngineComputedRecordScratch,
- ) -> Option<u64> {
- if let Some(&current) = scratch.current_custom_property_environments.get(&node) {
- return Some(current);
- }
- self.computed_group_sets.custom_property_environment_identity(node)?;
- let held = self.held_custom_property_environment(node).ok()?;
- // An ancestor outside the batch can have no retained answer for the current rule program.
- // That does not mean it declares no custom properties: keep its own resolved values when
- // refreshing what it inherits from a parent that moved.
- let has_match_answer = self
- .try_for_each_answer_match(node, None, |_, _, _, _| std::ops::ControlFlow::<()>::Continue(()))
- .is_some();
- let animates =
- self.computed_group_sets.adjustment_facts(node) & bridge::element_adjustment_fact::HAS_ANIMATIONS != 0
- || self.element_samples_custom_properties(node);
- let parent = self.tree.inheritance_parent(node).filter(|_| !animates);
- let current = match parent.and_then(|parent| {
- Some((
- parent,
- self.current_custom_property_environment(parent, inputs, scratch)?,
- ))
- }) {
- Some((parent, parent_environment))
- if !has_match_answer
- && self.computed_group_sets.custom_property_environment_identity(parent)
- != Some(parent_environment) =>
- {
- let inherited = self.custom_property_environments.inheritable(parent_environment);
- let previously_inherited = self
- .computed_group_sets
- .custom_property_environment_identity(parent)
- .map(|environment| self.custom_property_environments.inheritable(environment));
- if previously_inherited == Some(held) {
- inherited
- } else {
- let store = self.custom_property_environments.store(held)?;
- let parent_store = self.custom_property_environments.store(inherited).cloned();
- let values = store
- .declared_names
- .iter()
- .map(|&name| (name, store.own_values[&name].value.clone_retained()))
- .collect();
- let rebuilt = store.resolved_child(parent_store.clone(), values);
- self.custom_property_environments.adopt_engine_environment(
- rebuilt,
- inherited,
- parent_store.as_deref(),
- inputs.custom_property_registry(),
- )
- }
- }
- // A node declaring none inherits its parent's environment as it is now.
- Some((_, parent_environment)) if has_match_answer && !self.node_declares_custom_properties(node) => {
- self.custom_property_environments.inheritable(parent_environment)
- }
- // A node declaring custom properties was resolved over its parent's environment as the
- // parent holds it, so it is stale only beneath a parent that moved.
- Some((parent, parent_environment))
- if has_match_answer
- && self.computed_group_sets.custom_property_environment_identity(parent)
- != Some(parent_environment) =>
- {
- self.engine_custom_property_environment(node, parent_environment, inputs, None)
- .unwrap_or(held)
- }
- _ => held,
- };
- scratch.current_custom_property_environments.insert(node, current);
- Some(current)
- }
-
#[cfg(test)]
pub(super) fn retained_store_supports_property(target: computed::ComputedStyleTarget, property: u16) -> bool {
if property > crate::css::property_metadata::LAST_LONGHAND_PROPERTY_ID
@@ -289,1627 +57,23 @@ impl RetainedState {
..=crate::css::property_metadata::property_id::TRANSITION_TIMING_FUNCTION)
.contains(&property)
|| crate::css::property_metadata::property_is_in_logical_group(property)
- {
- return false;
- }
- !target.is_pseudo()
- || (property != crate::css::property_metadata::property_id::CONTENT
- && crate::css::property_metadata::pseudo_element_supports_property(target.pseudo_kind(), property))
- }
-
- #[cfg(test)]
- pub(crate) fn engine_constructed_cascade_store(
- &self,
- target: computed::ComputedStyleTarget,
- ) -> Option<CascadedPropertyStore> {
- let answer = self.current_published_answer(target.node())?;
- if !answer.cascade_winners_are_complete {
- return None;
- }
- let key = target.pseudo_element_target().map_or_else(
- || WinnerGroupKey::current(target.node(), self.program.version()),
- |pseudo| WinnerGroupKey::current_pseudo(target.node(), pseudo, self.program.version()),
- );
- let Lookup::Known((_, state)) = self.current_winner_groups().token_for(key) else {
- return None;
- };
-
- let mut store = CascadedPropertyStore::new();
- for winner in self.winner_groups.winners_in_state(state) {
- let winner = self.winner_groups.resolved_winner(winner)?;
- if !Self::retained_store_supports_property(target, winner.property) {
- return None;
- }
- let Some(value) = self.specified_values.retained_value(winner.key.value) else {
- return None;
- };
- if crate::css::style_compute::external_value_dependencies(value.data())
- .may_need_style_sheet_resource_context
- {
- return None;
- }
- store.seed_retained_property(winner.property, value, winner.important, false);
- }
- Some(store)
- }
-
- /// Derive the record a published-style reaction moves `node` to, when the engine can compute
- /// it exactly: the winners that moved compute in the drive's remaining phase from the values
- /// their declarations were written with, against the record's own font, the document's
- /// computation inputs, and the parent's record. Every node of one cohort - the same old
- /// record moved to the same winner state - derives the same record, so the second and later
- /// members take the first one's answer. `full_drive_reason` says why the row's reaction
- /// drives the record again in full whatever its winners did, if it does.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn engine_computed_record_delta(
- &mut self,
- node: StyleNodeID,
- cascade_winners_are_complete: bool,
- exact_flipped_rules: Option<FlippedRules>,
- parent_inputs_moved: ParentInputsMoved,
- full_drive_reason: Option<FullDriveReason>,
- scratch: &mut EngineComputedRecordScratch,
- ) -> Drive<RecordDelta> {
- // A child of an element the host composes once it installs the element's record inherits
- // that composition, which the host has made by the next wave of the pass.
- if self
- .tree
- .inheritance_parent(node)
- .is_some_and(|parent| scratch.nodes_composed_by_the_host.contains(&parent))
- {
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
- return Err(Unanswered::AwaitsParent);
- }
- let delta = self.decide_engine_computed_record_delta(
- node,
- cascade_winners_are_complete,
- exact_flipped_rules,
- parent_inputs_moved,
- full_drive_reason,
- scratch,
- );
- self.apply_substitution_effects(scratch);
- // A record that does not move keeps the composition the children read already, unless the
- // step it owes moves it.
- if let Ok((old, new)) = delta
- && (old != new || self.row_owes_a_transition_step(node))
- && self.host_composes_row(node, old.raw(), new.raw())
- {
- scratch.nodes_composed_by_the_host.insert(node);
- }
- delta
- }
-
- /// Whether a document hosts this engine. The host installs its font resolver when it creates the engine, and
- /// publishes the document's inputs and every table a record is computed against before it asks for any row. An
- /// engine no document hosts, such as a unit test's, computes no records. Only test builds can
- /// create such an engine, so the browser build has no unhosted path at all.
- #[cfg(test)]
- pub(super) fn computes_records(&self) -> bool {
- self.font_resolution.is_some()
- }
-
- /// A browser build's engine always has a document to host it.
- #[cfg(not(test))]
- pub(super) const fn computes_records(&self) -> bool {
- true
- }
-
- /// The step itself, which decides the substituted-record facts rather than writing them.
- #[allow(clippy::too_many_arguments)]
- fn decide_engine_computed_record_delta(
- &mut self,
- node: StyleNodeID,
- cascade_winners_are_complete: bool,
- exact_flipped_rules: Option<FlippedRules>,
- parent_inputs_moved: ParentInputsMoved,
- full_drive_reason: Option<FullDriveReason>,
- scratch: &mut EngineComputedRecordScratch,
- ) -> Drive<RecordDelta> {
- if !self.computes_records() {
- self.counters.bump(Counter::EngineComputedRecordBailUnhosted);
- return Err(Unanswered::Refused);
- }
- let pending_element = drive::PendingElement::take_for(&mut scratch.pending_element, node);
- if pending_element.is_none() {
- scratch.pseudo_deltas.clear();
- scratch.next_pseudo = 0;
- scratch.pseudo_uses_substitution = false;
- scratch.noted_substitution = None;
- scratch.element_explicitly_inherited_groups = 0;
- scratch.flipped_pseudo_rules = exact_flipped_rules.map_or(0, |flipped| flipped.pseudos);
- }
- let delta = match pending_element {
- Some(delta) => delta,
- None => self
- .engine_computed_element_record_delta(
- node,
- cascade_winners_are_complete,
- exact_flipped_rules,
- parent_inputs_moved,
- full_drive_reason,
- scratch,
- FontDriveGoal::Complete,
- )?
- .delta(),
- };
- // A pseudo-element's container conditions ask about its originating element first, whose
- // record may have just made it another container: pseudo-element winners whose verdicts
- // moved with it are published again from the node's retained answer. What the verdicts
- // read of the element as a container is known only now, and the host takes it with the
- // record.
- if self.container_verdicts_moved(node) {
- if scratch.winner_republication().is_none_or(|republication| {
- self.republish_pseudo_winners_from_retained_answer(node, republication)
- .is_none()
- }) || !self.container_verdicts_stand(node, VerdictTargets::ElementAndPseudoElements)
- {
- self.counters.bump(Counter::EngineComputedRecordBailIncompleteWinners);
- self.abandon_engine_computed_record(node, scratch);
- return Err(Unanswered::Refused);
- }
- } else {
- self.note_pseudo_container_effects_for_host(node);
- }
- // The element's pseudo-elements are settled beside its record, as the C++ computation
- // refreshes them after the element's own; a pseudo-element the engine cannot settle
- // sends the whole element to C++.
- let generation = self.winner_groups.generation();
- if let Err(unanswered) =
- self.engine_pseudo_records_beside(node, delta, None, generation, full_drive_reason, scratch)
- {
- match unanswered {
- Unanswered::Suspended(_) => scratch.pending_element = Some(drive::PendingElement::new(node, delta)),
- Unanswered::Refused | Unanswered::AwaitsParent => {
- self.abandon_engine_computed_record(node, scratch);
- }
- }
- return Err(unanswered);
- }
- // What this element's record was computed from decides the fact when the computation
- // noted it; a record that stands unchanged keeps the fact the node already carries.
- let uses_substitution = scratch
- .noted_substitution
- .unwrap_or_else(|| self.nodes_with_substituted_records.contains(&node))
- || scratch.pseudo_uses_substitution
- || self
- .current_winner_groups()
- .pseudo_states(node)
- .any(|(_, version, state, priority_current)| {
- version == self.program.version() && priority_current && self.state_has_substitutions(node, state)
- });
- scratch.element_uses_substitution = uses_substitution;
- scratch.substitution_effects.push((node, uses_substitution));
- Ok(delta)
- }
-
- /// The winners a driven element's record is computed from. An answer that published nothing is
- /// matched again; a row that holds
- /// no winners even then is the host's, as is one a drive without the leave to republish holds
- /// no winners for.
- fn driven_element_winners(
- &mut self,
- node: StyleNodeID,
- winner_key: WinnerGroupKey,
- republication: Option<WinnerRepublication>,
- ) -> Option<(u64, CascadeStateID)> {
- if let Lookup::Known(token) = self.current_winner_groups().token_for(winner_key) {
- return Some(token);
- }
- self.rematch_driven_winners(node, republication?);
- let token = match self.current_winner_groups().token_for(winner_key) {
- Lookup::Known(token) => Some(token),
- _ => None,
- };
- debug_assert!(
- token.is_some(),
- "a driven element holds no winners after matching again"
- );
- token
- }
-
- /// `exact_flipped_rules` are the rules that flipped for the node when the reaction is exactly
- /// those flips and nothing else the record depends on moved. `parent_inputs_moved` says which
- /// of the parent's inputs may have moved under the record.
- #[allow(clippy::too_many_arguments)]
- fn engine_computed_element_record_delta(
- &mut self,
- node: StyleNodeID,
- mut cascade_winners_are_complete: bool,
- exact_flipped_rules: Option<FlippedRules>,
- parent_inputs_moved: ParentInputsMoved,
- full_drive_reason: Option<FullDriveReason>,
- scratch: &mut EngineComputedRecordScratch,
- goal: FontDriveGoal,
- ) -> Drive<ElementAnswer> {
- use crate::css::computed_value_types::{
- STYLE_GROUP_INDEX_ANCHOR, STYLE_GROUP_INDEX_FONT, STYLE_GROUP_INDEX_SURROUND,
- };
- use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LONGHAND_WORD_COUNT};
-
- let target = computed::ComputedStyleTarget::new(node, u8::MAX);
- // An element standing for its host's pseudo-element is cascaded from the host's rules.
- if let Some(backed) = self.backed_host_pseudo_element(node) {
- return self
- .engine_backing_element_record(node, backed, cascade_winners_are_complete, scratch)
- .map(ElementAnswer::Delta);
- }
- // A row left out of winner publication can still carry a retained selector answer.
- // Rebuild its winners before comparing them with the record's cascade state: otherwise
- // an empty delta can describe yesterday's answer after this flush flipped a rule. So does
- // a row that holds no winners for the current program at all. Exact flips of
- // pseudo-element rules alone leave the element row as it was: the pseudo rows are
- // refreshed where the pseudo-elements settle.
- let winner_key = WinnerGroupKey::current(node, self.program.version());
- let stale_element_winners = (scratch.answer_or_declarations_moved
- && exact_flipped_rules.is_none_or(|flipped| flipped.element)
- && self.current_winner_groups().row_stamp(node) != Some(self.flush_stamp))
- || !matches!(self.current_winner_groups().token_for(winner_key), Lookup::Known(_));
- if stale_element_winners {
- // A read-only demand's drive reads the rows its private traversal published. One it
- // would have to republish is the host's: the republished row would outlive the demand.
- let Some(republication) = scratch.winner_republication() else {
- self.counters.bump(Counter::EngineComputedRecordBailWinner);
- return Err(Unanswered::Refused);
- };
- cascade_winners_are_complete = self.republish_driven_winners(node, republication);
- }
- // The winners hold a gated rule where its container conditions held when they were
- // published; they answer for the node while every one decides as it did, over containers
- // its settled ancestors published. One a declined ancestor may still move waits for the
- // host to install that ancestor's record, as a row waits for its parent's. Winners
- // published while an ancestor was moving, or whose verdicts moved since (a container
- // resized, or an ancestor whose container type moved or that left display:none, whose
- // record this batch settled before the node), are published again from the node's
- // retained answer, over the containers as they stand now.
- if self.node_holds_container_gates(node) {
- if self.container_ancestor_is_unsettled(node, scratch) {
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
- return Err(Unanswered::AwaitsParent);
- }
- if self.container_winners_are_stale(node) {
- let Some(complete) = scratch
- .winner_republication()
- .and_then(|republication| self.republish_winners_from_answer(node, republication))
- else {
- self.counters.bump(Counter::EngineComputedRecordBailIncompleteWinners);
- return Err(Unanswered::Refused);
- };
- cascade_winners_are_complete = complete;
- }
- // A container the host styles in this update decides the verdicts once it is installed.
- // Those of the pseudo-elements are decided over the element's record, once it is settled.
- if !self.container_verdicts_stand(node, VerdictTargets::Element) {
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
- return Err(Unanswered::AwaitsParent);
- }
- }
- // A custom property the cascade declares is no winner the columns hold; the engine
- // computes the environment it decides itself.
- if !cascade_winners_are_complete && !self.cascade_winners_are_complete_but_for_custom_properties(node) {
- self.counters.bump(Counter::EngineComputedRecordBailIncompleteWinners);
- return Err(Unanswered::Refused);
- }
- // The winners the record was computed from, against the winners the node holds now: the
- // same comparison a C++ publication makes to select what it recomputes.
- let Some((generation, state)) = self.driven_element_winners(node, winner_key, scratch.winner_republication())
- else {
- self.counters.bump(Counter::EngineComputedRecordBailWinner);
- return Err(Unanswered::Refused);
- };
- let facts = self.computed_group_sets.adjustment_facts(node);
- // Moved root inputs reach every row below the root. The root's font the root-input probe
- // drove is left pending for the root's own row, which resumes it in full the same way.
- let root_inputs_moved = if facts & bridge::element_adjustment_fact::IS_DOCUMENT_ELEMENT != 0 {
- scratch.font_drive.is_pending_for(node)
- } else {
- scratch.root_font_inputs_changed
- };
- // An element's animations compose over the record its winners decide, and the host samples
- // them over the record it installs. A record demand installs none of its own.
- if facts & bridge::element_adjustment_fact::HAS_ANIMATIONS != 0 && !scratch.host_applies_animation_plans {
- self.counters.bump(Counter::EngineComputedRecordBailWinnerElement);
- return Err(Unanswered::Refused);
- }
- let Some(old_style_record) = self.computed_group_sets.assigned_style_record(node) else {
- return self.engine_cold_record(node, (generation, state), scratch, goal);
- };
- // A row derives the record beneath the composition the element's animations laid over it:
- // the delta starts at the record the winners decided, and the composition stays the record
- // the row moves the element away from.
- let Some(underlying_style_record) = self.computed_group_sets.underlying_style_record(old_style_record) else {
- self.counters.bump(Counter::EngineComputedRecordBailRecordOverlay);
- return Err(Unanswered::Refused);
- };
- let composes_animations = underlying_style_record != old_style_record;
- if composes_animations && !scratch.host_applies_animation_plans {
- self.counters.bump(Counter::EngineComputedRecordBailRecordOverlay);
- return Err(Unanswered::Refused);
- }
- // A record C++ computed holds no cascade state, so there is no earlier state to take a
- // delta from, and the state of a record from a replaced rule program names winners of
- // another generation: either record is driven again in full from the node's winners,
- // which binds the state. The old record still supplies the before-change values.
- let (mut delta, holds_no_current_cascade_state) = match self.computed_group_sets.cascade_state(target) {
- Some((previous_generation, previous_state)) if previous_generation == generation => {
- (self.winner_groups.semantic_delta(Some(previous_state), state), false)
- }
- Some(_) | None => (self.winner_groups.semantic_delta(Some(state), state), true),
- };
- // No delta names the winners such a record is driven from, so they are checked as a first
- // record's are: one starting an animation keeps the record in C++, unless it declares CSS
- // animations and the host can be handed the plan the record decides.
- if holds_no_current_cascade_state
- && self
- .winner_groups
- .semantic_delta_properties(None, state)
- .any(|property| {
- self.first_record_winner_needs_cpp(property)
- && !(property_declares_css_animations(property)
- && self.may_plan_css_animations(node, state, scratch))
- })
- {
- self.counters.bump(Counter::EngineComputedRecordBailProperty);
- return Err(Unanswered::Refused);
- }
- let mut inputs = self.document_style_computation_inputs;
- if let Some((root, root_inputs)) = scratch.root_element_inputs
- && root == node
- {
- root_inputs.apply_to(&mut inputs);
- }
- // The environment the node's own custom declarations resolve to over the parent's. A node
- // declaring none keeps its record's, which is the parent's; a moved environment
- // republishes the record under the new one. A registered name declared here computes
- // against the record's font until a drive settles the font anew.
- let has_registered_declarations = self.declares_registered_custom_property(node, None, &inputs);
- let initial_registered_context =
- has_registered_declarations.then(|| self.standing_registered_value_context(node, None));
- // Every installed record is published with an environment; a record without is
- // republished as moved.
- let old_environment = self
- .computed_group_sets
- .style_record_custom_property_environment(underlying_style_record.raw());
- debug_assert!(
- old_environment.is_some(),
- "an installed record was published with a custom-property environment"
- );
- let (mut environment, mut current_environment, parent_environment) = {
- let parent = self
- .record_inheritance_parent(node)
- .inspect_err(|_| self.counters.bump(Counter::EngineComputedRecordBailRecordParent))?;
- let parent_environment = match parent {
- Some(parent) => self.held_custom_property_environment(parent)?,
- None => 0,
- };
- // A function's container condition the engine cannot decide yet waits, as the row does.
- let environment = self
- .engine_custom_property_environment_by_answer(node, parent_environment, &inputs)
- .inspect_err(|&unanswered| {
- if unanswered == Unanswered::Refused {
- self.counters.bump(Counter::EngineComputedRecordBailCustomProperties);
- }
- })?;
- // An unmoved environment is the one the record holds, so the current one is always
- // what the declarations resolved to.
- (
- (old_environment != Some(environment)).then_some(environment),
- environment,
- parent_environment,
- )
- };
- // OPTIMIZATION: Compare substituted declarations so an environment move reaches only its changed values.
- let substituted_delta = if environment.is_some()
- && !self.custom_property_registrations_changed
- && !has_registered_declarations
- && !self.state_reads_beyond_environment(node, state)
- && self.state_has_substitutions(node, state)
- && let Some(old_environment) = old_environment
- {
- let old_store = self.cached_winner_store(node, state, old_environment, parent_environment, scratch)?;
- let new_store = self.cached_winner_store(node, state, current_environment, parent_environment, scratch)?;
- old_store.environment_value_delta(&new_store, self)
- } else {
- None
- };
- let substitutions_unchanged = substituted_delta
- .as_ref()
- .is_some_and(|properties| properties.is_empty());
- if let Some(properties) = &substituted_delta {
- delta.include_substituted_properties(properties);
- }
- // A record driven from its winners alone takes its transition declarations from them. A
- // moved display is applied after the step, as C++ applies it after the step it runs. The row
- // carries what is decided here to the host, for a record that moves.
- let moves_transition_declarations = if holds_no_current_cascade_state {
- self.winner_groups
- .semantic_delta_properties(None, state)
- .any(property_declares_transitions)
- } else {
- delta
- .properties()
- .iter()
- .any(|&property| property_declares_transitions(property))
- };
- let owes_a_transition_step = self.decide_transition_step(
- node,
- underlying_style_record,
- moves_transition_declarations,
- scratch.host_applies_animation_plans,
- )?;
- // A step decides over a moved base record, or over one an ancestor's moved style reaches
- // without moving it: the base the record holds an inherited animated value of.
- let owes_a_transition_step_to = |new_style_record| {
- owes_a_transition_step
- && (new_style_record != underlying_style_record || parent_inputs_moved.inherited_style)
- };
- // A moved environment reaches every winner written with a substitution, and so does a
- // moved custom-property registry. A winner written with `attr()` computes to what the
- // element's attributes hold now, one written with `inherit()` to what the parent's
- // environment holds now, one written with `if()` to what its conditions say now, one
- // calling a custom function to what the function's definition says now, one reading the
- // element's place among its siblings to where it stands now, and one written with a
- // container-relative length to what its containers measure now, which no winner delta
- // shows. Such a record is driven again in full, as is one holding no current cascade
- // state, one under a moved document environment, one whose reaction stands for inputs no
- // winner shows, and one that rolled a property back below a substituted revert keyword,
- // to declarations no winner names.
- let drive_in_full = holds_no_current_cascade_state
- || scratch.document_environment_moved
- || (scratch.viewport_moved && self.record_reads_the_viewport(underlying_style_record))
- || full_drive_reason.is_some()
- // NB: An overlay that adjusts the base's display, overflow or other driver inputs
- // needs their unadjusted values rebuilt before the host composes it again.
- || (composes_animations
- && self.computed_group_sets.style_record_view(old_style_record.raw()).is_some_and(|view| {
- view.animated_overlay.is_some_and(|overlay| {
- overlay.entries().iter().any(|entry| {
- entry.post_compute_adjustment
- || !property_computes_in_remaining_phase(entry.property)
- || crate::css::style_compute::is_required_driver_input(entry.property)
- || property_feeds_box_type_transformation(entry.property)
- })
- })
- }))
- || (((environment.is_some() && substituted_delta.is_none()) || self.custom_property_registrations_changed)
- && self.state_has_substitutions(node, state))
- || self.state_reads_beyond_environment(node, state)
- || self.record_reads_sibling_position(node, state)
- || self.record_rolls_back_substitution(node);
- // The winners the record was computed from are the winners now when the delta is empty;
- // the flips the reaction holds are reflected in them once the row holds the cascade of
- // the node's current answer (custom properties are no winners).
- let flips_are_reflected = exact_flipped_rules.is_some_and(|flipped| {
- !flipped.element || self.current_winner_groups().row_stamp(node) == Some(self.flush_stamp)
- });
- // The document element's own record stays with C++ when nothing says why it is asked
- // for, but nothing says its font inputs moved either: keep the host's root-metric route
- // rather than declaring the root's computation unsupported, which takes every descendant
- // with it.
- if goal == FontDriveGoal::RootInputs && delta.is_empty() && !flips_are_reflected {
- return Ok(ElementAnswer::RootInputs(None));
- }
- let inherited_text_moved = parent_inputs_moved.inherited_style
- && parent_inputs_moved.inherited_style_groups
- == 1 << crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_TEXT;
- let inherited_text_can_be_partial = inherited_text_moved
- && !parent_inputs_moved.display
- && !root_inputs_moved
- && !drive_in_full
- && !(has_registered_declarations && environment.is_some())
- && delta.properties().iter().all(|&property| {
- property_computes_in_remaining_phase(property) && !property_feeds_box_type_transformation(property)
- });
- let scope = if inherited_text_can_be_partial {
- DriveScope::Partial
- } else {
- self.record_drive_scope(
- node,
- state,
- &delta,
- flips_are_reflected,
- parent_inputs_moved.any() || root_inputs_moved || drive_in_full,
- environment,
- has_registered_declarations,
- scratch.pseudo_inputs_alone,
- substitutions_unchanged,
- )
- };
- match scope {
- DriveScope::Stands | DriveScope::Environment(_) if goal == FontDriveGoal::RootInputs => {
- // NB: This proof covers the retained font, without publishing the root's
- // remaining properties or custom-property environment during preparation.
- return Ok(ElementAnswer::RootInputs(Some(
- self.root_font_inputs_from_record(old_style_record).or_refused()?,
- )));
- }
- // A record reading its place among its siblings is driven in full, so one that stands
- // reads none.
- DriveScope::Stands => {
- self.counters.bump(Counter::EngineComputedRecordUnchangedWinners);
- self.counters.bump(Counter::CascadeWinnerDeltaStops);
- let replaced = self.computed_group_sets.replaced_columns(node);
- self.note_engine_computed_record(
- node,
- (old_style_record, old_style_record),
- replaced,
- (generation, state),
- false,
- 0,
- 0,
- );
- return Ok(ElementAnswer::Delta((old_style_record, old_style_record)));
- }
- DriveScope::Environment(environment) => {
- let replaced = self.computed_group_sets.replaced_columns(node);
- // NB: Publish the changed environment on the base before the host resamples its effects,
- // as a driven record does. Keep the detached composition until the row is installed.
- let detached_composition = composes_animations
- .then(|| self.computed_group_sets.detach_composition(node))
- .flatten();
- let Some((_, new_style_record)) = self
- .computed_group_sets
- .republish_engine_record_with_environment(node, environment)
- else {
- if let Some(detached) = detached_composition {
- self.computed_group_sets.reattach_composition(node, detached);
- }
- return Err(Unanswered::Refused);
- };
- let delta = (old_style_record, new_style_record);
- self.counters.bump(Counter::EngineComputedRecordUnchangedWinners);
- let pending = self.note_engine_computed_record(node, delta, replaced, (generation, state), false, 0, 0);
- pending.detached_composition = detached_composition;
- pending.owes_a_transition_step = owes_a_transition_step_to(delta.1);
- return Ok(ElementAnswer::Delta(delta));
- }
- // Standing winners driven in full for a reason they do not show still stop the
- // cascade's winner delta.
- DriveScope::Full if delta.is_empty() => self.counters.bump(Counter::CascadeWinnerDeltaStops),
- DriveScope::Partial | DriveScope::Full => {}
- }
- let full_drive = scope == DriveScope::Full;
- let delta_property_count = delta.properties().len() as u64;
- // Partial drives can share across parents whose inherited inputs agree. Keep the full
- // parent record in the key when a non-inherited property explicitly inherits, including
- // through substitution, or when a full drive may read more of the parent's style.
- let parent = self.tree.inheritance_parent(node);
- let parent_record = parent.and_then(|parent| self.computed_group_sets.assigned_style_record(parent));
- // A record whose winners read beyond its environment is the element's alone, as is one
- // driven in full under registered custom properties, which its own font decides.
- let record_is_the_elements_alone =
- self.state_reads_beyond_environment(node, state) || (has_registered_declarations && full_drive);
- let exact_cohort = (!record_is_the_elements_alone).then(|| {
- (
- underlying_style_record.raw(),
- state,
- facts,
- RecordDeltaParent::Exact(parent_record.map_or(0, |record| record.raw())),
- // An unchanged environment is not necessarily empty. Distinguish it from a
- // record moving to the empty environment when both started with the same style.
- current_environment,
- RootFontInputs::from_document(&inputs),
- self.monospace_cohort_key(computed::ComputedStyleTarget::new(node, u8::MAX), state),
- self.sibling_position_key(node, state),
- )
- });
- // OPTIMIZATION: Try the exact parent record before deriving its sharing inputs. Siblings
- // commonly share it, so repeating the proof costs more than the partial drive.
- let mut cohort = exact_cohort;
- if exact_cohort.is_some_and(|key| !scratch.cohorts.contains_key(&key))
- && !full_drive
- && let (Some(parent), Some(parent_record)) = (parent, parent_record)
- && !self.state_has_substitutions(node, state)
- && let Some(inputs) = self.cold_record_parent(node, parent, parent_record, state)
- && let Some(key) = cohort.as_mut()
- {
- key.3 = RecordDeltaParent::Inputs(inputs);
- }
- if let Some(&(new_style_record, explicitly_inherited_groups, reads_sibling_position)) = cohort
- .as_ref()
- .and_then(|cohort| scratch.cohorts.get(cohort))
- .filter(|&&(record, ..)| self.record_answers_counter_styles_for(record, node))
- {
- if let Some(exact_cohort) = exact_cohort {
- scratch.cohorts.insert(
- exact_cohort,
- (new_style_record, explicitly_inherited_groups, reads_sibling_position),
- );
- }
- self.note_node_substitution(node, scratch, state, current_environment);
- // The mark is per node: an element taking the record owes its own parent the mark.
- scratch.element_explicitly_inherited_groups = explicitly_inherited_groups;
- let detached_composition = composes_animations
- .then(|| self.computed_group_sets.detach_composition(node))
- .flatten();
- let Some(replaced) =
- self.computed_group_sets
- .assign_engine_computed_record(node, underlying_style_record, new_style_record)
- else {
- if let Some(detached) = detached_composition {
- self.computed_group_sets.reattach_composition(node, detached);
- }
- return Err(Unanswered::Refused);
- };
- let delta = (old_style_record, new_style_record);
- if delta.0 == delta.1 {
- self.counters.bump(Counter::ComputedWinnerPropagationStops);
- }
- let pending = self.note_engine_computed_record(
- node,
- delta,
- replaced,
- (generation, state),
- reads_sibling_position,
- delta_property_count,
- 0,
- );
- pending.detached_composition = detached_composition;
- pending.owes_a_transition_step = owes_a_transition_step_to(delta.1);
- self.counters.bump(Counter::EngineComputedRecordCohortHits);
- return Ok(ElementAnswer::Delta(delta));
- }
-
- // The moved properties, the groups they feed, and the drive selection. A moved member of
- // a logical property group takes its counterpart along: which of the pair the other
- // derives from is a cascade decision the drive makes for both.
- let mut groups_to_rebuild = 0_u32;
- let mut selected = [0_u64; LONGHAND_WORD_COUNT];
- let mut select = |property: u16| {
- let index = usize::from(property - FIRST_LONGHAND_PROPERTY_ID);
- selected[index / 64] |= 1 << (index % 64);
- };
- // The record being driven again has a view. A record without one cannot say what a
- // partial drive would leave standing: it is driven in full.
- let mut old_record_is_unreadable = false;
- let (writing_mode, direction) = match self
- .computed_group_sets
- .style_record_view(underlying_style_record.raw())
- {
- Some(view) => {
- let inherited_box = unsafe {
- view.payloads[crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_BOX]
- .cast::<crate::css::computed_values::InheritedBoxValues>()
- .deref()
- };
- (inherited_box.writing_mode, inherited_box.direction)
- }
- None => {
- debug_assert!(false, "the record being driven again has a view");
- old_record_is_unreadable = true;
- (
- crate::css::css_enums::writing_mode::HORIZONTAL_TB,
- crate::css::css_enums::direction::LTR,
- )
- }
- };
- let mut inherited_text_needs_full_drive = false;
- if inherited_text_can_be_partial {
- // NB: Group members are validated while selecting them, after cohort lookup, so
- // siblings reusing the same result do not repeat the phase checks.
- groups_to_rebuild |= 1 << crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_TEXT;
- for property in FIRST_LONGHAND_PROPERTY_ID..=crate::css::property_metadata::LAST_LONGHAND_PROPERTY_ID {
- if crate::css::property_metadata::property_style_group_index(property)
- == Some(crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_TEXT as u8)
- {
- inherited_text_needs_full_drive |= !property_computes_in_remaining_phase(property);
- select(property);
- }
- }
- }
- for &property in delta.properties() {
- // Any animation the engine cannot hand the host a plan for starts from the C++
- // computation; a transition declaration is the step's to act on.
- if property_starts_animation(property)
- && !property_declares_transitions(property)
- && !(property_declares_css_animations(property) && self.may_plan_css_animations(node, state, scratch))
- {
- self.counters.bump(Counter::EngineComputedRecordBailProperty);
- return Err(Unanswered::Refused);
- }
- groups_to_rebuild |= moved_longhand_groups(property);
- select(property);
- let bits = crate::css::style_compute::table_row_bits(property);
- let counterpart = if bits & crate::css::style_compute::LOGICAL_ALIAS_BIT != 0 {
- crate::css::style_compute::map_logical_alias_to_physical(property, writing_mode, direction)
- } else if bits & crate::css::style_compute::PHYSICAL_TO_LOGICAL_BIT != 0 {
- crate::css::style_compute::map_physical_to_logical_alias(property, writing_mode, direction)
- } else {
- property
- };
- if counterpart != property {
- groups_to_rebuild |= moved_longhand_groups(counterpart);
- select(counterpart);
- }
- }
- if groups_to_rebuild & (1 << STYLE_GROUP_INDEX_ANCHOR) != 0 {
- groups_to_rebuild |= 1 << STYLE_GROUP_INDEX_SURROUND;
- }
- // A moved `color` reaches every group holding a value resolved against currentcolor.
- if delta
- .properties()
- .contains(&crate::css::property_metadata::property_id::COLOR)
- || inherited_text_can_be_partial
- {
- // A record holding no table cannot say which values read currentcolor: it is driven
- // in full, as a partial drive of it is.
- let dependencies = self.computed_group_sets.current_color_dependency_mask(target);
- let dependent_properties = self.computed_group_sets.current_color_dependency_properties(target);
- old_record_is_unreadable |= dependencies.is_none() || dependent_properties.is_none();
- groups_to_rebuild |= dependencies.unwrap_or(0);
- // The dependents compute again from their specified values, so the table spells them
- // the way a fresh computation does, not the way an inherited-group swap resolved them.
- let dependent_properties = dependent_properties.unwrap_or_default();
- for (word, &bits) in dependent_properties.iter().enumerate() {
- let mut bits = bits;
- while bits != 0 {
- let bit = bits.trailing_zeros() as usize;
- bits &= bits - 1;
- let property = FIRST_LONGHAND_PROPERTY_ID + (word * 64 + bit) as u16;
- select(property);
- if crate::css::style_compute::table_row_bits(property)
- & crate::css::style_compute::LOGICAL_ALIAS_BIT
- != 0
- {
- select(crate::css::style_compute::map_logical_alias_to_physical(
- property,
- writing_mode,
- direction,
- ));
- }
- }
- }
- }
- // A partial delta that reaches the font group reaches every value the font feeds, so it is
- // driven in full, as a partial drive whose driver inputs moved is below, and so is one of
- // a record that cannot say what it would leave standing.
- let mut in_full_after_all = !full_drive
- && (old_record_is_unreadable
- || inherited_text_needs_full_drive
- || groups_to_rebuild & (1 << STYLE_GROUP_INDEX_FONT) != 0);
- if goal == FontDriveGoal::RootInputs && !full_drive && !in_full_after_all {
- // NB: No font property moved, but borrowing the retained font still needs the
- // proof that only the named rule flips changed the computation's inputs.
- if exact_flipped_rules.is_some() {
- return Ok(ElementAnswer::RootInputs(Some(
- self.root_font_inputs_from_record(old_style_record).or_refused()?,
- )));
- }
- // Without that proof the root's font is computed rather than borrowed.
- in_full_after_all = true;
- }
- if full_drive || in_full_after_all {
- groups_to_rebuild = (1 << crate::css::table_group_builder::group_index::COUNT) - 1;
- }
-
- let mut store = self.cached_winner_store(node, state, current_environment, parent_environment, scratch)?;
- self.note_node_substitution(node, scratch, state, current_environment);
- let partial = if full_drive || in_full_after_all {
- None
- } else {
- Some(self.engine_driven_table(node, underlying_style_record, &store, &selected, &inputs)?)
- };
- let driver_input_moved = matches!(partial, Some(PartialDrive::DriverInputMoved));
- let DrivenTable {
- table,
- length,
- longhand_evaluations,
- font,
- explicitly_inherited_groups,
- } = match partial {
- Some(PartialDrive::Driven(partial)) => partial,
- // A partial drive whose driver inputs moved reaches values it did not select, so the
- // record is driven in full and every group is rebuilt.
- Some(PartialDrive::DriverInputMoved) | None => {
- if driver_input_moved {
- groups_to_rebuild = (1 << crate::css::table_group_builder::group_index::COUNT) - 1;
- }
- let subject = self.element_drive_subject(node)?;
- let mut driven = self.engine_full_drive(
- subject,
- Some(underlying_style_record),
- &store,
- &inputs,
- &mut scratch.font_drive,
- goal,
- initial_registered_context.as_ref(),
- )?;
- // The registered custom properties compute against the font the drive settled,
- // and the winners substitute what they computed to.
- if let FullDrive::AwaitsRegisteredContext(registered) = driven {
- let (settled, settled_store, _) = self.store_over_registered_context(
- subject.target,
- state,
- parent_environment,
- |engine| {
- engine
- .engine_custom_property_environment(
- node,
- parent_environment,
- &inputs,
- Some(&registered),
- )
- .inspect_err(|&unanswered| {
- if unanswered == Unanswered::Refused {
- engine.counters.bump(Counter::EngineComputedRecordBailCustomProperties);
- }
- })
- },
- scratch,
- )?;
- current_environment = settled;
- environment = (old_environment != Some(settled)).then_some(settled);
- store = std::sync::Arc::new(settled_store);
- self.note_node_substitution(node, scratch, state, current_environment);
- driven = self.engine_full_drive(
- subject,
- Some(underlying_style_record),
- &store,
- &inputs,
- &mut scratch.font_drive,
- goal,
- None,
- )?;
- }
- match driven {
- FullDrive::Driven(driven) => driven,
- FullDrive::RootInputs(root_inputs) => return Ok(ElementAnswer::RootInputs(Some(root_inputs))),
- FullDrive::AwaitsRegisteredContext(_) => {
- unreachable!("a drive resumed with its registered context waits for nothing")
- }
- }
- }
- };
- let parent_in_display_none_subtree = self
- .tree
- .inheritance_parent(node)
- .and_then(|parent| self.computed_group_sets.assigned_style_record(parent))
- .and_then(|record| self.computed_group_sets.style_record_view(record.raw()))
- .is_some_and(|view| view.dependency_flags & (1 << 2) != 0);
- // The record names the counter-style registry its `content` or `list-style-type` reads,
- // which a moved `content` may have started or stopped reading.
- let counter_style_registry = self.table_counter_style_environment_identity(target, &table);
- let detached_composition = composes_animations
- .then(|| self.computed_group_sets.detach_composition(node))
- .flatten();
- let assembly = self.computed_group_sets.replace_engine_computed_table(
- node,
- underlying_style_record,
- old_style_record,
- table,
- groups_to_rebuild,
- &length,
- font.as_ref(),
- parent_in_display_none_subtree,
- environment,
- Some(counter_style_registry),
- );
- let Some(assembly) = assembly else {
- if let Some(detached) = detached_composition {
- self.computed_group_sets.reattach_composition(node, detached);
- }
- return Err(Unanswered::Refused);
- };
- self.counters.add(
- Counter::ComputedOutputGroupsCanonicalized,
- u64::from(assembly.canonicalized_groups),
- );
- if assembly.group_set_unchanged {
- self.counters.bump(Counter::ComputedWinnerPropagationStops);
- }
- let delta = assembly.delta;
- // The record reads the element's place among its siblings where its state's winners do, as
- // the store substitutes them.
- let reads_sibling_position = store.uses_tree_counting_function(self);
- let pending = self.note_engine_computed_record(
- node,
- delta,
- assembly.replaced,
- (generation, state),
- reads_sibling_position,
- delta_property_count,
- longhand_evaluations,
- );
- pending.detached_composition = detached_composition;
- pending.owes_a_transition_step = owes_a_transition_step_to(delta.1);
- // A record driven in full stands for a cohort keyed by the parent's inherited inputs only
- // when the drive was partial.
- if !driver_input_moved
- && !self.records_are_the_elements_alone(node)
- && let Some(cohort) = cohort
- {
- let record = (delta.1, explicitly_inherited_groups, reads_sibling_position);
- scratch.cohorts.insert(cohort, record);
- if let Some(exact_cohort) = exact_cohort {
- scratch.cohorts.insert(exact_cohort, record);
- }
- }
- scratch.element_explicitly_inherited_groups = explicitly_inherited_groups;
- Ok(ElementAnswer::Delta(delta))
- }
-
- /// Move the record the host holds for a node to the environment C++ refreshed its inherited
- /// custom-property data to, without recomputing anything: what an inherited-custom-properties
- /// reaction C++ settled by refreshing the data alone publishes. The host installs it in the
- /// middle of a batch, so it is never a record the engine assigned for a row the host has yet to
- /// apply, which moves more than the environment. The new record's identity, or nothing when the
- /// node holds no record to move.
- pub(crate) fn republish_record_environment(&mut self, node: StyleNodeID, environment: u64) -> Option<u64> {
- let held_style_record = computed::FinalStyleRecordID::from_raw(*self.held_style_records.get(&node)?)?;
- // Only a base record moves to another environment by itself, so an environment move computes an element holding
- // one that composes animated values again instead. Left unmoved, the record would not name the environment the
- // host holds, and the host would refuse every record the engine computes for a child of the element.
- assert!(
- !held_style_record.is_animation_overlay(),
- "a record composing animated values cannot move to another environment"
- );
- self.computed_group_sets
- .republish_style_record_with_environment(node, held_style_record, environment)
- .map(|style_record| style_record.raw())
- }
-
- /// Note whether the node's record was computed with a substituted winner, for C++ to record
- /// the node as a reader of custom properties when it installs the record. The step records
- /// the fact; the boundary that installs the record applies it.
- fn note_node_substitution(
- &self,
- node: StyleNodeID,
- scratch: &mut EngineComputedRecordScratch,
- state: CascadeStateID,
- environment: u64,
- ) {
- let substituted = scratch.substituted_states.contains(&(state, environment));
- scratch.noted_substitution = Some(substituted);
- scratch.substitution_effects.push((node, substituted));
- }
-
- /// The environment and store a full drive resumes with once it settled the context the
- /// target's registered custom properties compute against: `resolve_environment` resolves the
- /// target's custom declarations again with that context, and the state's winners substitute
- /// what they computed to. Returns the settled environment, the store and whether it
- /// substituted.
- fn store_over_registered_context(
- &mut self,
- target: computed::ComputedStyleTarget,
- state: CascadeStateID,
- inherited_environment: u64,
- resolve_environment: impl FnOnce(&mut Self) -> Drive<u64>,
- scratch: &mut EngineComputedRecordScratch,
- ) -> Drive<(u64, WinnerStore, bool)> {
- let environment = resolve_environment(self)?;
- let mut substituted = false;
- let store = self.cascaded_store_for_state(
- target.node(),
- state,
- target.is_pseudo().then_some(target.pseudo_kind()),
- custom_property_cascade::SubstitutionEnvironment {
- own: environment,
- inherited: inherited_environment,
- },
- &mut substituted,
- )?;
- if substituted {
- scratch.substituted_states.insert((state, environment));
- }
- Ok((environment, store, substituted))
- }
-
- /// Write the substituted-record facts the step decided. The set is a retained per-node fact
- /// C++ reads when it installs a record, so the step decides it once and the record's
- /// installation boundary writes it once, rather than the step reading its own writes back.
- fn apply_substitution_effects(&mut self, scratch: &mut EngineComputedRecordScratch) {
- for (node, uses_substitution) in scratch.substitution_effects.drain(..) {
- if uses_substitution {
- self.nodes_with_substituted_records.insert(node);
- } else {
- self.nodes_with_substituted_records.remove(&node);
- }
- }
- }
-
- /// Account for an element record the engine derived, which reads the node's place among its
- /// siblings as `reads_sibling_position` says, in place of whatever the record it replaces read.
- #[allow(clippy::too_many_arguments)]
- fn note_engine_computed_record(
- &mut self,
- node: StyleNodeID,
- delta: (computed::FinalStyleRecordID, computed::FinalStyleRecordID),
- replaced: computed::ReplacedColumns,
- cascade_state: (u64, CascadeStateID),
- reads_sibling_position: bool,
- delta_property_count: u64,
- longhand_evaluations: u32,
- ) -> &mut PendingEngineComputedRecord {
- self.counters
- .add(Counter::CascadeWinnerDeltaProperties, delta_property_count);
- self.counters
- .add(Counter::ComputedWinnerDeltaPropertiesConsumed, delta_property_count);
- self.counters.bump(Counter::EngineComputedRecordDeltas);
- // The containers the node's descendants ask about are the ones its settled record
- // describes, as the host publishes them when it installs a record: a descendant this batch
- // derives after it reads the container as the host will leave it.
- self.set_element_container_query_inputs(node, delta.1.raw());
- self.note_sibling_position_reads(node, u8::MAX, reads_sibling_position);
- self.note_container_unit_effects_for_host(node, false, cascade_state.1, delta.0);
- let records = self.engine_computed_records_pending.entry(node).or_default();
- records.push(PendingEngineComputedRecord {
- node,
- pseudo_kind: u8::MAX,
- old_style_record: delta.0,
- new_style_record: delta.1,
- replaced: Some(replaced),
- cascade_state: Some(cascade_state),
- longhand_evaluations,
- owes_a_transition_step: false,
- detached_composition: None,
- });
- let last = records.len() - 1;
- &mut records[last]
- }
-
- /// C++ installed the record the engine derived for `node`: the winner state it was computed
- /// from becomes the node's cascade state, and the answer counts as consumed.
- pub(crate) fn acknowledge_engine_computed_record(&mut self, node: StyleNodeID) {
- if let Some(pending_records) = self.engine_computed_records_pending.remove(&node) {
- for pending in pending_records {
- let target = computed::ComputedStyleTarget::new(node, pending.pseudo_kind);
- // A pseudo-element settled as gone is removed now that C++ has cleared its style.
- if pending.pseudo_kind != u8::MAX && pending.new_style_record == computed::FinalStyleRecordID::NONE {
- self.remove_computed_pseudo(node, pending.pseudo_kind);
- continue;
- }
- self.computed_group_sets.take_pending_cascade_state(target);
- if let Some(cascade_state) = pending.cascade_state {
- self.computed_group_sets.bind_cascade_state(target, cascade_state);
- }
- // The host holds the record that replaced the composition now.
- if let Some(detached) = pending.detached_composition {
- self.computed_group_sets.release_detached_composition(detached);
- }
- // A pseudo-element's record was computed from this very state, as the retained
- // cascade would have observed had C++ computed it.
- if pending.pseudo_kind != u8::MAX {
- self.computed_group_sets
- .observe_pseudo_retained_cascade_state(target, pending.cascade_state);
- }
- self.counters.add(
- Counter::EngineComputedLonghandEvaluations,
- u64::from(pending.longhand_evaluations),
- );
- }
- }
- }
-
- /// The records the engine derived for `node`'s element that the host has not taken, for the
- /// panic of a layout update that ran out of passes: how many, and the records the last of the
- /// element's own moves between.
- pub(crate) fn bound_failure_pending_records(&self, node: StyleNodeID) -> (u8, u64, u64) {
- let Some(pending_records) = self.engine_computed_records_pending.get(&node) else {
- return (0, 0, 0);
- };
- let last = pending_records
- .iter()
- .rev()
- .find(|pending| pending.pseudo_kind == u8::MAX);
- (
- u8::try_from(pending_records.len()).unwrap_or(u8::MAX),
- last.map_or(0, |pending| pending.old_style_record.raw()),
- last.map_or(0, |pending| pending.new_style_record.raw()),
- )
- }
-
- /// The host computed the target's record itself: the record the engine derived for it is not
- /// installed, and a composition the derivation detached gives way to what the host published.
- pub(super) fn forget_engine_computed_record(&mut self, target: computed::ComputedStyleTarget) {
- let Some(pending_records) = self.engine_computed_records_pending.get_mut(&target.node()) else {
- return;
- };
- let computed_group_sets = &mut self.computed_group_sets;
- pending_records.retain(|pending| {
- if pending.pseudo_kind != target.pseudo_kind() {
- return true;
- }
- if let Some(detached) = pending.detached_composition.take() {
- computed_group_sets.release_detached_composition(detached);
- }
- false
- });
- if pending_records.is_empty() {
- self.engine_computed_records_pending.remove(&target.node());
- }
- }
-
- /// The transaction's outputs are gone: every derived record C++ did not install goes back to
- /// the record the node held, unless a publication has moved the node on since.
- pub(super) fn discard_engine_computed_records(&mut self) {
- for pending in std::mem::take(&mut self.engine_computed_records_pending)
- .into_values()
- .flatten()
- {
- if pending.pseudo_kind != u8::MAX {
- self.revert_engine_computed_pseudo_record(pending);
- continue;
- }
- self.revert_engine_computed_element_record(pending);
- }
- }
-
- /// Put an element back on the record it held before the engine derived one for it, unless a
- /// publication has moved it on since, with the composition the derivation detached composing
- /// over it again, and its container query inputs back on the record the host holds: the
- /// derived record they were read from goes with the derivation, and may be reclaimed.
- fn revert_engine_computed_element_record(&mut self, pending: PendingEngineComputedRecord) {
- if let Some(replaced) = pending.replaced {
- self.computed_group_sets
- .revert_engine_computed_record(pending.node, pending.new_style_record, replaced);
- }
- if let Some(detached) = pending.detached_composition {
- self.computed_group_sets.reattach_composition(pending.node, detached);
- }
- let held_style_record = self.held_style_records.get(&pending.node).copied().unwrap_or(0);
- self.set_element_container_query_inputs(pending.node, held_style_record);
- }
-
- /// Derive a node's first record: every winner of its state driven through every phase, every
- /// group built against the parent's payloads, and the record published the way a C++ first
- /// computation publishes it, with the parent's custom-property environment. A node alike in
- /// everything a first record is computed from takes the record an earlier node got, whether
- /// in this flush or one before it.
- fn engine_cold_record(
- &mut self,
- node: StyleNodeID,
- cascade_state: (u64, CascadeStateID),
- scratch: &mut EngineComputedRecordScratch,
- goal: FontDriveGoal,
- ) -> Drive<ElementAnswer> {
- if !self.computes_records() {
- self.counters.bump(Counter::EngineComputedRecordBailUnhosted);
- return Err(Unanswered::Refused);
- }
- let target = computed::ComputedStyleTarget::new(node, u8::MAX);
- let (_, state) = cascade_state;
- let mut inputs = self.document_style_computation_inputs;
- if let Some((root, root_inputs)) = scratch.root_element_inputs
- && root == node
- {
- root_inputs.apply_to(&mut inputs);
- }
- let facts = self.computed_group_sets.adjustment_facts(node);
- // The document element inherits from the initial values.
- let parent = self
- .record_inheritance_parent(node)
- .inspect_err(|_| self.counters.bump(Counter::EngineComputedRecordBailRecordParent))?;
- let parent_record = parent.and_then(|parent| self.computed_group_sets.assigned_style_record(parent));
- // The document element's environment is its own, which is nothing without declarations;
- // any other node's is its declarations resolved over the parent's.
- let parent_environment = match parent {
- Some(parent) => {
- let held = self.held_custom_property_environment(parent)?;
- self.current_custom_property_environment(parent, &inputs, scratch)
- .unwrap_or(held)
- }
- None => 0,
- };
- let pseudo_styles = self.pseudo_style_mask_or_rematch(node);
- // A record whose winners read beyond its environment is the element's alone.
- let element_alone = self.state_reads_beyond_environment(node, state);
- let cache_key = parent
- .zip(parent_record)
- .filter(|_| !element_alone)
- .and_then(|(parent, parent_record)| self.cold_record_parent(node, parent, parent_record, state))
- .map(|parent| ColdRecordKey {
- monospace_recascaded_font_size: self
- .monospace_cohort_key(computed::ComputedStyleTarget::new(node, u8::MAX), state),
- sibling_position: self.sibling_position_key(node, state),
- parent,
- previous_style_record: 0,
- generation: cascade_state.0,
- state,
- facts: cold_record_facts(facts),
- pseudo_styles,
- environment: self.custom_property_environments.inheritable(parent_environment),
- font_environment_generation: inputs.font_environment_generation,
- root_font_inputs: RootFontInputs::from_document(&inputs),
- });
- // A winner that starts an animation keeps the record in C++, unless it declares CSS
- // animations and the host can be handed the plan the record decides, which is asked of every
- // node, a shared record's too.
- for property in self.winner_groups.semantic_delta_properties(None, state) {
- if self.first_record_winner_needs_cpp(property)
- && !(property_declares_css_animations(property) && self.may_plan_css_animations(node, state, scratch))
- {
- self.counters.bump(Counter::EngineComputedRecordBailProperty);
- return Err(Unanswered::Refused);
- }
- }
- let delta_property_count = self.winner_groups.winner_count_in_state(state) as u64;
- if !self.node_declares_custom_properties(node)
- && let Some(delta) = self.assign_cached_cold_record(
- node,
- target,
- cascade_state,
- cache_key,
- parent,
- state,
- computed::FinalStyleRecordID::NONE,
- delta_property_count,
- scratch,
- )
- {
- return Ok(ElementAnswer::Delta(delta));
- }
- // A registered name declared here computes provisionally against the parent's font until
- // the drive settles the element's own.
- let has_registered_declarations = self.declares_registered_custom_property(node, None, &inputs);
- let initial_registered_context =
- has_registered_declarations.then(|| self.standing_registered_value_context(node, None));
- // A function's container condition the engine cannot decide yet waits, as the row does.
- let mut environment = self
- .engine_custom_property_environment_by_answer(node, parent_environment, &inputs)
- .inspect_err(|&unanswered| {
- if unanswered == Unanswered::Refused {
- self.counters.bump(Counter::EngineComputedRecordBailCustomProperties);
- }
- })?;
- // The state has to be one the engine can compute from before any record is shared under
- // it: a record C++ computed for a per-element value, such as a `random()` draw, is that
- // element's alone. A store with substituted values is the environment's as well as the
- // state's, and admits nothing for the state alone.
- let mut store = match scratch.stores.get(&(state, environment)).filter(|_| !element_alone) {
- Some(store) => store.clone(),
- None => {
- let mut substituted = false;
- let store = self.cascaded_store_for_state(
- node,
- state,
- None,
- custom_property_cascade::SubstitutionEnvironment {
- own: environment,
- inherited: parent_environment,
- },
- &mut substituted,
- );
- scratch.computability.remember(
- (
- node,
- cascade_state.0,
- state,
- environment,
- inputs.custom_property_registration_generation,
- ),
- store.as_ref().ok().map(|store| store.record_reads(self)),
- );
- let store = std::sync::Arc::new(store?);
- if !element_alone && !self.records_are_the_elements_alone(node) {
- scratch.stores.insert((state, environment), store.clone());
- }
- if substituted {
- scratch.substituted_states.insert((state, environment));
- }
- store
- }
- };
- self.note_node_substitution(node, scratch, state, environment);
- // The record reads the element's place among its siblings where its state's winners do, as
- // the store substitutes them.
- let reads_sibling_position = store.uses_tree_counting_function(self);
- // A record whose winners read beyond its environment is the element's alone, as is one
- // declaring registered custom properties, which its own font decides. The key is the one
- // above, with the environment the element's declarations resolved, and the element's
- // sibling position only where the substituted winners read it: before substitution, any
- // substitution may have produced a tree-counting function. A substitution that made a
- // non-inherited longhand `inherit` pins the parent's record, as a written `inherit` does.
- let cache_key = cache_key
- .filter(|_| !has_registered_declarations)
- .map(|key| ColdRecordKey {
- environment,
- sibling_position: reads_sibling_position.then(|| self.sibling_position(node)).flatten(),
- parent: ColdRecordParent {
- record: if store.substitutes_inherit_for_non_inherited_property(self) {
- parent_record.map_or(0, |record| record.raw())
- } else {
- key.parent.record
- },
- ..key.parent
- },
- ..key
- });
- if let Some(delta) = self.assign_cached_cold_record(
- node,
- target,
- cascade_state,
- cache_key,
- parent,
- state,
- computed::FinalStyleRecordID::NONE,
- delta_property_count,
- scratch,
- ) {
- return Ok(ElementAnswer::Delta(delta));
- }
- let no_resource_contexts = store.reads_no_resource_contexts(self);
- let donor = cache_key.and_then(|key| {
- let donor_key = ColdRecordDonorKey {
- parent: key.parent,
- generation: key.generation,
- property_shape_hash: self.winner_groups.property_shape_hash(state),
- facts: key.facts,
- pseudo_styles: key.pseudo_styles,
- environment: key.environment,
- font_environment_generation: key.font_environment_generation,
- root_font_inputs: key.root_font_inputs,
- sibling_position: key.sibling_position,
- };
- self.engine_cold_record_donors
- .get(&donor_key)?
- .iter()
- .rev()
- .copied()
- .filter(|donor| {
- self.winner_groups.property_shapes_are_equal(donor.state, state)
- && self
- .computed_group_sets
- .final_style_record_is_live(donor.record.record.raw())
- })
- .min_by_key(|donor| {
- self.winner_groups
- .semantic_delta_properties(Some(donor.state), state)
- .count()
- })
- });
- if !scratch.font_drive.is_pending_for(node)
- && let Some(donor) = donor
- {
- let donor_delta = self.winner_groups.semantic_delta(Some(donor.state), state);
- if let Some((groups_to_rebuild, selected)) =
- self.cold_record_donor_selection(donor, donor_delta.properties())
- && let Ok(PartialDrive::Driven(DrivenTable {
- table,
- length,
- longhand_evaluations,
- explicitly_inherited_groups,
- ..
- })) = self.engine_driven_table(node, donor.record.record, &store, &selected, &inputs)
- {
- let parent_in_display_none_subtree = parent_record
- .and_then(|record| self.computed_group_sets.style_record_view(record.raw()))
- .is_some_and(|view| view.dependency_flags & (1 << 2) != 0);
- let counter_style_registry = self.table_counter_style_environment_identity(target, &table);
- let assembly = self
- .computed_group_sets
- .replace_engine_computed_table(
- node,
- donor.record.record,
- computed::FinalStyleRecordID::NONE,
- table,
- groups_to_rebuild,
- &length,
- None,
- parent_in_display_none_subtree,
- Some(environment),
- Some(counter_style_registry),
- )
- .or_refused()?;
- self.computed_group_sets
- .set_pending_cascade_state(target, cascade_state);
- self.note_node_substitution(node, scratch, state, environment);
- self.note_engine_computed_record(
- node,
- assembly.delta,
- assembly.replaced,
- cascade_state,
- reads_sibling_position,
- delta_property_count,
- longhand_evaluations,
- );
- // The key names the parent's environment: a record whose own declarations
- // resolved another is no answer for an element declaring none. Nor is one that is
- // the element's alone.
- if let Some(cache_key) =
- cache_key.filter(|key| key.environment == environment && !self.records_are_the_elements_alone(node))
- {
- let record = ColdRecord {
- record: assembly.delta.1,
- swap_eligible: self.computed_group_sets.node_inherited_group_swap_eligible(node),
- explicitly_inherited_groups,
- reads_sibling_position,
- };
- scratch.cold_cohorts.insert(cache_key, record);
- if let Some(no_resource_contexts) = no_resource_contexts {
- self.remember_cold_record(cache_key, record, no_resource_contexts);
- }
- }
- scratch.element_explicitly_inherited_groups = explicitly_inherited_groups;
- return Ok(ElementAnswer::Delta(assembly.delta));
- }
- }
- let subject = DriveSubject { target, parent, facts };
- let mut driven = self.engine_full_drive(
- subject,
- None,
- &store,
- &inputs,
- &mut scratch.font_drive,
- goal,
- initial_registered_context.as_ref(),
- )?;
- // The registered custom properties compute against the font the drive settled, and the
- // winners substitute what they computed to.
- if let FullDrive::AwaitsRegisteredContext(registered) = driven {
- let (settled, settled_store, _) = self.store_over_registered_context(
- subject.target,
- state,
- parent_environment,
- |engine| {
- engine
- .engine_custom_property_environment(node, parent_environment, &inputs, Some(&registered))
- .inspect_err(|&unanswered| {
- if unanswered == Unanswered::Refused {
- engine.counters.bump(Counter::EngineComputedRecordBailCustomProperties);
- }
- })
- },
- scratch,
- )?;
- environment = settled;
- store = std::sync::Arc::new(settled_store);
- self.note_node_substitution(node, scratch, state, environment);
- driven = self.engine_full_drive(subject, None, &store, &inputs, &mut scratch.font_drive, goal, None)?;
- }
- let DrivenTable {
- table,
- length,
- longhand_evaluations,
- font,
- explicitly_inherited_groups,
- } = match driven {
- FullDrive::Driven(driven) => driven,
- FullDrive::RootInputs(root_inputs) => return Ok(ElementAnswer::RootInputs(Some(root_inputs))),
- FullDrive::AwaitsRegisteredContext(_) => {
- unreachable!("a drive resumed with its registered context waits for nothing")
- }
- };
- let font = font.expect("a full drive resolves the font");
- let counter_style_registry = self.table_counter_style_environment_identity(target, &table);
- let replaced = self.computed_group_sets.replaced_columns(node);
- let (new_style_record, swap_eligible) = self.assemble_and_publish_engine_record(
- Some(target),
- parent_record,
- table,
- &length,
- &font,
- environment,
- pseudo_styles,
- counter_style_registry,
- Some(cascade_state),
- &mut scratch.computability,
- )?;
- let delta = (computed::FinalStyleRecordID::NONE, new_style_record);
- // The publication itself kept the record for later transactions; alike elements in this
- // one take it from the cohort. The key names the parent's environment, so a record whose
- // own declarations resolved another is kept for no one, nor is one that is the element's
- // alone.
- if let Some(cache_key) =
- cache_key.filter(|key| key.environment == environment && !self.records_are_the_elements_alone(node))
- {
- let record = ColdRecord {
- record: delta.1,
- swap_eligible,
- explicitly_inherited_groups,
- reads_sibling_position,
- };
- scratch.cold_cohorts.insert(cache_key, record);
- if let Some(no_resource_contexts) = no_resource_contexts {
- self.remember_cold_record(cache_key, record, no_resource_contexts);
- }
- }
- scratch.element_explicitly_inherited_groups = explicitly_inherited_groups;
- self.note_engine_computed_record(
- node,
- delta,
- replaced,
- cascade_state,
- reads_sibling_position,
- delta_property_count,
- longhand_evaluations,
- );
- Ok(ElementAnswer::Delta(delta))
- }
-
- #[allow(clippy::too_many_arguments)]
- fn assign_cached_cold_record(
- &mut self,
- node: StyleNodeID,
- target: computed::ComputedStyleTarget,
- cascade_state: (u64, CascadeStateID),
- cache_key: Option<ColdRecordKey>,
- parent: Option<StyleNodeID>,
- state: CascadeStateID,
- old_style_record: computed::FinalStyleRecordID,
- delta_property_count: u64,
- scratch: &mut EngineComputedRecordScratch,
- ) -> Option<(computed::FinalStyleRecordID, computed::FinalStyleRecordID)> {
- let own_groups = self.state_owned_inherited_groups(state);
- let derived_under_parent = |engine: &Self, record: ColdRecord| {
- parent.is_some_and(|parent| {
- engine
- .computed_group_sets
- .final_style_record_is_live(record.record.raw())
- && engine.computed_group_sets.style_record_inherits_from_node(
- record.record.raw(),
- parent,
- own_groups,
- )
- && engine.record_answers_counter_styles_for(record.record, node)
- })
- };
- let (
- ColdRecord {
- record,
- swap_eligible,
- explicitly_inherited_groups,
- reads_sibling_position,
- },
- from_cache,
- ) = cache_key.and_then(|cache_key| {
- scratch
- .cold_cohorts
- .get(&cache_key)
- .copied()
- .filter(|&record| derived_under_parent(self, record))
- .map(|record| (record, false))
- .or_else(|| {
- let record = *self.engine_cold_record_cache.get(&cache_key)?;
- derived_under_parent(self, record).then_some((record, true))
- })
- })?;
- self.computed_group_sets
- .set_pending_cascade_state(target, cascade_state);
- let replaced = self.computed_group_sets.replaced_columns(node);
- let publication = self.assign_shared_style_record(
- target,
- record.raw(),
- computed::ENGINE_INHERITED_GROUP_COUNT,
- swap_eligible,
- );
- let delta = (old_style_record, publication.style_record_identity);
- scratch.element_explicitly_inherited_groups = explicitly_inherited_groups;
- self.note_engine_computed_record(
- node,
- delta,
- replaced,
- cascade_state,
- reads_sibling_position,
- delta_property_count,
- 0,
- );
- self.counters.bump(if from_cache {
- Counter::EngineComputedRecordSharedHits
- } else {
- Counter::EngineComputedRecordCohortHits
- });
- Some(delta)
- }
-
- /// Whether a first record's winner keeps the record's computation in C++: a property that
- /// starts an animation. A transition declaration is computed into the record like any other
- /// value: a first record has no before-change style to start a transition from, and a record
- /// driven in full that replaces one leaves the transition step to the host.
- fn first_record_winner_needs_cpp(&self, property: u16) -> bool {
- property_starts_animation(property) && !property_declares_transitions(property)
+ {
+ return false;
+ }
+ !target.is_pseudo()
+ || (property != crate::css::property_metadata::property_id::CONTENT
+ && crate::css::property_metadata::pseudo_element_supports_property(target.pseudo_kind(), property))
}
- /// The counter-style registry a record computed for `target` from `table` names, as C++ stamps
- /// it: its style scope's registry whenever its `content` holds a counter in a named counter
- /// style, or its `list-style-type` names a counter style that registry may define, which for a
- /// pseudo-element is any named one. Zero otherwise.
- fn table_counter_style_environment_identity(
+ /// The identity of the counter-style registry of the style scope of `target`, the values a
+ /// group build of whose style reads `effective_value` answers, where the style reads one.
+ pub(super) fn values_counter_style_environment_identity<'v>(
&self,
target: computed::ComputedStyleTarget,
- table: &ComputedLonghandTable,
+ effective_value: impl Fn(u16) -> &'v crate::css::style_value::RetainedStyleValueData,
) -> u64 {
use crate::css::property_metadata::property_id as prop;
- let value = |property| table.effective_value_handle(None, property, true).0.optional_data();
+ let value = |property| effective_value(property).optional_data();
if !crate::css::style_compute::style_reads_counter_style_environment(
value(prop::CONTENT),
value(prop::LIST_STYLE_TYPE),
@@ -1917,207 +81,83 @@ impl RetainedState {
) {
return 0;
}
+ self.counter_style_environment_identity_of(target.node())
+ }
+
+ /// The identity of the counter-style registry `node`'s style scope has.
+ pub(super) fn counter_style_environment_identity_of(&self, node: StyleNodeID) -> u64 {
self.counter_style_environment_identities
- .get(&self.counter_style_scope(target.node()))
+ .get(&self.counter_style_scope(node))
.copied()
.unwrap_or(0)
}
- /// Whether a record settled for another element answers for `node` as far as counter styles
- /// go: it names no counter-style registry, or the one `node`'s style scope has.
- fn record_answers_counter_styles_for(&self, record: computed::FinalStyleRecordID, node: StyleNodeID) -> bool {
- self.computed_group_sets
- .style_record_view(record.raw())
- .is_some_and(|view| {
- view.counter_style_environment_identity == 0
- || self
- .counter_style_environment_identities
- .get(&self.counter_style_scope(node))
- == Some(&view.counter_style_environment_identity)
- })
- }
-
/// The style scope whose counter-style registry a node's records name. An element of a shadow
/// tree built from the document's style sheets has the document's style scope.
fn counter_style_scope(&self, node: StyleNodeID) -> TreeScopeID {
- let tree_scope = self.tree.tree_scope(node);
- if self.program.scope_uses_document_sheets(tree_scope) {
+ let tree_scope = self.projection.tree_scope(node);
+ if self.rules.scope_uses_document_sheets(tree_scope) {
TreeScopeID::DOCUMENT
} else {
tree_scope
}
}
- /// Whether the cascade state's winning `font-family` is monospace, which is what makes the
- /// font-size recascade against a 13px default. It is the target's own declaration that decides
- /// this, not what it inherits.
- fn font_family_winner_is_monospace(&self, state: CascadeStateID) -> bool {
- self.winner_groups
- .winner_in_state(state, crate::css::property_metadata::property_id::FONT_FAMILY)
- .and_then(|winner| self.winner_groups.resolved_winner(winner))
- .is_some_and(|winner| {
- self.specified_values
- .value(winner.key.value)
- .is_none_or(crate::css::style_compute::font_family_is_monospace)
- })
- }
-
- /// What a record for this target under this cascade state owes the monospace recascade, as a
- /// cohort key carries it: zero for a font-family that is not monospace. Two targets whose
- /// parents hold equal records can still sit under different cascaded font-size chains, and the
- /// recascade reads the chain rather than the records, so a cohort that ignored this would hand
- /// one target the other's font size.
- fn monospace_cohort_key(&self, target: computed::ComputedStyleTarget, state: CascadeStateID) -> i32 {
- if !self.font_family_winner_is_monospace(state) {
- return 0;
- }
- match self.monospace_recascaded_font_size(target, &self.document_style_computation_inputs) {
- Some(drive::MonospaceRecascade::Size(size, _)) => size,
- // The drive this key is for waits for the same font, and takes the key again after; or
- // it is left to C++.
- Some(drive::MonospaceRecascade::AwaitsFont(_)) | None => i32::MIN,
- }
- }
-
- /// Whether the host can be handed the animation plan of a record the engine derives for `node`
- /// from `state`, decided from that record once it is installed: the host applies it, and the
- /// winners say which scope the winning `animation-name` was declared in.
- fn may_plan_css_animations(
- &self,
- node: StyleNodeID,
- state: CascadeStateID,
- scratch: &EngineComputedRecordScratch,
- ) -> bool {
- scratch.host_applies_animation_plans && self.animation_name_declaration_scope(node, state).is_ok()
- }
-
- /// The tree scope the winning `animation-name` declaration of `state` was written in, where its
- /// `@keyframes` are looked for first, refused where C++'s exact cascade decided the winner. An
- /// author rule's is the scope its sheet is attached to, and for a sheet several scopes adopt,
- /// the one among them the winner's priority places among the element's encapsulation contexts.
- fn animation_name_declaration_scope(
- &self,
- node: StyleNodeID,
- state: CascadeStateID,
- ) -> Result<DeclarationScope, Unanswered> {
- let Some(winner) = self
- .winner_groups
- .winner_in_state(state, crate::css::property_metadata::property_id::ANIMATION_NAME)
- else {
- return Ok(DeclarationScope::Unscoped);
- };
- // A winner the cascade rolled back past every declaration (`revert`, `revert-layer`) takes
- // the initial or inherited value, which no scope declared.
- let Some(winner) = self.winner_groups.resolved_winner(winner) else {
- return Ok(DeclarationScope::Unscoped);
- };
- let rule = match winner.source {
- cascade::WinnerSource::Rule(rule) => rule,
- cascade::WinnerSource::Element(_) => return Ok(DeclarationScope::Unscoped),
- cascade::WinnerSource::ExactCascade => return Err(Unanswered::Refused),
- };
- let sheet = self.program.rule_sheet(rule);
- if self.program.sheet_origin(sheet) != crate::css::cascaded_properties::CascadeOrigin::Author {
- return Ok(DeclarationScope::Unscoped);
- }
- let scope = match self.program.sheet_scopes(sheet).as_slice() {
- &[scope] => scope,
- // The cascade weighs a match at the context of the scope it decided in, and each of the
- // element's contexts stands at its own depth.
- scopes => {
- let depth = winner.priority.author_context_depth();
- *scopes
- .iter()
- .find(|&&scope| self.author_context_index(node, scope) == depth)
- .expect("an author rule wins at one of the element's contexts its sheet is attached to")
- }
- };
- Ok(match scope {
- TreeScopeID::DOCUMENT => DeclarationScope::Unscoped,
- scope => DeclarationScope::Shadow(scope),
- })
- }
-
- /// The scope the winning `animation-name` of the cascade state the record an element, or its
- /// pseudo-element `pseudo_kind`, is installed with was declared in, as
- /// [`Self::animation_name_declaration_scope`] answers it, or `None` where it refuses or the
- /// record is bound to no state.
+ /// The scope the winning `animation-name` of `record`, the record the engine installed for an element, or its
+ /// pseudo-element `pseudo_kind`, was declared in, or `None` where it installed none. It is read off the record
+ /// because a record computed on demand is held by no pass.
pub(crate) fn animation_name_declaration_scope_of(
&self,
node: StyleNodeID,
pseudo_kind: u8,
+ record: &super::pipeline::Record,
) -> Option<DeclarationScope> {
- let (_, state) = self
- .computed_group_sets
- .installing_cascade_state(computed::ComputedStyleTarget::new(node, pseudo_kind))?;
- self.animation_name_declaration_scope(node, state).ok()
- }
-
- /// Whether the host composes the record the engine settled for `node`, moving it from `old` to
- /// `new`, before anything inherits from it: it applies the record's animation plan and samples
- /// the element's animations over it, even over a record that does not move. The element's
- /// pseudo-elements are settled over the composition afterwards, and its children wait for one
- /// that moves.
- pub(super) fn host_composes_row(&self, node: StyleNodeID, old: u64, new: u64) -> bool {
- self.computed_group_sets.adjustment_facts(node) & bridge::element_adjustment_fact::HAS_ANIMATIONS != 0
- || self.row_owes_an_animation_plan(node, old, new)
- || self.row_owes_a_transition_step(node)
- }
-
- /// Settle the pseudo-elements of an element the engine moves along `delta` beside its record,
- /// as `engine_pseudo_records` does, unless the host composes that record first: the host asks
- /// for them once the composition they inherit stands.
- #[allow(clippy::too_many_arguments)]
- fn engine_pseudo_records_beside(
- &mut self,
- node: StyleNodeID,
- delta: (computed::FinalStyleRecordID, computed::FinalStyleRecordID),
- old_is_list_item: Option<bool>,
- generation: u64,
- full_drive_reason: Option<FullDriveReason>,
- scratch: &mut EngineComputedRecordScratch,
- ) -> Drive<()> {
- if self.host_composes_row(node, delta.0.raw(), delta.1.raw()) {
- return Ok(());
- }
- let old_style_record = (delta.0 != computed::FinalStyleRecordID::NONE).then_some(delta.0);
- self.engine_pseudo_records(
- node,
- old_style_record,
- old_is_list_item,
- delta.1,
- generation,
- full_drive_reason,
- scratch,
- )
+ self.computed_group_sets
+ .holds_an_installed_record(computed::ComputedStyleTarget::new(node, pseudo_kind))
+ .then(|| record.rare().animation_name_scope)
}
/// Whether the host owes an element the engine settled the animation plan its record decides,
/// once it installs the record: the record moved the declarations, or the element runs CSS
/// animations, whose `@keyframes` may have moved without the declarations.
pub(super) fn row_owes_an_animation_plan(&self, node: StyleNodeID, old: u64, new: u64) -> bool {
+ self.row_owes_an_animation_plan_declaring(node, old, new, || self.record_declares_animations(new))
+ }
+
+ /// [`Self::row_owes_an_animation_plan`], for a `new` record of which `new_declares_animations`
+ /// answers whether it declares animations.
+ pub(super) fn row_owes_an_animation_plan_declaring(
+ &self,
+ node: StyleNodeID,
+ old: u64,
+ new: u64,
+ new_declares_animations: impl Fn() -> bool,
+ ) -> bool {
// An element the host holds no record for, its style cleared under display:none and its
// animations with it, starts the animations its record names as a first record does.
- let old = if self.held_style_records.contains_key(&node) {
- old
- } else {
- 0
- };
- self.record_owes_an_animation_plan(old, new) || self.css_defined_animations.node_runs_a_css_animation(node)
+ let old = if self.held_style_records.contains(node) { old } else { 0 };
+ self.record_owes_an_animation_plan(old, new, new_declares_animations)
+ || self.css_defined_animations.node_runs_a_css_animation(node)
}
/// Whether installing the `new` record the engine derived for an element, in place of the
/// `old` one the host holds, owes the host the animation plan the new record decides: a first
/// record that names an animation, a record that moves the declarations, or one that names an
/// animation and leaves a display:none subtree, which starts the animations it names.
- pub(super) fn record_owes_an_animation_plan(&self, old: u64, new: u64) -> bool {
+ /// `new_declares_animations` answers whether the new record names an animation.
+ pub(super) fn record_owes_an_animation_plan(
+ &self,
+ old: u64,
+ new: u64,
+ new_declares_animations: impl Fn() -> bool,
+ ) -> bool {
match old {
- 0 => self.record_declares_animations(new),
+ 0 => new_declares_animations(),
old => {
self.animation_declarations_moved(old, new)
|| (self.record_is_in_display_none_subtree(old)
&& !self.record_is_in_display_none_subtree(new)
- && self.record_declares_animations(new))
+ && new_declares_animations())
}
}
}
@@ -2126,8 +166,7 @@ impl RetainedState {
pub(super) fn record_declares_animations(&self, record: u64) -> bool {
self.computed_group_sets
.style_record_view(record)
- .and_then(|view| view.longhand_table)
- .is_some_and(crate::css::style_compute::table_declares_css_animations)
+ .is_some_and(|view| view.longhands().declares_css_animations())
}
/// Whether a record's element is display:none or inherits from one that is.
@@ -2150,8 +189,7 @@ impl RetainedState {
let animation_group = |record| {
self.computed_group_sets
.style_record_payloads(record)
- .and_then(|payloads| payloads.get(ANIMATION))
- .map(|payload| payload.as_ptr())
+ .map(|payloads| payloads[ANIMATION].as_ptr())
};
let (old_group, new_group) = (animation_group(old), animation_group(new));
if old_group == new_group {
@@ -2190,6 +228,45 @@ impl RetainedState {
declarations(old_values) != declarations(new_values)
}
+ /// Whether moving an element from the `old` record to the `new` one moves the `transition-*`
+ /// longhands declaring its transitions.
+ pub(super) fn transition_declarations_moved(&self, old: u64, new: u64) -> bool {
+ use crate::css::computed_value_types::{AnimationValues, ComputedStyleValueHandle};
+ use crate::css::table_group_builder::group_index::ANIMATION;
+ if old == new {
+ return false;
+ }
+ let animation_group = |record| {
+ self.computed_group_sets
+ .style_record_payloads(record)
+ .map(|payloads| payloads[ANIMATION].as_ptr())
+ };
+ let (old_group, new_group) = (animation_group(old), animation_group(new));
+ if old_group == new_group {
+ return false;
+ }
+ let (Some(old_group), Some(new_group)) = (old_group, new_group) else {
+ return true;
+ };
+ // SAFETY: A live record's animation group payload is an `AnimationValues`.
+ let (old_values, new_values) = unsafe {
+ (
+ &*old_group.cast::<AnimationValues>(),
+ &*new_group.cast::<AnimationValues>(),
+ )
+ };
+ fn declarations(values: &AnimationValues) -> [&ComputedStyleValueHandle; 5] {
+ [
+ &values.transition_property,
+ &values.transition_duration,
+ &values.transition_timing_function,
+ &values.transition_delay,
+ &values.transition_behavior,
+ ]
+ }
+ declarations(old_values) != declarations(new_values)
+ }
+
/// Whether the host composes animations over a record, which the engine cannot drive from: a
/// record it cannot read counts as one.
pub(super) fn record_holds_an_animation_overlay(&self, record: computed::FinalStyleRecordID) -> bool {
@@ -2203,8 +280,7 @@ impl RetainedState {
pub(super) fn record_declares_transitions(&self, record: computed::FinalStyleRecordID) -> bool {
self.computed_group_sets
.style_record_view(record.raw())
- .and_then(|view| view.longhand_table)
- .is_some_and(crate::css::style_compute::has_active_transition_properties)
+ .is_some_and(|view| view.longhands().declares_transitions())
}
/// Whether a row moving `node` off `underlying_style_record`, the record beneath any
@@ -2212,857 +288,31 @@ impl RetainedState {
/// from, and the record declares transitions or the row moves their declarations. The host runs
/// the step once it installs the new record, against the record the row moved away from, and
/// composes the record before anything inherits from it, so its children and pseudo-elements
- /// read the values the step started from. A row no host installs is refused.
+ /// read the values the step started from.
pub(super) fn decide_transition_step(
&self,
node: StyleNodeID,
- underlying_style_record: computed::FinalStyleRecordID,
- moves_transition_declarations: bool,
- host_applies_animation_plans: bool,
- ) -> Result<bool, Unanswered> {
- // An element whose style the host cleared on entering display:none, or never computed, has
- // no before-change style.
- let owes_a_transition_step = self.held_style_records.contains_key(&node)
- && (moves_transition_declarations || self.record_declares_transitions(underlying_style_record));
- if owes_a_transition_step && !host_applies_animation_plans {
- self.counters.bump(Counter::EngineComputedRecordBailProperty);
- return Err(Unanswered::Refused);
- }
- Ok(owes_a_transition_step)
- }
-
- /// Whether the host owes the element the transition step once it installs the record the engine
- /// settled for it, as deciding the row found.
- pub(super) fn row_owes_a_transition_step(&self, node: StyleNodeID) -> bool {
- self.engine_computed_records_pending
- .get(&node)
- .and_then(|records| records.iter().rev().find(|pending| pending.pseudo_kind == u8::MAX))
- .is_some_and(|pending| pending.owes_a_transition_step)
- }
-
- /// Select the remaining-phase properties and output groups needed to derive a record from a
- /// donor. Dependencies belong to the donor's published record, since the new node has no
- /// computed row yet.
- fn cold_record_donor_selection(
- &mut self,
- donor: ColdRecordDonor,
- properties: &[u16],
- ) -> Option<(u32, [u64; crate::css::property_metadata::LONGHAND_WORD_COUNT])> {
- use crate::css::computed_value_types::{
- STYLE_GROUP_INDEX_ANCHOR, STYLE_GROUP_INDEX_FONT, STYLE_GROUP_INDEX_SURROUND,
- };
- use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LONGHAND_WORD_COUNT};
-
- if properties.is_empty()
- || properties.iter().any(|&property| {
- !property_computes_in_remaining_phase(property) || property_feeds_box_type_transformation(property)
- })
- {
- return None;
- }
- let mut groups_to_rebuild = 0_u32;
- let mut selected = [0_u64; LONGHAND_WORD_COUNT];
- let mut select = |property: u16| {
- let index = usize::from(property - FIRST_LONGHAND_PROPERTY_ID);
- selected[index / 64] |= 1 << (index % 64);
- };
- let view = self.computed_group_sets.style_record_view(donor.record.record.raw())?;
- let inherited_box = unsafe {
- view.payloads[crate::css::computed_value_types::STYLE_GROUP_INDEX_INHERITED_BOX]
- .cast::<crate::css::computed_values::InheritedBoxValues>()
- .deref()
- };
- for &property in properties {
- if property_starts_animation(property) {
- return None;
- }
- groups_to_rebuild |= moved_longhand_groups(property);
- select(property);
- let bits = crate::css::style_compute::table_row_bits(property);
- let counterpart = if bits & crate::css::style_compute::LOGICAL_ALIAS_BIT != 0 {
- crate::css::style_compute::map_logical_alias_to_physical(
- property,
- inherited_box.writing_mode,
- inherited_box.direction,
- )
- } else if bits & crate::css::style_compute::PHYSICAL_TO_LOGICAL_BIT != 0 {
- crate::css::style_compute::map_physical_to_logical_alias(
- property,
- inherited_box.writing_mode,
- inherited_box.direction,
- )
- } else {
- property
- };
- if counterpart != property {
- groups_to_rebuild |= moved_longhand_groups(counterpart);
- select(counterpart);
- }
- }
- if groups_to_rebuild & (1 << STYLE_GROUP_INDEX_ANCHOR) != 0 {
- groups_to_rebuild |= 1 << STYLE_GROUP_INDEX_SURROUND;
- }
- if properties.contains(&crate::css::property_metadata::property_id::COLOR) {
- let (dependent_groups, dependent_properties) = self
- .computed_group_sets
- .record_current_color_dependencies(donor.record.record)?;
- groups_to_rebuild |= dependent_groups;
- for (word, &bits) in dependent_properties.iter().enumerate() {
- let mut bits = bits;
- while bits != 0 {
- let bit = bits.trailing_zeros() as usize;
- bits &= bits - 1;
- let property = FIRST_LONGHAND_PROPERTY_ID + (word * 64 + bit) as u16;
- select(property);
- if crate::css::style_compute::table_row_bits(property)
- & crate::css::style_compute::LOGICAL_ALIAS_BIT
- != 0
- {
- select(crate::css::style_compute::map_logical_alias_to_physical(
- property,
- inherited_box.writing_mode,
- inherited_box.direction,
- ));
- }
- }
- }
- }
- if groups_to_rebuild & (1 << STYLE_GROUP_INDEX_FONT) != 0 {
- return None;
- }
- Some((groups_to_rebuild, selected))
- }
-
- /// Build a driven table's groups against the parent record's payloads and publish the record
- /// for `target` the way a C++ computation publishes one; the record's swap eligibility comes
- /// back beside its identity. Without a target, no row holds the record.
- #[allow(clippy::too_many_arguments)]
- fn assemble_and_publish_engine_record(
- &mut self,
- target: Option<computed::ComputedStyleTarget>,
- parent_record: Option<computed::FinalStyleRecordID>,
- mut table: ComputedLonghandTable,
- length: &crate::css::style_compute::FfiLengthResolutionContext,
- font: &crate::css::table_group_builder::FfiFontGroupBuildInputs,
- environment: u64,
- pseudo_styles: u64,
- counter_style_registry: u64,
- cascade_state: Option<(u64, CascadeStateID)>,
- scratch: &mut EngineComputabilityScratch,
- ) -> Drive<(computed::FinalStyleRecordID, bool)> {
- use crate::css::table_group_builder::group_index;
-
- // The document element's groups build against no parent payloads.
- let (parent_payloads, parent_in_display_none_subtree) = match parent_record {
- Some(parent_record) => {
- let Some(parent_view) = self.computed_group_sets.style_record_view(parent_record.raw()) else {
- debug_assert!(false, "an assigned parent record has a view");
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
- return Err(Unanswered::Refused);
- };
- (parent_view.payloads, parent_view.dependency_flags & (1 << 2) != 0)
- }
- None => (&[SharedPayload::null(); group_index::COUNT][..], false),
- };
- let display_is_none = crate::css::style_compute::effective_display(&table, None).is_none();
- table.set_in_display_none_subtree(parent_in_display_none_subtree || display_is_none);
- table.freeze();
- let swap_eligible = table.property_inheritance_is_standard()
- && !table.display_is_list_item()
- && !crate::css::style_compute::has_active_transition_properties(&table);
- let color_inputs = crate::css::table_group_builder::assembly_color_inputs(&table, length);
- let table = table.into_raw_shared();
- let payloads = parent_payloads
- .iter()
- .enumerate()
- .take(group_index::COUNT)
- .map(|(group, &parent_payload)| {
- SharedPayload::new(unsafe {
- crate::css::table_group_builder::assemble_group_from_table(
- &*table,
- group,
- Some(font),
- crate::css::computed_values::GroupPayloadRef::new(group, parent_payload.as_ptr()),
- color_inputs,
- length,
- )
- })
- })
- .collect::<Vec<_>>();
- // SAFETY: Each payload was just built for its group, and the drive holds the only reference to it until
- // ownership transfers to the catalog below.
- let holds_image_values = unsafe {
- crate::css::computed_values::style_group_payloads_hold_image_values(HostShared::as_pointer_slice(&payloads))
- };
- let dependency_flags = unsafe { &*table }.publication_dependency_flags()
- | (u8::from(swap_eligible) * computed::INHERITED_GROUP_SWAP_ELIGIBLE)
- | (u8::from(holds_image_values) * computed::HOLDS_IMAGE_VALUES);
- let metadata_input = computed::ComputedMetadataInput {
- pseudo_element_styles: pseudo_styles,
- dependency_flags,
- counter_style_environment_identity: counter_style_registry,
- animation_overlay_identity: 0,
- animated_overlay: HostShared::null(),
- animation_overlay_payloads: &[],
- longhand_table: HostShared::new(table),
- };
- if let Some(target) = target
- && let Some(cascade_state) = cascade_state
- {
- self.computed_group_sets
- .set_pending_cascade_state(target, cascade_state);
- }
- // The drive built every payload and the table, and holds the only reference to each:
- // hand them to the catalog rather than have it retain a second one per published payload.
- let owned = computed::PendingRecordOwnership {
- groups: u32::try_from((1_u64 << payloads.len()) - 1).expect("a style group index fits the ownership mask"),
- table: true,
- };
- let publication = self.publish_computed_groups_impl(
- target,
- &payloads,
- computed::ENGINE_INHERITED_GROUP_COUNT,
- environment,
- metadata_input,
- owned,
- scratch,
- );
- let transferred = publication.transferred;
- for (group, payload) in payloads.into_iter().enumerate() {
- if transferred.groups & (1 << group) == 0 {
- crate::css::computed_values::release_group_payload(group, payload.as_ptr());
- }
- }
- if !transferred.table {
- unsafe {
- crate::css::computed_longhand_table::rust_computed_longhand_table_release(table.cast_mut());
- }
- }
- Ok((publication.style_record_identity, swap_eligible))
- }
-
- /// C++ computes `node` itself rather than install what a record demand derived for it: the
- /// derived records go back as an abandoned derivation's do, and the demand's own cohorts went
- /// with it.
- pub(crate) fn abandon_demanded_records(&mut self, node: StyleNodeID) {
- self.abandon_engine_computed_record(node, &mut EngineComputedRecordScratch::default());
- }
-
- /// A derivation that could not be completed: everything derived for `node` this flush goes
- /// back to what the node held, and nothing in the flush may share it.
- pub(super) fn abandon_engine_computed_record(
- &mut self,
- node: StyleNodeID,
- scratch: &mut EngineComputedRecordScratch,
- ) {
- self.put_back_engine_computed_records(node, scratch);
- self.counters.bump(Counter::EngineComputedRecordsAbandoned);
- }
-
- /// Put back every record derived for `node` that the host has not taken: the node goes back to
- /// the records it held, the cascade state a derived record waits to bind goes with it, and no
- /// cohort of the drive or cache across drives keeps a derived record to share.
- pub(super) fn put_back_engine_computed_records(
- &mut self,
- node: StyleNodeID,
- scratch: &mut EngineComputedRecordScratch,
- ) {
- for pending in self.engine_computed_records_pending.remove(&node).into_iter().flatten() {
- let derived = pending.new_style_record;
- if pending.pseudo_kind == u8::MAX {
- let target = computed::ComputedStyleTarget::new(node, u8::MAX);
- self.computed_group_sets.take_pending_cascade_state(target);
- self.revert_engine_computed_element_record(pending);
- scratch.cohorts.retain(|_, (record, ..)| *record != derived);
- scratch.cold_cohorts.retain(|_, record| record.record != derived);
- self.engine_cold_record_cache
- .retain(|_, record| record.record != derived);
- self.engine_cold_record_donors.retain(|_, donors| {
- donors.retain(|donor| donor.record.record != derived);
- !donors.is_empty()
- });
- } else {
- self.revert_engine_computed_pseudo_record(pending);
- scratch.pseudo_cohorts.retain(|_, record| *record != derived);
- self.engine_pseudo_record_cache.retain(|_, record| *record != derived);
- }
- }
- scratch.pseudo_deltas.clear();
- }
-
- /// Whether a node's winners hold gated rules, decided where they were published or left for
- /// the record drive to decide once its containers settle.
- pub(super) fn node_holds_container_gates(&self, node: StyleNodeID) -> bool {
- self.published_container_verdicts.contains_key(&node) || self.container_gates_unheld.contains(&node)
- }
-
- /// NB: Reuse stores resolved under the same winner state and environment while retaining
- /// per-element context checks and accounting for every stored allocation.
- fn cached_winner_store(
- &mut self,
- node: StyleNodeID,
- state: CascadeStateID,
- environment: u64,
- parent_environment: u64,
- scratch: &mut EngineComputedRecordScratch,
- ) -> Drive<std::sync::Arc<WinnerStore>> {
- let element_alone = self.state_reads_beyond_environment(node, state);
- if let Some(store) = scratch.stores.get(&(state, environment)).filter(|_| !element_alone) {
- return Ok(store.clone());
- }
- let mut substituted = false;
- let store = std::sync::Arc::new(self.cascaded_store_for_state(
- node,
- state,
- None,
- custom_property_cascade::SubstitutionEnvironment {
- own: environment,
- inherited: parent_environment,
- },
- &mut substituted,
- )?);
- if !element_alone && !self.records_are_the_elements_alone(node) {
- scratch.stores.insert((state, environment), store.clone());
- }
- if substituted {
- scratch.substituted_states.insert((state, environment));
- }
- Ok(store)
- }
-
- /// How much of an element's held record a row drives again, given the winner `delta` since
- /// the record and whether anything else it was computed from moved (`inputs_moved`: the
- /// parent's inherited style or display, the root's inputs, or an input that drives in full).
- #[allow(clippy::too_many_arguments)]
- fn record_drive_scope(
- &self,
- node: StyleNodeID,
- state: CascadeStateID,
- delta: &cascade::CascadeWinnerDelta,
- flips_are_reflected: bool,
- inputs_moved: bool,
- environment: Option<u64>,
- has_registered_declarations: bool,
- pseudo_inputs_alone: bool,
- substitutions_unchanged: bool,
- ) -> DriveScope {
- if delta.is_empty() {
- // Standing winners leave the record standing when the reaction is the rules that flipped
- // and nothing else moved, while its inherited groups provably follow the current parent
- // or all that moved is what the pseudo-elements read. Any other reaction stands for an
- // input no winner shows, a host's forced recompute (an attribute, a state, an input
- // type) among them: the record is driven in full from the inputs as they are now.
- return if flips_are_reflected
- && !inputs_moved
- && (pseudo_inputs_alone
- || self.record_inherits_from_current_parent(node, state, substitutions_unchanged))
- {
- environment.map_or(DriveScope::Stands, DriveScope::Environment)
- } else {
- DriveScope::Full
- };
- }
- // A moved font-phase longhand reaches every value the font feeds, so the record is driven
- // through every phase and every group is rebuilt. A moved box-type transformation input
- // takes the same route: the transformation is part of the full drive, and so is a moved
- // environment under registered custom properties, which compute against the font the drive
- // settles.
- if inputs_moved
- || (has_registered_declarations && environment.is_some())
- || delta.properties().iter().any(|&property| {
- !property_computes_in_remaining_phase(property) || property_feeds_box_type_transformation(property)
- })
- {
- DriveScope::Full
- } else {
- DriveScope::Partial
- }
- }
-
- /// Whether a node's record inherits from the parent it has now: each inherited group is the
- /// parent's own, no non-inherited property is inherited explicitly, and its custom-property
- /// environment follows the parent or preserves the substituted values of its winners.
- fn record_inherits_from_current_parent(
- &self,
- node: StyleNodeID,
- state: CascadeStateID,
- substitutions_unchanged: bool,
- ) -> bool {
- let Some(parent) = self.tree.inheritance_parent(node) else {
- return false;
- };
- if self.state_explicitly_inherits_non_inherited_property(node, state) {
- return false;
- }
- self.computed_group_sets
- .inherited_groups_follow_parent(node, parent)
- .unwrap_or(false)
- && (substitutions_unchanged
- || self
- .computed_group_sets
- .custom_property_environment_identity(node)
- .is_some_and(|environment| self.inherited_custom_property_environment(parent) == Some(environment)))
- }
-
- /// The inherited groups a state's winners rebuild for their element: the groups its
- /// declarations land in, the font group when it declares a longhand that group carries
- /// without landing in it, and the ones holding colors when it declares `color`, which their
- /// currentcolor-dependent values resolve against.
- fn state_owned_inherited_groups(&self, state: CascadeStateID) -> u32 {
- use crate::css::computed_value_types::{
- STYLE_GROUP_INDEX_FONT, STYLE_GROUP_INDEX_INHERITED_SVG, STYLE_GROUP_INDEX_INHERITED_TEXT,
- STYLE_GROUP_INDEX_INHERITED_UI,
- };
- use crate::css::property_metadata::{property_id as prop, property_style_group_index};
- self.winner_groups
- .properties_in_state(state)
- .fold(0_u32, |mask, property| {
- let mask = mask | property_style_group_index(property).map_or(0, |group| 1 << group);
- // A font longhand the group carries rather than holds, such as
- // `font-variant-numeric`, has no group of its own, so the group it does rebuild
- // has to be named here or nothing names it.
- let mask = if font_group_carries_longhand(property) {
- mask | (1 << STYLE_GROUP_INDEX_FONT)
- } else {
- mask
- };
- if property == prop::COLOR {
- mask | (1 << STYLE_GROUP_INDEX_INHERITED_UI)
- | (1 << STYLE_GROUP_INDEX_INHERITED_SVG)
- | (1 << STYLE_GROUP_INDEX_INHERITED_TEXT)
- } else {
- mask
- }
- })
- }
-
- pub(super) fn root_font_inputs_from_record(&self, record: computed::FinalStyleRecordID) -> Option<RootFontInputs> {
- use crate::css::computed_value_types::{STYLE_GROUP_INDEX_FONT, STYLE_GROUP_INDEX_INHERITED_BOX};
- let view = self.computed_group_sets.style_record_view(record.raw())?;
- let font = unsafe {
- view.payloads[STYLE_GROUP_INDEX_FONT]
- .cast::<crate::css::computed_value_types::FontValues>()
- .deref()
- };
- let inherited_box = unsafe {
- view.payloads[STYLE_GROUP_INDEX_INHERITED_BOX]
- .cast::<crate::css::computed_values::InheritedBoxValues>()
- .deref()
- };
- Some(RootFontInputs {
- metrics: [
- font.font_size.to_double().to_bits(),
- drive_font_metric(font.font_x_height).to_bits(),
- drive_font_metric(font.font_ascent).to_bits(),
- drive_font_metric(font.font_zero_advance).to_bits(),
- font.line_height_used.to_double().to_bits(),
- ],
- depends_on_viewport: view.dependency_flags & FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS != 0,
- effective_zoom: f64::from(inherited_box.effective_zoom()).to_bits(),
- })
- }
-
- /// The host boundary publishes root inputs after materializing a document element.
- /// Cache entries name these inputs; publication does not clear them as a side effect.
- fn prepare_root_font_metrics_from_record(&mut self, record: computed::FinalStyleRecordID) {
- let Some(root_inputs) = self.root_font_inputs_from_record(record) else {
- return;
- };
- root_inputs.apply_to(&mut self.document_style_computation_inputs);
- }
-
- fn element_drive_subject(&mut self, node: StyleNodeID) -> Drive<DriveSubject> {
- let facts = self.computed_group_sets.adjustment_facts(node);
- // The document element inherits from the initial values.
- let parent = self
- .record_inheritance_parent(node)
- .inspect_err(|_| self.counters.bump(Counter::EngineComputedRecordBailRecordParent))?;
- Ok(DriveSubject {
- target: computed::ComputedStyleTarget::new(node, u8::MAX),
- parent,
- facts,
- })
- }
-
- /// A later element alike in what a first record is computed from takes this record, the way a
- /// C++ computation shares across transactions. The cache is small and bounded.
- fn remember_cold_record(&mut self, key: ColdRecordKey, record: ColdRecord, _: ReadsNoResourceContexts) {
- if self.engine_cold_record_cache.len() >= COLD_RECORD_CACHE_LIMIT {
- self.engine_cold_record_cache.clear();
- self.engine_cold_record_donors.clear();
- }
- self.engine_cold_record_cache.insert(key, record);
- if key.previous_style_record == 0 {
- let donor_key = ColdRecordDonorKey {
- parent: key.parent,
- generation: key.generation,
- property_shape_hash: self.winner_groups.property_shape_hash(key.state),
- facts: key.facts,
- pseudo_styles: key.pseudo_styles,
- environment: key.environment,
- font_environment_generation: key.font_environment_generation,
- root_font_inputs: key.root_font_inputs,
- sibling_position: key.sibling_position,
- };
- let donors = self.engine_cold_record_donors.entry(donor_key).or_default();
- if let Some(existing) = donors.iter_mut().find(|donor| donor.state == key.state) {
- existing.record = record;
- return;
- }
- if donors.len() == MAXIMUM_COLD_RECORD_DONORS_PER_KEY {
- donors.remove(0);
- }
- donors.push(ColdRecordDonor {
- state: key.state,
- record,
- });
- }
- }
-
- /// What a record the engine computes from a winner state reads beside its winners, or `None`
- /// when the state is not one the engine computes records from: every
- /// winner a plain rule declaration with a written value that needs no document context.
- /// Substituted declarations also depend on the custom-property environment and the registry
- /// used to parse them.
- fn computable_state_record_reads(
- &mut self,
- node: StyleNodeID,
- cascade_state: (u64, CascadeStateID),
- scratch: &mut EngineComputabilityScratch,
- ) -> Option<StateRecordReads> {
- let environment = self
- .computed_group_sets
- .custom_property_environment_identity(node)
- .unwrap_or(0);
- let registration_generation = self
- .document_style_computation_inputs
- .custom_property_registration_generation;
- let key = (
- node,
- cascade_state.0,
- cascade_state.1,
- environment,
- registration_generation,
- );
- if let Some(&admitted) = scratch.states.get(&key) {
- return admitted;
- }
- let inherited = self
- .tree
- .inheritance_parent(node)
- .and_then(|parent| self.computed_group_sets.custom_property_environment_identity(parent))
- .unwrap_or(0);
- let mut substituted = false;
- let admitted = self
- .cascaded_store_for_state_in(
- node,
- cascade_state.1,
- None,
- custom_property_cascade::SubstitutionEnvironment {
- own: environment,
- inherited,
- },
- &mut substituted,
- StoreUse::Admission,
- )
- .ok()
- .map(|store| store.record_reads(self));
- scratch.remember(key, admitted);
- admitted
- }
-
- /// Whether C++ may publish one record as the answer for another element with this winner
- /// state. Values which read per-element or external context are never shared opaquely, and
- /// no context-free value resolves a `url()`.
- fn opaque_record_shareable_state(
- &mut self,
- node: StyleNodeID,
- state: CascadeStateID,
- ) -> Option<ReadsNoResourceContexts> {
- for winner in self
- .winner_groups
- .winners_in_state(state)
- .filter_map(|winner| self.winner_groups.resolved_winner(winner))
- {
- match self.written_winner_value(node, &winner) {
- Ok(Some((_, _, checks))) if checks.whole_context_free => {}
- Err(counter) => {
- self.counters.bump(counter);
- return None;
- }
- _ => return None,
- }
- }
- Some(ReadsNoResourceContexts(()))
- }
-
- /// The parent-side half of a first record's sharing key, or nothing when the parent's style
- /// is one no first record may be shared under.
- fn cold_record_parent(
- &self,
- node: StyleNodeID,
- parent: StyleNodeID,
- parent_record: computed::FinalStyleRecordID,
- state: CascadeStateID,
- ) -> Option<ColdRecordParent> {
- let view = self.computed_group_sets.style_record_view(parent_record.raw())?;
- if view.animated_overlay.is_some() {
- return None;
- }
- let dependency_flags = view.dependency_flags;
- let environment = self.inherited_custom_property_environment(parent)?;
- let inherited_groups = self.computed_group_sets.node_inherited_groups_identity(parent)?;
- // C++ styles the children of a display:none element on demand, past the engine's view of
- // the parent, so no first record is computed under one.
- let parent_blockifies = self.box_type_parent_blockifies(parent, UnderDisplayNone::NoKey)?;
- let record = if self.state_explicitly_inherits_non_inherited_property(node, state) {
- parent_record.raw()
- } else {
- 0
- };
- Some(ColdRecordParent {
- record,
- inherited_groups,
- environment,
- dependency_flags,
- parent_blockifies,
- })
- }
-
- /// Whether the parent a child's box-type transformation reads blockifies the child: the
- /// parent's own display, past any display:contents ancestor, is grid or flex inside. That is
- /// all the transformation reads of it. Under a display:none parent, `display_none` says
- /// whether there is an answer.
- fn box_type_parent_blockifies(&self, parent: StyleNodeID, display_none: UnderDisplayNone) -> Option<bool> {
- let mut ancestor = Some(parent);
- while let Some(current) = ancestor {
- let record = self.computed_group_sets.assigned_style_record(current)?;
- let view = self.computed_group_sets.style_record_view(record.raw())?;
- let table = view.longhand_table?;
- let display = crate::css::style_compute::effective_display(table, None);
- if display.is_none() && display_none == UnderDisplayNone::NoKey {
- return None;
- }
- if !display.is_contents() {
- return Some(display.is_grid_inside() || display.is_flex_inside());
- }
- ancestor = self.tree.inheritance_parent(current);
- }
- None
- }
-
- /// Whether a winner state declares `inherit` for a non-inherited property, or carries a value
- /// the engine cannot see the spelling of.
- pub(super) fn node_explicitly_inherits_non_inherited_property(&self, node: StyleNodeID) -> bool {
- let Lookup::Known((_, state)) = self
- .current_winner_groups()
- .token_for(WinnerGroupKey::current(node, self.program.version()))
- else {
- return false;
- };
- self.state_explicitly_inherits_non_inherited_property(node, state)
- }
-
- /// NB: The written winners cover inheritance before the host has published its dependency marks.
- pub(super) fn node_explicitly_inherited_groups(&self, node: StyleNodeID) -> u32 {
- let Lookup::Known((_, state)) = self
- .current_winner_groups()
- .token_for(WinnerGroupKey::current(node, self.program.version()))
- else {
- return 0;
- };
- self.state_explicitly_inherited_groups(node, state)
- }
-
- fn state_explicitly_inherits_non_inherited_property(&self, node: StyleNodeID, state: CascadeStateID) -> bool {
- self.state_summary(node, state).explicitly_inherited_groups != 0
- }
-
- /// The non-inherited style groups a winner state reads straight from the parent: what C++
- /// marks the parent with when it computes a record from the state.
- fn state_explicitly_inherited_groups(&self, node: StyleNodeID, state: CascadeStateID) -> u32 {
- self.state_summary(node, state).explicitly_inherited_groups
+ underlying_style_record: computed::FinalStyleRecordID,
+ moves_transition_declarations: bool,
+ ) -> bool {
+ // An element whose style the host cleared on entering display:none, or never computed, has
+ // no before-change style.
+ self.held_style_records.contains(node)
+ && (moves_transition_declarations || self.record_declares_transitions(underlying_style_record))
}
- /// What the engine asks of a state's winners' written values, decided once for each state where `node` finds
- /// every winner's written value: the style groups of each non-inherited property the state declares `inherit` for,
- /// and every group for a value the engine cannot see the spelling of, and whether any longhand winner was written
- /// with a substitution.
- fn state_summary(&self, node: StyleNodeID, state: CascadeStateID) -> cascade::StateSummary {
- use crate::css::style_value::StyleValueData;
- if let Some(summary) = self.winner_groups.state_summary(state) {
- return summary;
- }
- let mut summary = cascade::StateSummary::default();
- // NB: A winner whose written value `node` does not find, such as an element declaration hidden for a demand,
- // says nothing of other nodes, so the summary is only kept when every value was found.
- for winner in self.winner_groups.winners_in_state(state) {
- let inherited = crate::css::property_metadata::property_is_inherited(winner.property);
- let Some(winner) = self.winner_groups.resolved_winner(winner) else {
- summary.has_unknown_values = true;
- continue;
- };
- let longhand = winner.property >= crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID;
- if inherited && !longhand {
- summary.has_unknown_values = true;
- continue;
- }
- let group_mask = || match crate::css::computed_values::StyleGroupMasks::get().dependencies(winner.property)
- {
- 0 => u32::MAX,
- mask => mask,
- };
- let value = match winner.source {
- WinnerSource::Rule(rule) => {
- self.program
- .written_winner_value(rule, winner.property, winner.important, winner.key.value)
- }
- WinnerSource::Element(kind) => self.facts.element_declarations(node, kind).and_then(|declarations| {
- declarations.winner_value(winner.property, winner.important, winner.key.value)
- }),
- WinnerSource::ExactCascade => {
- summary.has_unknown_values = true;
- if !inherited {
- summary.explicitly_inherited_groups = u32::MAX;
- }
- continue;
- }
- };
- let Some(value) = value else {
- summary.has_unknown_values = true;
- if !inherited {
- summary.explicitly_inherited_groups |= group_mask();
- }
- continue;
- };
- if !inherited
- && matches!(value.data(), StyleValueData::Keyword { keyword }
- if *keyword == crate::css::style_compute::keyword::INHERIT)
- {
- summary.explicitly_inherited_groups |= group_mask();
- }
- if longhand
- && matches!(
- value.data(),
- StyleValueData::Unresolved { .. } | StyleValueData::PendingSubstitution { .. }
- )
- {
- summary.has_substitutions = true;
- }
- }
- if !summary.has_unknown_values {
- self.winner_groups.note_state_summary(state, summary);
- }
- summary
+ pub(super) fn root_font_inputs_from_record(&self, record: computed::FinalStyleRecordID) -> Option<RootFontInputs> {
+ let view = self.computed_group_sets.style_record_view(record.raw())?;
+ Some(RootFontInputs::from_payloads(view.payloads, view.dependency_flags))
}
- /// Keep a record C++ published for an element as a first record a later alike element can
- /// take, when it was computed from nothing but what the engine keys first records on: the
- /// parent's inherited style and environment, a winner state the engine can compute from, the
- /// element facts and the pseudo-elements it has rules for.
- #[allow(clippy::too_many_arguments)]
- fn remember_cold_record_candidate(
- &mut self,
- target: computed::ComputedStyleTarget,
- cascade_state: (u64, CascadeStateID),
- custom_property_environment: u64,
- pseudo_styles: u64,
- previous_style_record: Option<computed::FinalStyleRecordID>,
- style_record: computed::FinalStyleRecordID,
- is_base_record: bool,
- scratch: &mut EngineComputabilityScratch,
- ) {
- if target.is_pseudo() || !is_base_record {
- return;
- }
- let inputs = self.document_style_computation_inputs;
- let node = target.node();
- let facts = self.computed_group_sets.adjustment_facts(node);
- if self.node_declares_custom_properties(node) {
- return;
- }
- // A record C++ computed for an element with animations is not what its winner state
- // alone describes.
- if facts & bridge::element_adjustment_fact::HAS_ANIMATIONS != 0 {
- return;
- }
- // A state minted before the winner groups were cleared names nothing in the table now.
- if cascade_state.0 != self.winner_groups.generation() {
- return;
- }
- let Some(parent) = self.tree.inheritance_parent(node) else {
- return;
- };
- let Some(parent_record) = self.computed_group_sets.assigned_style_record(parent) else {
- return;
- };
- if self.inherited_custom_property_environment(parent) != Some(custom_property_environment) {
- return;
- }
- // An opaque record is shared only when every winner is context-free, which no winner
- // reading the element's place among its siblings is.
- let Some(reads) = self
- .computable_state_record_reads(node, cascade_state, scratch)
- .or_else(|| {
- self.opaque_record_shareable_state(node, cascade_state.1)
- .map(|no_resource_contexts| StateRecordReads {
- sibling_position: false,
- no_resource_contexts: Some(no_resource_contexts),
- })
- })
- else {
- return;
- };
- // The element holds the record whether or not a later element takes it, and a change
- // among its siblings has to drive one reading its place again in full.
- self.note_sibling_position_reads(node, u8::MAX, reads.sibling_position);
- let Some(no_resource_contexts) = reads.no_resource_contexts else {
- return;
- };
- // A record whose winners read beyond its environment is the element's alone, as is one
- // `records_are_the_elements_alone` says is. Nor is one whose winners substitute kept: what
- // they substituted to is C++'s, and a substitution can make a non-inherited property
- // `inherit`, which neither the key nor the record's explicitly inherited groups would show.
- if self.state_reads_beyond_environment(node, cascade_state.1)
- || self.records_are_the_elements_alone(node)
- || self.state_has_substitutions(node, cascade_state.1)
- {
- return;
- }
- let Some(parent) = self.cold_record_parent(node, parent, parent_record, cascade_state.1) else {
+ /// The host boundary publishes root inputs after materializing a document element.
+ /// Cache entries name these inputs; publication does not clear them as a side effect.
+ pub(super) fn prepare_root_font_metrics_from_record(&mut self, record: computed::FinalStyleRecordID) {
+ let Some(root_inputs) = self.root_font_inputs_from_record(record) else {
return;
};
- let swap_eligible = self.computed_group_sets.node_inherited_group_swap_eligible(node);
- let key = ColdRecordKey {
- monospace_recascaded_font_size: self
- .monospace_cohort_key(computed::ComputedStyleTarget::new(node, u8::MAX), cascade_state.1),
- sibling_position: self.sibling_position_key(node, cascade_state.1),
- parent,
- previous_style_record: previous_style_record.map_or(0, computed::FinalStyleRecordID::raw),
- generation: cascade_state.0,
- state: cascade_state.1,
- facts: cold_record_facts(facts),
- pseudo_styles,
- environment: custom_property_environment,
- font_environment_generation: inputs.font_environment_generation,
- root_font_inputs: RootFontInputs::from_document(&inputs),
- };
- self.remember_cold_record(
- key,
- ColdRecord {
- record: style_record,
- swap_eligible,
- explicitly_inherited_groups: self.state_explicitly_inherited_groups(node, cascade_state.1),
- reads_sibling_position: reads.sibling_position,
- },
- no_resource_contexts,
- );
- }
-
- /// The synthetic pseudo-elements the node has rules for, as a C++ record's pseudo-style mask,
- /// or no bits when the engine holds no answer for the node.
- pub(crate) fn published_pseudo_style_mask(&self, node: StyleNodeID) -> u64 {
- self.pseudo_style_mask(node).unwrap_or(0)
+ root_inputs.apply_to(&mut self.document_style_computation_inputs);
}
/// What the node and its DOM descendants do to the two pieces of generated-content state that run
@@ -3123,102 +373,17 @@ impl RetainedState {
self.published_pseudo_record(node, pseudo_kind::FIRST_LETTER).is_some()
}
- /// The value a winner's declaration was written with, and the declaration's index in its
- /// block: the drive computes from the spelling the declaration was written in, which the
- /// cascade's canonical identity may have rewritten. A rule keeps its written values beside its
- /// declarations, and an element's own declarations keep theirs beside the facts.
- fn written_winner_value(
- &self,
- node: StyleNodeID,
- winner: &PropertyWinner,
- ) -> Result<
- Option<(
- usize,
- &crate::css::style_value::RetainedStyleValueData,
- WrittenValueChecks,
- )>,
- Counter,
- > {
- match winner.source {
- WinnerSource::Rule(rule) => Ok(self
- .program
- .written_winner_declaration(rule, winner.property, winner.important, winner.key.value)
- .map(|(index, value)| (index, value, self.program.written_value_checks(rule, index)))),
- WinnerSource::Element(kind) => Ok(self.facts.element_declarations(node, kind).and_then(|declarations| {
- let index = declarations.winner_index(winner.property, winner.important, winner.key.value)?;
- Some((index, declarations.written(index), declarations.checks(index)))
- })),
- WinnerSource::ExactCascade => Err(Counter::EngineComputedRecordBailWinnerOperator),
- }
- }
-
- /// The outermost shorthand declared in a winner's block for the written value a pending
- /// longhand names, and that shorthand's written value. A shorthand nested in another, such as
- /// `border-width` in `border`, is itself declared pending the outer one.
- fn shorthand_declaration_written_as(
- &self,
- node: StyleNodeID,
- source: WinnerSource,
- written_value: *const crate::css::style_value::StyleValueData,
- ) -> Option<(u16, crate::css::style_value::RetainedStyleValueData)> {
- let declarations = match source {
- WinnerSource::Rule(rule) => {
- let declared = self.program.declared_properties_of(rule);
- let written = self.program.written_values_of(rule);
- if written.len() != declared.len() {
- return None;
- }
- declared.iter().zip(written)
- }
- WinnerSource::Element(kind) => self.facts.element_declarations(node, kind)?.iter(),
- WinnerSource::ExactCascade => return None,
- };
- let mut written_value = written_value;
- while let Some((shorthand, value)) = declarations.clone().find(|(declared, written)| {
- declared.property < crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID
- && std::ptr::eq(written.pointer(), written_value)
- }) {
- match value.data() {
- crate::css::style_value::StyleValueData::PendingSubstitution {
- original_shorthand_value,
- } => written_value = original_shorthand_value.pointer(),
- _ => return Some((shorthand.property, value.clone_retained())),
- }
- }
-
- // Inline declarations retain the expanded pending longhands without a separate shorthand
- // declaration. The longhands pending the same original value are the leaves of the
- // shorthand whose grammar parses the substituted source, through any shorthand nested in
- // it (`border-width` in `border`).
- let mut original = None;
- let mut pending_longhands = Vec::new();
- for (declared, written) in declarations {
- if let crate::css::style_value::StyleValueData::PendingSubstitution {
- original_shorthand_value,
- } = written.data()
- && std::ptr::eq(original_shorthand_value.pointer(), written_value)
- {
- pending_longhands.push(declared.property);
- original = Some(original_shorthand_value);
- }
- }
- let original = original?;
- let shorthand = crate::css::property_metadata::shorthand_with_leaf_longhands(pending_longhands)?;
- Some((shorthand, original.clone_retained()))
- }
-
- /// Whether any winner of a state was written with a substitution, so the record computed
- /// from it reads the node's custom-property environment.
- pub(super) fn state_has_substitutions(&self, node: StyleNodeID, state: CascadeStateID) -> bool {
- self.state_summary(node, state).has_substitutions
- }
-
/// Whether publishing sampled custom properties requires another style computation.
- /// The sample has already resolved the target's custom declarations that read animated values.
+ /// The sample has already resolved the target's custom declarations that read animated values,
+ /// which `moved` holds with the animated ones.
pub(crate) fn animated_custom_properties_trigger_restyle(
&self,
node: StyleNodeID,
pseudo: Option<u8>,
+ moved: &[(
+ crate::css::retained_fly_string::RetainedUtf16FlyString,
+ RetainedStyleValueData,
+ )],
has_non_custom_property_animation: bool,
uncached_interval_values_may_need_substitution: bool,
host_custom_property_registration_generation: u64,
@@ -3233,7 +398,7 @@ impl RetainedState {
.element_animation_effects(node, pseudo.map_or(0, |kind| kind + 1))
.iter()
.any(|effect| {
- effect.keyframes.iter().any(|keyframe| {
+ effect.keyframes().iter().any(|keyframe| {
keyframe
.easing_value
.as_ref()
@@ -3274,914 +439,115 @@ impl RetainedState {
return true;
}
- self.ordinary_properties_may_need_substitution(node, pseudo)
- }
-
- /// Whether pseudo styles need updating when the element's custom properties change.
- fn has_pseudo_styles_to_recompute(&self, node: StyleNodeID, view: &computed::StyleRecordView<'_>) -> bool {
- // Existing pseudo-element styles may inherit the sampled values and need to be recomputed.
- if self.computed_group_sets.assigned_pseudo_kinds(node).next().is_some() {
- return true;
- }
-
- // Ignore rules for pseudo-elements that generate no box.
- let pseudo_kinds = view.pseudo_element_styles & !self.inert_pseudo_kinds(node);
- let marker_is_live = view.longhand_table.is_none_or(|table| table.display_is_list_item());
- self.filter_non_generating_pseudo_kinds(node, pseudo_kinds, marker_is_live) != 0
- }
-
- pub(super) fn element_record_winner_state(&self, node: StyleNodeID) -> Option<CascadeStateID> {
- if self.backed_host_pseudo_element(node).is_some() {
- return self
- .computed_group_sets
- .cascade_state(computed::ComputedStyleTarget::new(node, u8::MAX))
- .map(|(_, state)| state);
- }
- match self
- .current_winner_groups()
- .token_for(WinnerGroupKey::current(node, self.program.version()))
- {
- Lookup::Known((_, state)) => Some(state),
- Lookup::KnownAbsent | Lookup::Missing(_) => None,
- }
- }
-
- /// Whether ordinary properties may need to compute against changed custom properties.
- /// Missing winners or values prevent ruling out substitution.
- fn ordinary_properties_may_need_substitution(&self, node: StyleNodeID, pseudo: Option<u8>) -> bool {
- let state = match pseudo {
- Some(kind) => match self.current_winner_groups().token_for(WinnerGroupKey::current_pseudo(
- node,
- tree::PseudoElementTarget::new(tree::PseudoElementKind(u16::from(kind))),
- self.program.version(),
- )) {
- Lookup::Known((_, state)) => Some(state),
- Lookup::KnownAbsent | Lookup::Missing(_) => None,
- },
- None => self.element_record_winner_state(node),
- };
-
- let Some(state) = state else {
+ // The engine keeps the custom properties the longhands of each record it holds substitute.
+ let Some(live) = self.live_style.as_ref() else {
return true;
};
-
- let summary = self.state_summary(node, state);
-
- summary.has_unknown_values || summary.has_substitutions
- }
-
- pub(super) fn state_custom_property_reads(
- &self,
- node: StyleNodeID,
- state: CascadeStateID,
- ) -> Option<custom_property_cascade::CustomPropertyNames> {
- self.winner_groups.state_custom_property_reads(state, || {
- let mut names = Vec::new();
- for value in self.state_substitution_values(node, state) {
- if !custom_property_cascade::append_custom_property_reads(value.data(), &mut names) {
- return None;
- }
- }
- Some(custom_property_cascade::sorted_custom_property_names(names))
- })
- }
-
- /// What a state's winners read beyond the cascade, as `cascade::STATE_READS_*` bits, decided
- /// once for each state.
- pub(super) fn state_reads(&self, node: StyleNodeID, state: CascadeStateID) -> u8 {
- if let Some(reads) = self.winner_groups.state_reads(state) {
- return reads;
- }
- // OPTIMIZATION: An element's own declarations that read nothing between them, as most do, need no winner of
- // theirs asked what it reads. Whether they do is looked up once a winner of theirs is met.
- let mut element_declarations_read_nothing = [None; ElementDeclarationKind::ALL.len()];
- let mut reads = 0;
- // NB: As with the state's summary, what a node that does not find a winner's written value reads says nothing
- // of other nodes.
- let mut every_value_found = true;
- for winner in self
- .winner_groups
- .winners_in_state(state)
- .filter_map(|winner| self.winner_groups.resolved_winner(winner))
- {
- let (_, value, _) = match self.written_winner_value(node, &winner) {
- Ok(Some(written)) => written,
- Ok(None) => {
- every_value_found = false;
- continue;
- }
- Err(_) => continue,
- };
- if let WinnerSource::Element(kind) = winner.source
- && *element_declarations_read_nothing[kind as usize].get_or_insert_with(|| {
- self.facts
- .element_declarations(node, kind)
- .is_some_and(index::ElementDeclarations::read_nothing)
- })
- {
- continue;
- }
- reads |= written_value_reads(winner.property, value);
- }
- if every_value_found {
- self.winner_groups.note_state_reads(state, reads);
- }
- reads
- }
-
- /// The container-relative units a state's winners are written with, as a
- /// `container_relative_length_unit_mask`.
- pub(super) fn state_container_unit_mask(&self, node: StyleNodeID, state: CascadeStateID) -> u8 {
- self.winner_groups
- .winners_in_state(state)
- .filter_map(|winner| self.winner_groups.resolved_winner(winner))
- .filter_map(|winner| self.written_winner_value(node, &winner).ok().flatten())
- .fold(0, |mask, (_, value, _)| {
- mask | crate::css::style_compute::collect_external_value_dependencies(value.data())
- .container_relative_length_unit_mask
- })
- }
-
- /// Whether any of a state's longhand winners, itself or through the shorthand it is pending,
- /// substitutes what the node's own custom-property environment does not decide: the element's
- /// attributes through `attr()`, the parent's environment through `inherit()`, the document's
- /// media features and the element's lengths through `if()`, or the `@function` definitions
- /// through a custom function call. What such a state substitutes to is the element's alone,
- /// as is what a state computes to whose winners draw a random base value for the element or
- /// resolve a container-relative length against the element's query containers, or substitute
- /// under the custom properties the element's animations sample.
- pub(super) fn state_reads_beyond_environment(&self, node: StyleNodeID, state: CascadeStateID) -> bool {
- self.state_reads(node, state)
- & (cascade::STATE_READS_ATTRIBUTES
- | cascade::STATE_READS_INHERIT_FUNCTION
- | cascade::STATE_READS_IF_FUNCTION
- | cascade::STATE_READS_CUSTOM_FUNCTION
- | cascade::STATE_READS_ELEMENT_RANDOM_BASE
- | cascade::STATE_READS_CONTAINER_UNITS)
- != 0
- || (self.element_samples_custom_properties(node) && self.state_has_substitutions(node, state))
- }
-
- /// Whether a record holds a value resolved against the viewport, its own or its font's, which
- /// the record's publication flags carry, or a registered custom property's, which its
- /// environment does.
- pub(super) fn record_reads_the_viewport(&self, record: computed::FinalStyleRecordID) -> bool {
- self.computed_group_sets
- .style_record_view(record.raw())
- .is_some_and(|view| {
- view.dependency_flags & (DEPENDS_ON_VIEWPORT_METRICS | FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS) != 0
- })
- || self
- .computed_group_sets
- .style_record_custom_property_environment(record.raw())
- .is_some_and(|environment| self.custom_property_environments.reads_viewport(environment))
- }
-
- /// Whether a record of the node rolled a property back below a revert keyword a substitution
- /// produced, to a declaration its winners do not name: its records are the node's alone, and
- /// are computed again whatever its winners say.
- pub(super) fn record_rolls_back_substitution(&self, node: StyleNodeID) -> bool {
- self.nodes_with_rolled_back_records.contains_key(&node)
- }
-
- /// Whether the node's records are its alone whatever its winners and environment say, so no
- /// record cache keeps them: one rolled a property back below a substituted revert keyword, or
- /// substituted a value that resolves against the element.
- pub(super) fn records_are_the_elements_alone(&self, node: StyleNodeID) -> bool {
- self.record_rolls_back_substitution(node) || self.nodes_with_element_relative_substitutions.contains_key(&node)
- }
-
- /// The element whose attributes `attr()` reads for a node's record or one of its
- /// pseudo-elements': an element standing for its shadow host's pseudo-element is computed as
- /// that pseudo-element, so it reads the host's, as C++ does for all but its ::first-letter.
- pub(super) fn substitution_attribute_element(&self, node: StyleNodeID, pseudo_kind: Option<u8>) -> StyleNodeID {
- if pseudo_kind == Some(pseudo_kind::FIRST_LETTER) {
- return node;
- }
- self.backed_host_pseudo_element(node).map_or(node, |(_, host)| host)
- }
-
- /// Where `node` stands among its element siblings, as the tree-counting functions count: an
- /// element whose parent is a shadow root has no parent element, and is an only child. `None`
- /// for a node the retained tree does not hold.
- pub(super) fn sibling_position(&self, node: StyleNodeID) -> Option<SiblingPosition> {
- if !self.tree.is_live(node) {
- return None;
- }
- let Some(parent) = self
- .tree
- .parent(node)
- .filter(|&parent| self.tree.host_of(parent).is_none())
- else {
- return Some(SiblingPosition { count: 1, index: 1 });
- };
- // OPTIMIZATION: Each element of a run of many siblings asks for its place as a style pass reaches it, which
- // counting the run every time would make quadratic: the places of a long run are kept until
- // the tree's DOM order changes.
- let mut cache = self
- .sibling_positions
- .lock()
- .expect("the sibling position memo is never held across a panic");
- cache.forget_unless_at(self.tree.dom_order_version());
- if let Some(position) = cache.position_of(parent, node) {
- return Some(position);
- }
- let children: Vec<StyleNodeID> = self
- .tree
- .dom_children(parent)
- .filter(|child| child.text_index().is_none())
- .collect();
- let count = u32::try_from(children.len()).expect("sibling count space exhausted");
- if children.len() >= SiblingPositionCache::MIN_CHILDREN {
- cache.insert(parent, &children);
- }
- let index = children
- .iter()
- .position(|&child| child == node)
- .map_or(0, |index| index as u32 + 1);
- Some(SiblingPosition { count, index })
- }
-
- /// Whether any of a state's winners is written with a tree-counting function.
- pub(super) fn state_has_written_tree_counting(&self, node: StyleNodeID, state: CascadeStateID) -> bool {
- self.state_reads(node, state) & cascade::STATE_READS_SIBLING_POSITION != 0
- }
-
- /// Whether the record `node` holds reads its place among its siblings, written or substituted,
- /// as its installation noted, or as a winner of `state` written with a tree-counting function
- /// says of a record whose installation noted nothing.
- pub(super) fn record_reads_sibling_position(&self, node: StyleNodeID, state: CascadeStateID) -> bool {
- self.nodes_with_tree_counting_records
- .get(&node)
- .is_some_and(|&bits| bits & ELEMENT_READS_SIBLING_POSITION != 0)
- || self.state_has_written_tree_counting(node, state)
- }
-
- /// Note whether the record the engine derived for `node`, or for its pseudo-element of
- /// `pseudo_kind` (`u8::MAX` for the element's own), reads the node's place among its siblings,
- /// in place of what the record it replaces read.
- fn note_sibling_position_reads(&mut self, node: StyleNodeID, pseudo_kind: u8, reads: bool) {
- let bit = match pseudo_kind {
- u8::MAX => ELEMENT_READS_SIBLING_POSITION,
- kind if usize::from(kind) < pseudo_kind::SYNTHETIC_COUNT => 1 << kind,
- // A kind past the synthetic ones is only a read's, which no style update installs.
- _ => return,
- };
- if reads {
- *self.nodes_with_tree_counting_records.entry(node).or_default() |= bit;
- } else if let Some(bits) = self.nodes_with_tree_counting_records.get_mut(&node) {
- *bits &= !bit;
- if *bits == 0 {
- self.nodes_with_tree_counting_records.remove(&node);
- }
- }
- }
-
- /// Where `node` stands among its siblings, for the record caches, when a winner of `state` is
- /// written with a tree-counting function, or a substitution may produce one.
- pub(super) fn sibling_position_key(&self, node: StyleNodeID, state: CascadeStateID) -> Option<SiblingPosition> {
- (self.state_has_written_tree_counting(node, state) || self.state_has_substitutions(node, state))
- .then(|| self.sibling_position(node))
- .flatten()
- }
-
- /// The written values of a state's longhand winners that substitute: `var()`, `attr()` and
- /// the like, or a longhand pending its shorthand's substitution.
- fn state_substitution_values(
- &self,
- node: StyleNodeID,
- state: CascadeStateID,
- ) -> impl Iterator<Item = &crate::css::style_value::RetainedStyleValueData> {
- self.winner_groups.winners_in_state(state).filter_map(move |winner| {
- let winner = self.winner_groups.resolved_winner(winner)?;
- if winner.property < crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID {
- return None;
- }
- let value = match winner.source {
- WinnerSource::Rule(rule) => {
- self.program
- .written_winner_value(rule, winner.property, winner.important, winner.key.value)
- }
- WinnerSource::Element(kind) => self.facts.element_declarations(node, kind).and_then(|declarations| {
- declarations.winner_value(winner.property, winner.important, winner.key.value)
- }),
- WinnerSource::ExactCascade => None,
- }?;
- matches!(
- value.data(),
- crate::css::style_value::StyleValueData::Unresolved { .. }
- | crate::css::style_value::StyleValueData::PendingSubstitution { .. }
- )
- .then_some(value)
+ live.custom_property_reads_of(node, pseudo).is_none_or(|reads| {
+ reads.read_any_of(|read| moved.iter().any(|(name, _)| name.to_utf16().as_ref() == read))
})
}
- /// The cascade a winner state describes, as the drive consumes it: every winner's written
- /// value, seeded in cascade order so a logical property pair resolves the way it cascaded.
- /// `None` when a winner is not a plain rule declaration the engine can compute from.
- fn cascaded_store_for_state(
- &mut self,
- node: StyleNodeID,
- state: CascadeStateID,
- pseudo_kind: Option<u8>,
- environment: custom_property_cascade::SubstitutionEnvironment,
- substituted: &mut bool,
- ) -> Drive<WinnerStore> {
- self.cascaded_store_for_state_in(node, state, pseudo_kind, environment, substituted, StoreUse::Drive)
- }
-
- /// `cascaded_store_for_state`, for a drive or for the admission that proves a drive can
- /// read every winner's written declaration: admission refuses a winner the drive asserts it
- /// finds.
- #[allow(clippy::too_many_arguments)]
- fn cascaded_store_for_state_in(
- &mut self,
- node: StyleNodeID,
- state: CascadeStateID,
- pseudo_kind: Option<u8>,
- environment: custom_property_cascade::SubstitutionEnvironment,
- substituted: &mut bool,
- store_use: StoreUse,
- ) -> Drive<WinnerStore> {
- // A winner whose written declaration is not where its cascade found it.
- let unwritten = |counters: &Counters, invariant: &str| -> Drive<()> {
- if store_use == StoreUse::Admission {
- counters.bump(Counter::EngineComputedRecordBailWinner);
- return Err(Unanswered::Refused);
- }
- debug_assert!(false, "{invariant}");
- Ok(())
- };
- // An element's own values read what its animations sampled into its custom properties.
- let environment = match pseudo_kind {
- None => custom_property_cascade::SubstitutionEnvironment {
- own: self.sampled_custom_property_environment(node, environment.own),
- ..environment
- },
- Some(_) => environment,
- };
- // Seeded in cascade order, and within one rule in declaration order, since a logical
- // property and its physical associate resolve by order of appearance.
- let mut declarations = Vec::with_capacity(self.winner_groups.winner_count_in_state(state));
- // What an `attr()` reads, gathered once for the first winner that reads it. A
- // pseudo-element's reads its originating element's.
- let mut attributes = None;
- let attribute_element = self.substitution_attribute_element(node, pseudo_kind);
- // What a `style()` query in an `if()` resolves against, and the custom functions a call
- // reaches, likewise.
- let mut style_query = None;
- let style_query_references = std::cell::RefCell::new(None);
- let mut functions: Option<custom_property_cascade::PreparedCustomFunctions<'_>> = None;
- // Whether a property rolled back below a substituted revert keyword: what it rolled back to
- // is decided by declarations the winners do not name.
- let mut rolled_back = false;
- // Whether a substitution produced a value that resolves against the element, and the
- // container-relative units it did.
- let mut element_relative = false;
- let mut substituted_container_units = 0;
- 'winners: for winner in self.winner_groups.winners_in_state(state) {
- // A declaration that reverts is remembered as declared, for the logical property group
- // it belongs to.
- let declared_winner = winner;
- // A revert whose continuation resumes at nothing leaves the property undeclared.
- let Some(mut winner) = self.winner_groups.resolved_winner(winner) else {
- // NB: It computes as `unset`, but still wins over a logical counterpart that it reverted past, so
- // a reverted margin-inline-start declared after a margin-left still wins over it. Below every
- // declaration in cascade order, it loses to the counterparts that it did not revert past.
- if declared_winner.property >= crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID
- && let operator @ (CascadeOperator::Revert | CascadeOperator::RevertLayer) =
- declared_winner.key.operator
- && crate::css::property_metadata::property_logical_group(declared_winner.property).is_some()
- && pseudo_kind.is_none_or(|kind| {
- crate::css::property_metadata::pseudo_element_supports_property(kind, declared_winner.property)
- })
- && let Ok(Some((index, ..))) = self.written_winner_value(node, &declared_winner)
- {
- declarations.push((
- CascadePriority::lowest(),
- 0,
- WinnerDeclaration::new(
- declared_winner.property,
- declared_winner.important,
- WinnerValue::Substituted {
- value: unset_value(),
- source: declared_winner.source,
- },
- None,
- ),
- Some(winner_store::RevertedDeclaration {
- position: (declared_winner.priority, index),
- operator,
- }),
- ));
- }
- continue;
- };
- if winner.key.animation_relevance != 0 {
- self.counters.bump(Counter::EngineComputedRecordBailWinnerAnimated);
- return Err(Unanswered::Refused);
- }
- // A pseudo-element's cascade keeps the properties its kind supports. Its animations
- // start, and its transition step runs, where the host installs its record. Its anchor
- // name is a plain computed value: the host registers an element's alone.
- if let Some(kind) = pseudo_kind
- && !crate::css::property_metadata::pseudo_element_supports_property(kind, winner.property)
- {
- continue;
- }
- // A shorthand written with a substitution is declared beside the longhands it
- // pends; those carry it.
- if winner.property < crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID {
- continue;
- }
- // A substitution that produces `revert` or `revert-layer` rolls the property back below
- // the declaration that held it, to a lower declaration that is substituted in turn,
- // as the C++ cascade does. The declarations it rolled back, with the keyword each
- // substituted to.
- let mut reverted = Vec::new();
- let (index, checks, value, borrowed) = loop {
- // A winner's declaration is written in its source. One the engine cannot find again
- // is invalid at computed-value time, and the property is left undeclared: it
- // computes as `unset`.
- let (index, value, checks) = match self.written_winner_value(node, &winner) {
- Ok(Some(written)) => written,
- Ok(None) => {
- unwritten(&self.counters, "a winner's declaration is written in its source")?;
- continue 'winners;
- }
- Err(counter) => {
- self.counters.bump(counter);
- return Err(Unanswered::Refused);
- }
- };
- // A longhand declared through a shorthand keeps the whole shorthand as its
- // written value; the store takes the longhand's own part of it.
- let location = WinnerValue::Written {
- node,
- source: winner.source,
- index,
- };
- let calls_functions = custom_property_cascade::value_calls_custom_functions(value.data());
- if calls_functions && functions.is_none() {
- // A container condition the engine cannot decide asks about an ancestor the
- // host styles in this update: the row waits for it.
- let Some(prepared) = self.prepare_custom_functions(&self.document_functions, node, pseudo_kind)
- else {
- self.counters.bump(Counter::EngineComputedRecordBailRecordParent);
- return Err(Unanswered::AwaitsParent);
- };
- functions = Some(prepared);
- }
- // A function's declarations may hold an `if()` as well.
- if style_query.is_none()
- && (calls_functions || custom_property_cascade::value_reads_conditions(value.data()))
- {
- style_query =
- Some(self.style_query_inputs(computed::ComputedStyleTarget::new(
- node,
- pseudo_kind.unwrap_or(u8::MAX),
- )));
- }
- // An `attr()` reads the element's attributes, written in a longhand or in the
- // shorthand it pends, or in a function's declarations. A state that reads them
- // keeps its store the element's alone.
- let reads_attributes = custom_property_cascade::value_reads_attributes(value.data())
- || (calls_functions && functions.as_ref().is_some_and(|functions| functions.reads_attributes));
- if reads_attributes && attributes.is_none() {
- attributes = Some(custom_property_cascade::SubstitutionAttributes::of(
- &self.facts,
- attribute_element,
- self.html_element_namespace,
- ));
- }
- let (value, borrowed) = match value.data() {
- crate::css::style_value::StyleValueData::Shorthand { .. } => {
- let Some(value) = shorthand_longhand_data(winner.property, value.data()) else {
- unwritten(
- &self.counters,
- "a shorthand written for a longhand winner carries that longhand",
- )?;
- continue 'winners;
- };
- (location, Some(value.data()))
- }
- // A value with var() references substitutes under the node's environment, as
- // the C++ cascade substitutes it; a value invalid at computed-value time is
- // unset.
- crate::css::style_value::StyleValueData::Unresolved { .. } => {
- *substituted = true;
- let value = value.clone_retained();
- let inputs = custom_property_cascade::SubstitutionInputs {
- document: &self.document_style_computation_inputs,
- media: &self.document_media,
- environment,
- attributes: attributes.as_ref().filter(|_| reads_attributes),
- style_query: style_query.as_ref().and_then(Option::as_ref),
- style_query_references: Some(&style_query_references),
- functions: functions.as_ref(),
- };
- let value = Self::substitute_written_value(
- &mut self.custom_property_environments,
- &inputs,
- winner.property,
- value,
- &self.counters,
- )?;
- (
- WinnerValue::Substituted {
- value: invalid_as_unset(value),
- source: winner.source,
- },
- None,
- )
- }
- // A longhand pending its shorthand's substitution takes its part of the
- // substituted shorthand.
- crate::css::style_value::StyleValueData::PendingSubstitution {
- original_shorthand_value,
- } => {
- *substituted = true;
- let Some((shorthand, written)) = self.shorthand_declaration_written_as(
- node,
- winner.source,
- original_shorthand_value.pointer(),
- ) else {
- unwritten(
- &self.counters,
- "a pending longhand's shorthand is written in its source",
- )?;
- continue 'winners;
- };
- let inputs = custom_property_cascade::SubstitutionInputs {
- document: &self.document_style_computation_inputs,
- media: &self.document_media,
- environment,
- attributes: attributes.as_ref().filter(|_| reads_attributes),
- style_query: style_query.as_ref().and_then(Option::as_ref),
- style_query_references: Some(&style_query_references),
- functions: functions.as_ref(),
- };
- let resolved = Self::substitute_written_value(
- &mut self.custom_property_environments,
- &inputs,
- shorthand,
- written,
- &self.counters,
- )?;
- let value = match resolved.data() {
- crate::css::style_value::StyleValueData::GuaranteedInvalid => unset_value(),
- _ => expanded_longhand_value(shorthand, winner.property, &resolved)
- .unwrap_or_else(unset_value),
- };
- (
- WinnerValue::Substituted {
- value,
- source: winner.source,
- },
- None,
- )
- }
- _ => (location, Some(value.data())),
- };
- if let WinnerValue::Substituted {
- value: substituted_value,
- ..
- } = &value
- && let operator @ (CascadeOperator::Revert | CascadeOperator::RevertLayer) =
- super::program_updates::declaration_operator(substituted_value.data())
- {
- reverted.push((winner.priority, operator));
- // An element standing for its host's pseudo-element is cascaded from the host's
- // rules, which its own answer does not hold.
- let below = match self.backed_host_pseudo_element(node) {
- Some(_) => Err(()),
- None => self.winner_below_substitution(node, pseudo_kind, winner.property, &reverted),
- };
- rolled_back = true;
- match below {
- Ok(Some(lower)) => {
- winner = lower;
- continue;
- }
- // Nothing below declares the property: it is undeclared.
- Ok(None) => continue 'winners,
- Err(()) => {
- self.counters.bump(Counter::EngineComputedRecordBailSubstitution);
- return Err(Unanswered::Refused);
- }
- }
- }
- break (index, checks, value, borrowed);
- };
- let data = match &value {
- WinnerValue::Substituted { value, .. } => value.data(),
- WinnerValue::Written { .. } => borrowed.expect("written declaration is borrowed"),
- };
- // A `url()` resolves against the sheet its rule came from, written or substituted, or
- // the document's base URL for an element's own declaration.
- let resources_are_known = match &value {
- WinnerValue::Written {
- source: WinnerSource::Rule(rule),
- ..
- }
- | WinnerValue::Substituted {
- source: WinnerSource::Rule(rule),
- ..
- } => self
- .rule_source_identity(*rule)
- .is_some_and(|source| self.document_resource_contexts.for_source(source).is_some()),
- WinnerValue::Written {
- source: WinnerSource::Element(_),
- ..
- }
- | WinnerValue::Substituted {
- source: WinnerSource::Element(_),
- ..
- } => true,
- _ => false,
- };
- // A value of a shape the computation does not know never reaches a winner, and the
- // drive holds everything else a value may read beyond the record, the parent and the
- // document's computation inputs, in any mix. A random function or a container-relative
- // length that appears through a substitution resolves against the element, which the
- // record caches key a state's written winners on but not what the environment
- // substitutes: the record is the element's alone.
- let computable = checks.longhand_context_free == Some(true)
- || crate::css::style_compute::value_is_computationally_independent(data).is_some_and(|_| {
- let dependencies = crate::css::style_compute::external_value_dependencies(data);
- if matches!(value, WinnerValue::Substituted { .. }) {
- element_relative |= value_resolves_against_the_element(&dependencies);
- substituted_container_units |= dependencies.container_relative_length_unit_mask;
- }
- drive_holds_value_inputs(&dependencies, resources_are_known, || {
- self.sibling_position(node).is_some()
- })
- });
- debug_assert!(
- computable || crate::css::style_compute::value_is_computationally_independent(data).is_some(),
- "a cascade winner computes to a value of a known shape"
- );
- if !computable {
- self.counters.bump(Counter::EngineComputedRecordBailValue);
- return Err(Unanswered::Refused);
- }
- let revert = if winner == declared_winner {
- None
- } else {
- let operator = match declared_winner.key.operator {
- operator @ (CascadeOperator::Revert | CascadeOperator::RevertLayer) => operator,
- _ => reverted
- .first()
- .map_or(CascadeOperator::Revert, |&(_, operator)| operator),
- };
- // NB: Without the reverting declaration's position, the winner still applies, and its logical
- // property group falls back to ordering by cascade position.
- match self.written_winner_value(node, &declared_winner) {
- Ok(Some((declared_index, ..))) => Some(winner_store::RevertedDeclaration {
- position: (declared_winner.priority, declared_index),
- operator,
- }),
- _ => None,
- }
- };
- declarations.push((
- winner.priority,
- index,
- WinnerDeclaration::new(
- winner.property,
- winner.important,
- value,
- Some(winner.priority.cascade_origin()),
- ),
- revert,
- ));
- }
- // What a function's container conditions read is recorded with the node's record, as a
- // gated rule's is.
- if let Some(effects) = functions.and_then(|functions| functions.container_effects) {
- self.note_container_effects_for_host(node, effects);
- }
- declarations.sort_by_key(|(priority, index, ..)| (*priority, *index));
- let mut positions = Vec::with_capacity(declarations.len());
- let mut reverted_declarations = Vec::new();
- let mut store_declarations = Vec::with_capacity(declarations.len());
- for (store_index, (priority, index, declaration, revert)) in declarations.into_iter().enumerate() {
- positions.push((priority, index));
- if let Some(revert) = revert {
- reverted_declarations.push((store_index, revert));
- }
- store_declarations.push(declaration);
- }
- let mut store = WinnerStore::new(store_declarations);
- store.set_reverted_declarations(positions, reverted_declarations);
- store.reads_sibling_position = style_query_references
- .borrow()
- .as_ref()
- .is_some_and(|dependencies| dependencies.sibling_position);
- // A store built to drive a record says whether that record rolls back; one built to admit a
- // row only adds to what the node's records are known to do.
- let bit = rolled_back_bit(pseudo_kind);
- if rolled_back {
- *self.nodes_with_rolled_back_records.entry(node).or_default() |= bit;
- } else if store_use == StoreUse::Drive
- && let Some(bits) = self.nodes_with_rolled_back_records.get_mut(&node)
- {
- *bits &= !bit;
- if *bits == 0 {
- self.nodes_with_rolled_back_records.remove(&node);
- }
- }
- // So does one whose substitutions resolve against the element.
- if element_relative {
- let substitutions = self.nodes_with_element_relative_substitutions.entry(node).or_default();
- substitutions.records |= bit;
- substitutions.container_units |= substituted_container_units;
- } else if store_use == StoreUse::Drive
- && let Some(substitutions) = self.nodes_with_element_relative_substitutions.get_mut(&node)
- {
- substitutions.records &= !bit;
- if substitutions.records == 0 {
- self.nodes_with_element_relative_substitutions.remove(&node);
- }
- }
- // The custom properties its `style()` queries read are the element's style query
- // references, which the host records with its record.
- if store_use == StoreUse::Drive
- && let Some(references) = style_query_references.into_inner()
- {
- self.note_container_effects_for_host(
- node,
- super::container_queries::ContainerVerdict {
- style_query_references: Some(references),
- ..Default::default()
- },
- );
- }
- if store_use == StoreUse::Drive {
- store.draw_random_base_values(self, node);
- }
- Ok(store)
- }
-
- /// Whether every cascade winner that moved on this node since its record was computed is a
- /// longhand the engine computes itself. Such a change cannot reach the node's descendants:
- /// nothing inherited moves, and no custom property does, so a descendant's engine-computed
- /// record stays exact even though this ancestor changes in the same batch.
- pub(super) fn winner_delta_is_engine_confined(&self, node: StyleNodeID) -> bool {
- if self.backed_host_pseudo_element(node).is_some() {
- return false;
- }
- let target = computed::ComputedStyleTarget::new(node, u8::MAX);
- let Lookup::Known((generation, state)) = self
- .current_winner_groups()
- .token_for(WinnerGroupKey::current(node, self.program.version()))
- else {
- return false;
- };
- let Some((previous_generation, previous_state)) = self.computed_group_sets.cascade_state(target) else {
- return false;
- };
- if previous_generation != generation {
- return false;
- }
- // A descendant's engine-computed record is assembled before C++ applies the ancestor, so
- // nothing the descendant inherits may move; custom properties inherit unless registered
- // otherwise, and a child's box-type transformation reads its parent's display.
- let mut moves_non_inherited = false;
- let confined = self
- .winner_groups
- .semantic_delta_properties(Some(previous_state), state)
- .all(|property| {
- moves_non_inherited = true;
- property != crate::css::property_metadata::property_id::CUSTOM
- && property != crate::css::property_metadata::property_id::DISPLAY
- && !crate::css::property_metadata::property_is_inherited(property)
- });
- // A child that explicitly inherits a non-inherited property inherits it like any other,
- // and passes it on to a descendant whose record is assembled from the child's.
- confined && !(moves_non_inherited && self.children_explicitly_inherit_non_inherited_properties(node))
- }
-
- /// Whether any of the node's children, as its descendants inherit through them, explicitly
- /// inherits a non-inherited property.
- fn children_explicitly_inherit_non_inherited_properties(&self, node: StyleNodeID) -> bool {
- // A text slottable holds a place among a slot's assigned nodes, but inherits nothing on.
- self.tree
- .flat_tree_children(node)
- .filter(|child| child.element_index().is_some())
- .any(|child| self.node_explicitly_inherits_non_inherited_property(child))
- }
-
- /// Publish the immutable computed-group payloads of one element's base style. This assigns
- /// dense identities to shared payloads and their ordered tuple, so an equal handle proves equal
- /// groups and downstream operators can consume one node handle.
- pub(crate) fn publish_computed_groups(
- &mut self,
- target: computed::ComputedStyleTarget,
- payloads: &[SharedPayload],
- inherited_group_count: usize,
- custom_property_environment: u64,
- metadata_input: computed::ComputedMetadataInput<'_>,
- ) -> computed::ComputedGroupPublication {
- let mut scratch = EngineComputabilityScratch::default();
- let publication = self.publish_computed_groups_impl(
- Some(target),
- payloads,
- inherited_group_count,
- custom_property_environment,
- metadata_input,
- computed::PendingRecordOwnership::default(),
- &mut scratch,
- );
-
- drop(scratch);
+ /// Whether pseudo styles need updating when the element's custom properties change.
+ fn has_pseudo_styles_to_recompute(&self, node: StyleNodeID, view: &computed::StyleRecordView<'_>) -> bool {
+ // Existing pseudo-element styles may inherit the sampled values and need to be recomputed.
+ if self.computed_group_sets.assigned_pseudo_kinds(node).next().is_some() {
+ return true;
+ }
- publication
+ // Ignore rules for pseudo-elements that generate no box.
+ let pseudo_kinds = view.pseudo_element_styles;
+ let marker_is_live = view.longhands().display_is_list_item();
+ self.filter_non_generating_pseudo_kinds(node, pseudo_kinds, marker_is_live) != 0
}
- pub(crate) fn assign_shared_style_record(
- &mut self,
- target: computed::ComputedStyleTarget,
- style_record: u64,
- inherited_group_count: usize,
- inherited_group_swap_eligible: bool,
- ) -> computed::ComputedGroupPublication {
- let group_count = self
- .computed_group_sets
- .style_record_payloads(style_record)
- .expect("a shared style record must name a live base record")
- .len();
- let current_cascade_state = self.computed_group_sets.take_pending_cascade_state(target);
- let publication = self
- .computed_group_sets
- .assign_shared_style_record(
- target,
- style_record,
- inherited_group_count,
- inherited_group_swap_eligible,
- )
- .expect("a shared style record must name a live base record");
- if let Some(current_cascade_state) = current_cascade_state {
- self.bind_published_cascade_state(target, current_cascade_state, publication.node_handle_changed);
- } else {
- self.computed_group_sets.clear_cascade_state(target);
- }
- self.counters.add(Counter::ComputedGroupsReused, group_count as u64);
- self.note_identity_mints();
- self.counters.bump(Counter::ComputedGroupSetsReused);
- self.counters.bump(Counter::InheritedGroupSetsReused);
- self.counters.bump(Counter::CustomPropertyEnvironmentsReused);
- self.counters.bump(Counter::ComputedFixedMetadataReused);
- self.counters.bump(Counter::StyleRecordsReused);
- if publication.node_handle_changed {
- self.counters.bump(Counter::ComputedGroupNodeHandlesPublished);
- }
- if publication.inherited_node_handle_changed {
- self.counters.bump(Counter::InheritedGroupNodeHandlesPublished);
- }
- if publication.custom_property_environment_node_handle_changed {
- self.counters
- .bump(Counter::CustomPropertyEnvironmentNodeHandlesPublished);
- }
- if publication.computed_fixed_metadata_node_handle_changed {
- self.counters.bump(Counter::ComputedFixedMetadataNodeHandlesPublished);
+ /// The element whose attributes `attr()` reads for a node's record or one of its
+ /// pseudo-elements': an element standing for its shadow host's pseudo-element is computed as
+ /// that pseudo-element, so it reads the host's, as C++ does for all but its ::first-letter.
+ pub(super) fn substitution_attribute_element(&self, node: StyleNodeID, pseudo_kind: Option<u8>) -> StyleNodeID {
+ if pseudo_kind == Some(pseudo_kind::FIRST_LETTER) {
+ return node;
}
- if publication.style_record_node_handle_changed {
- self.counters.bump(Counter::StyleRecordNodeHandlesPublished);
+ self.backed_host_pseudo_element(node).map_or(node, |(_, host)| host)
+ }
+
+ /// Where `node` stands among its element siblings, as the tree-counting functions count: an
+ /// element whose parent is a shadow root has no parent element, and is an only child. `None`
+ /// for a node the retained tree does not hold.
+ pub(super) fn sibling_position(&self, node: StyleNodeID) -> Option<SiblingPosition> {
+ if !self.projection.is_live(node) {
+ return None;
}
- if publication.animation_overlay_slot_released {
- self.counters.bump(Counter::AnimationOverlaySlotsReleased);
+ let Some(parent) = self
+ .projection
+ .parent(node)
+ .filter(|&parent| self.projection.host_of(parent).is_none())
+ else {
+ return Some(SiblingPosition { count: 1, index: 1 });
+ };
+ // OPTIMIZATION: Each element of a run of many siblings asks for its place as a style pass reaches it, which
+ // counting the run every time would make quadratic: the places of a long run are kept until
+ // the tree's DOM order changes.
+ let mut cache = self
+ .sibling_positions
+ .lock()
+ .expect("the sibling position memo is never held across a panic");
+ cache.forget_unless_at(self.tree.dom_order_version());
+ if let Some(position) = cache.position_of(parent, node) {
+ return Some(position);
}
- self.counters.set(
- Counter::LiveAnimationOverlayRecords,
- publication.live_animation_overlay_records as u64,
- );
- if publication.is_pseudo && publication.style_record_node_handle_changed {
- self.counters.bump(Counter::ComputedPseudoAssignmentsPublished);
+ let children: Vec<StyleNodeID> = self
+ .tree
+ .dom_children(parent)
+ .filter(|child| child.text_index().is_none())
+ .collect();
+ let count = u32::try_from(children.len()).expect("sibling count space exhausted");
+ if children.len() >= SiblingPositionCache::MIN_CHILDREN {
+ cache.insert(parent, &children);
}
- publication
+ let index = children
+ .iter()
+ .position(|&child| child == node)
+ .map_or(0, |index| index as u32 + 1);
+ Some(SiblingPosition { count, index })
}
- /// Intern the immutable computed-group payloads of a style which has no live StyleEngine target.
- pub(crate) fn intern_computed_groups(
+ /// Install a record of `table`'s values, or of the initial ones where it has none, holding
+ /// `payloads`, or the default ones where none are given, styling the pseudo-elements of the
+ /// bits of `pseudo_element_styles`, and assign it to `target`.
+ #[cfg(test)]
+ pub(crate) fn install_test_record(
&mut self,
- payloads: &[SharedPayload],
- inherited_group_count: usize,
- custom_property_environment: u64,
- metadata_input: computed::ComputedMetadataInput<'_>,
- ) -> computed::ComputedGroupPublication {
- self.publish_computed_groups_impl(
- None,
- payloads,
- inherited_group_count,
- custom_property_environment,
- metadata_input,
- computed::PendingRecordOwnership::default(),
- &mut EngineComputabilityScratch::default(),
- )
+ target: computed::ComputedStyleTarget,
+ value_of: Option<&dyn Fn(u16) -> RetainedStyleValueData>,
+ payloads: Option<&crate::css::computed_values::StyleGroups>,
+ pseudo_element_styles: u64,
+ ) -> computed::FinalStyleRecordID {
+ let initial = |property| crate::css::style_compute::initial_value_handle(property).clone();
+ let source = super::pipeline::Record::of_test_values(|property| {
+ value_of.map_or_else(|| initial(property), |value_of| value_of(property))
+ });
+ let payloads = payloads
+ .cloned()
+ .unwrap_or_else(|| self.default_groups().groups().clone());
+ let record = std::sync::Arc::new(super::pipeline::Record::derived(&source, &payloads))
+ .with_pseudo_element_styles(super::pipeline::PseudoElementStyles::from_bits(pseudo_element_styles));
+ let identity = self.computed_group_sets.install_record(&record, || {
+ computed::record_dependency_flags(&record.facts(), &record.payloads)
+ });
+ match target.is_pseudo() {
+ true => {
+ self.computed_group_sets
+ .assign_installed_pseudo_record(target.node(), target.pseudo_kind(), identity)
+ }
+ false => self
+ .computed_group_sets
+ .assign_installed_record(target.node(), identity),
+ }
+ identity
}
- pub(crate) fn style_record_payloads(&self, style_record: u64) -> Option<&[SharedPayload]> {
+ pub(crate) fn style_record_payloads(&self, style_record: u64) -> Option<&crate::css::computed_values::StyleGroups> {
self.computed_group_sets.style_record_payloads(style_record)
}
@@ -4199,6 +565,11 @@ impl RetainedState {
self.computed_group_sets.style_record_view(style_record)
}
+ /// The record the host holds for the live record `style_record`.
+ pub(crate) fn host_record(&self, style_record: u64) -> Option<&std::sync::Arc<super::pipeline::Record>> {
+ self.computed_group_sets.host_record(style_record)
+ }
+
pub(crate) fn take_released_animation_overlay_records(&mut self) -> computed::ReleasedAnimationOverlayRecords {
// Even an empty take copies the sets while a fork shares them.
if !self.computed_group_sets.has_released_animation_overlay_records() {
@@ -4231,170 +602,10 @@ impl RetainedState {
.expect("style-record view epoch depth overflow");
}
- /// Publishes how many identities each catalog has minted. These count the sharing partition
- /// a run produces; the reuse counters beside them credit whichever publication interned an
- /// identity first, which is an execution-order decision.
- fn note_identity_mints(&mut self) {
- let mints = self.computed_group_sets.identity_mints();
- self.counters.set(Counter::ComputedGroupIdentitiesMinted, mints.groups);
- self.counters
- .set(Counter::ComputedGroupSetIdentitiesMinted, mints.group_sets);
- self.counters
- .set(Counter::InheritedGroupSetIdentitiesMinted, mints.inherited_group_sets);
- self.counters
- .set(Counter::StyleRecordIdentitiesMinted, mints.style_records);
- }
-
pub(crate) fn unpin_style_record(&mut self, style_record: u64) {
self.computed_group_sets.unpin_style_record(style_record);
}
- fn bind_published_cascade_state(
- &mut self,
- target: computed::ComputedStyleTarget,
- (current_generation, current_cascade_state): (u64, CascadeStateID),
- node_handle_changed: bool,
- ) {
- let previous_cascade_state = self
- .computed_group_sets
- .bind_cascade_state(target, (current_generation, current_cascade_state))
- .and_then(|(previous_generation, previous_state)| {
- (previous_generation == current_generation).then_some(previous_state)
- });
- // A first binding moves every winner of the state, which needs no merge to count.
- let changed_properties = match previous_cascade_state {
- None => self.winner_groups.winner_count_in_state(current_cascade_state),
- previous => self
- .winner_groups
- .semantic_delta_properties(previous, current_cascade_state)
- .count(),
- };
- if changed_properties == 0 {
- self.counters.bump(Counter::CascadeWinnerDeltaStops);
- return;
- }
- self.counters
- .add(Counter::CascadeWinnerDeltaProperties, changed_properties as u64);
- self.counters.add(
- Counter::ComputedWinnerDeltaPropertiesConsumed,
- changed_properties as u64,
- );
- if !node_handle_changed {
- self.counters.bump(Counter::ComputedWinnerPropagationStops);
- }
- }
-
- #[allow(clippy::too_many_arguments)]
- /// `owned` says which payloads, and whether the table, the caller hands to the catalog; the
- /// publication says which of those references the catalog took.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn publish_computed_groups_impl(
- &mut self,
- target: Option<computed::ComputedStyleTarget>,
- payloads: &[SharedPayload],
- inherited_group_count: usize,
- custom_property_environment: u64,
- metadata_input: computed::ComputedMetadataInput<'_>,
- owned: computed::PendingRecordOwnership,
- scratch: &mut EngineComputabilityScratch,
- ) -> computed::ComputedGroupPublication {
- let current_cascade_state =
- target.and_then(|target| self.computed_group_sets.take_pending_cascade_state(target));
- let is_base_record = metadata_input.animation_overlay_identity == 0;
- let pseudo_styles = metadata_input.pseudo_element_styles;
- let publication = self.computed_group_sets.publish(
- target,
- payloads,
- inherited_group_count,
- custom_property_environment,
- metadata_input,
- owned,
- );
- if let Some(target) = target
- && !target.is_pseudo()
- && self.computed_group_sets.adjustment_facts(target.node())
- & bridge::element_adjustment_fact::IS_DOCUMENT_ELEMENT
- != 0
- {
- self.prepare_root_font_metrics_from_record(publication.style_record_identity);
- }
- if let Some(current_cascade_state) = current_cascade_state {
- let target = target.expect("only a target has pending cascade state");
- self.bind_published_cascade_state(target, current_cascade_state, publication.node_handle_changed);
- self.remember_cold_record_candidate(
- target,
- current_cascade_state,
- custom_property_environment,
- pseudo_styles,
- publication.previous_style_record_identity,
- publication.style_record_identity,
- is_base_record,
- scratch,
- );
- } else if let Some(target) = target {
- self.computed_group_sets.clear_cascade_state(target);
- }
- self.counters.add(
- Counter::ComputedOutputGroupsCanonicalized,
- publication.canonical_output_groups_reused as u64,
- );
- self.counters.add(
- Counter::ComputedGroupsReused,
- (payloads.len() - publication.new_groups) as u64,
- );
- self.note_identity_mints();
- if !publication.new_group_set {
- self.counters.bump(Counter::ComputedGroupSetsReused);
- }
- if !publication.new_inherited_group_set {
- self.counters.bump(Counter::InheritedGroupSetsReused);
- }
- if publication.node_handle_changed {
- self.counters.bump(Counter::ComputedGroupNodeHandlesPublished);
- }
- if publication.inherited_node_handle_changed {
- self.counters.bump(Counter::InheritedGroupNodeHandlesPublished);
- }
- if !publication.new_custom_property_environment {
- self.counters.bump(Counter::CustomPropertyEnvironmentsReused);
- }
- if publication.custom_property_environment_node_handle_changed {
- self.counters
- .bump(Counter::CustomPropertyEnvironmentNodeHandlesPublished);
- }
- match publication.new_computed_fixed_metadata {
- true => self.counters.bump(Counter::ComputedFixedMetadataInterned),
- false => self.counters.bump(Counter::ComputedFixedMetadataReused),
- }
- if publication.computed_fixed_metadata_node_handle_changed {
- self.counters.bump(Counter::ComputedFixedMetadataNodeHandlesPublished);
- }
- match publication.new_style_record {
- true => self.counters.bump(Counter::StyleRecordsInterned),
- false => self.counters.bump(Counter::StyleRecordsReused),
- }
- if publication.style_record_node_handle_changed {
- self.counters.bump(Counter::StyleRecordNodeHandlesPublished);
- }
- if publication.animation_overlay_slot_allocated {
- self.counters.bump(Counter::AnimationOverlaySlotsAllocated);
- }
- if publication.animation_overlay_slot_released {
- self.counters.bump(Counter::AnimationOverlaySlotsReleased);
- }
- if publication.animation_overlay_record_updated {
- self.counters.bump(Counter::AnimationOverlayRecordsUpdated);
- }
- self.counters.set(
- Counter::LiveAnimationOverlayRecords,
- publication.live_animation_overlay_records as u64,
- );
- if publication.is_pseudo && publication.style_record_node_handle_changed {
- self.counters.bump(Counter::ComputedPseudoAssignmentsPublished);
- }
- publication
- }
-
pub(crate) fn current_color_dependent_group_mask(&self, node: StyleNodeID, pseudo_kind: u8) -> Option<u32> {
let target = computed::ComputedStyleTarget::new(node, pseudo_kind);
let dependencies = self.computed_group_sets.current_color_dependency_mask(target)?;
@@ -4408,14 +619,6 @@ impl RetainedState {
node: StyleNodeID,
pseudo_kind: u8,
) -> Option<computed::FinalStyleRecordID> {
- let target = computed::ComputedStyleTarget::new(node, pseudo_kind);
- // A record the engine derived for the pseudo-element goes with it, uninstalled: the host removed the
- // pseudo-element instead, as where its element left the top layer beside the transaction that derived it.
- self.forget_engine_computed_record(target);
- if let Some(state) = self.computed_group_sets.take_pending_cascade_state(target) {
- self.computed_group_sets
- .observe_absent_pseudo_cascade_state(target, state);
- }
let live_animation_overlays_before = self.computed_group_sets.live_animation_overlay_records();
let removed_style_record = self.computed_group_sets.remove_pseudo(node, pseudo_kind);
let live_animation_overlays_after = self.computed_group_sets.live_animation_overlay_records();
@@ -4442,23 +645,18 @@ impl StyleEngine {
self.reclaim_unreachable_computed_records();
}
- /// Reclaims the unreachable computed records, if they are due and nothing views them, and answers whether it did.
+ /// Frees the installed records nothing holds, where nothing views them, and once enough were freed reclaims the
+ /// custom-property environments no record names any more. Answers whether it reclaimed them.
pub(super) fn reclaim_unreachable_computed_records(&mut self) -> bool {
let records_are_viewed = self.retained.style_record_view_epoch_depth != 0;
- let Some(retention) = self
+ if !self
.retained
.computed_group_sets
.reclaim_unreachable_if_needed(records_are_viewed)
- else {
+ {
return false;
- };
- self.retained
- .counters
- .set(Counter::ComputedGroupsRetained, retention.retained as u64);
- self.retained
- .counters
- .set(Counter::ComputedGroupsReachable, retention.reachable as u64);
- // An element's animation overlay is named by no record, only by the element holding it.
+ }
+ // An animation overlay is named by no record, only by the element or pseudo-element holding it.
let live: super::fast_hash::FastSet<u64> = self
.retained
.computed_group_sets
@@ -4469,27 +667,31 @@ impl StyleEngine {
.values()
.map(|held| held.identity),
)
+ .chain(
+ self.retained
+ .pseudo_element_custom_property_data
+ .values()
+ .flat_map(|environments| environments.iter().map(|(_, held)| held.identity)),
+ )
.collect();
self.retained
.custom_property_environments
.retain_only(|identity| live.contains(&identity));
- self.retained.forget_custom_property_environments_by_answer();
true
}
pub(super) fn publish_animation_overlay_impl(
&mut self,
target: computed::ComputedStyleTarget,
- installed_style_record: computed::FinalStyleRecordID,
source_identity: u64,
animated_overlay: HostShared<crate::css::animated_overlay::AnimatedOverlay>,
- payloads: &[SharedPayload],
+ payloads: Option<&crate::css::computed_values::StyleGroups>,
) -> Option<computed::AnimationOverlayUpdate> {
// A pseudo-element inherits from its element.
let parent = if target.is_pseudo() {
Some(target.node())
} else {
- self.retained.tree.inheritance_parent(target.node())
+ self.retained.projection.inheritance_parent(target.node())
};
let parent_in_display_none_subtree = parent
.and_then(|parent| self.retained.computed_group_sets.assigned_style_record(parent))
@@ -4499,629 +701,84 @@ impl StyleEngine {
.style_record_dependency_flags(record.raw())
})
.is_some_and(|flags| flags & computed::IN_DISPLAY_NONE_SUBTREE != 0);
- let publication = self
- .publish_animation_overlay_beneath_derivation(
- target,
- installed_style_record,
- source_identity,
- animated_overlay,
- payloads,
- parent_in_display_none_subtree,
- )
- .or_else(|| {
- self.retained.computed_group_sets.publish_animation_overlay(
- target,
- source_identity,
- animated_overlay,
- payloads,
- parent_in_display_none_subtree,
- )
- })?;
- if publication.slot_allocated {
- self.retained.counters.bump(Counter::AnimationOverlaySlotsAllocated);
- }
- if publication.slot_released {
- self.retained.counters.bump(Counter::AnimationOverlaySlotsReleased);
- }
- if publication.record_updated {
- self.retained.counters.bump(Counter::AnimationOverlayRecordsUpdated);
- }
- self.retained
- .counters
- .set(Counter::LiveAnimationOverlayRecords, publication.live_records as u64);
- Some(publication)
- }
-
- fn publish_animation_overlay_beneath_derivation(
- &mut self,
- target: computed::ComputedStyleTarget,
- installed_style_record: computed::FinalStyleRecordID,
- source_identity: u64,
- animated_overlay: HostShared<crate::css::animated_overlay::AnimatedOverlay>,
- payloads: &[SharedPayload],
- parent_in_display_none_subtree: bool,
- ) -> Option<computed::AnimationOverlayUpdate> {
- let computed_group_sets = &self.retained.computed_group_sets;
- if computed_group_sets.assigned_final_style_record(target)? == installed_style_record {
- return None;
- }
- let assigned = computed_group_sets.assigned_underlying_style_record(target)?;
- let derivation = self
- .retained
- .engine_computed_records_pending
- .get_mut(&target.node())
- .and_then(|pending| {
- pending.iter_mut().find(|pending| {
- pending.pseudo_kind == target.pseudo_kind()
- && computed_group_sets.underlying_style_record(pending.new_style_record) == Some(assigned)
- })
- });
- debug_assert!(
- derivation.is_some()
- || computed_group_sets
- .underlying_style_record(installed_style_record)
- .is_none_or(|installed| installed == assigned),
- "only a pending derivation moves an assignment off the base of the record the host installed"
- );
- let derivation = derivation?;
- let (publication, composition) = self.retained.computed_group_sets.compose_detached_animation_overlay(
- installed_style_record,
+ // The children of an element style styles inherit the composition of its
+ // animations, which they compute again where it moves.
+ let held_composition = match target.is_pseudo() {
+ true => None,
+ false => self.hold_composition(target.node()),
+ };
+ let publication = self.retained.computed_group_sets.publish_animation_overlay(
+ target,
source_identity,
animated_overlay,
payloads,
parent_in_display_none_subtree,
- )?;
- if publication.style_record != installed_style_record {
- derivation.old_style_record = publication.style_record;
- let replaced = std::mem::replace(&mut derivation.detached_composition, composition);
- if let Some(replaced) = replaced {
- self.retained.computed_group_sets.release_detached_composition(replaced);
- }
- }
- Some(publication)
- }
-}
-
-/// What the records of a node substitute that resolves against the element itself, which makes
-/// them the element's alone.
-#[derive(Clone, Copy, Default)]
-pub(super) struct ElementRelativeSubstitutions {
- /// The records that do, a bit each as `rolled_back_bit` numbers them.
- records: u64,
- /// The container-relative units they substituted, as a `container_relative_length_unit_mask`.
- pub(super) container_units: u8,
-}
-
-/// The bit of `nodes_with_rolled_back_records` that stands for a node's element record, or for one
-/// of its pseudo-element records.
-fn rolled_back_bit(pseudo_kind: Option<u8>) -> u64 {
- match pseudo_kind {
- Some(kind) => {
- debug_assert!(kind < 63, "a pseudo-element kind leaves the element's bit free");
- 1 << kind
- }
- None => 1 << 63,
- }
-}
-
-/// The element facts a cold record is keyed by: every fact but the ones only the layout tree build
-/// or a record move's damage reads, which no style depends on.
-fn cold_record_facts(facts: u32) -> u32 {
- use bridge::element_adjustment_fact::{LAYOUT_TREE_FACTS, RECORD_DAMAGE_FACTS};
- facts & !(LAYOUT_TREE_FACTS | RECORD_DAMAGE_FACTS)
-}
-
-/// The bit a node's own record holds among what its records read of its place among its siblings,
-/// above one bit per synthetic pseudo-element kind.
-const ELEMENT_READS_SIBLING_POSITION: u16 = 1 << pseudo_kind::SYNTHETIC_COUNT;
-
-/// The places of the element children of parents with many of them, as
-/// [`RetainedState::sibling_position`] counts them, at one version of the tree's DOM order.
-#[derive(Default)]
-pub(super) struct SiblingPositionCache {
- dom_order_version: u64,
- /// How many element children each parent counted has.
- counts: super::fast_hash::FastMap<StyleNodeID, u32>,
- /// The place of each counted child among its parent's element children, counted from one.
- indices: super::fast_hash::FastMap<StyleNodeID, u32>,
-}
-
-impl SiblingPositionCache {
- /// How many element children a parent has before their places are kept: fewer are counted again
- /// as quickly as they are looked up.
- const MIN_CHILDREN: usize = 32;
-
- /// Forgets the places counted at a version of the DOM order other than `dom_order_version`.
- fn forget_unless_at(&mut self, dom_order_version: u64) {
- if self.dom_order_version != dom_order_version {
- self.counts.clear();
- self.indices.clear();
- self.dom_order_version = dom_order_version;
- }
- }
-
- fn position_of(&self, parent: StyleNodeID, node: StyleNodeID) -> Option<SiblingPosition> {
- Some(SiblingPosition {
- count: *self.counts.get(&parent)?,
- index: *self.indices.get(&node)?,
- })
- }
-
- fn insert(&mut self, parent: StyleNodeID, children: &[StyleNodeID]) {
- self.counts.insert(parent, children.len() as u32);
- for (index, &child) in children.iter().enumerate() {
- self.indices.insert(child, index as u32 + 1);
- }
- }
-}
-
-/// Where an element stands among its element siblings, counted from one: what `sibling-count()`
-/// and `sibling-index()` read.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
-pub(super) struct SiblingPosition {
- pub(super) count: u32,
- pub(super) index: u32,
-}
-
-/// Whether a record derived under a display:none parent is keyed by the parent's display.
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub(super) enum UnderDisplayNone {
- NoKey,
- Keyed,
-}
-
-/// What a first record was derived from: the parent's side of the computation, the winner state
-/// (with the generation its identity belongs to), the element facts, the pseudo-elements the
-/// element has rules for, and the font environment.
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-pub(super) struct ColdRecordKey {
- /// What the monospace font-size recascade gives this node, or zero when its winning
- /// font-family is not monospace. The recascade reads the whole cascaded chain, which equal
- /// parent records do not pin down.
- monospace_recascaded_font_size: i32,
- parent: ColdRecordParent,
- previous_style_record: u64,
- generation: u64,
- state: CascadeStateID,
- facts: u32,
- /// The pseudo-elements the element has rules for: the record's metadata says which, and
- /// C++ computes their styles beside it.
- pseudo_styles: u64,
- /// The custom-property environment the record is published with.
- environment: u64,
- font_environment_generation: u64,
- root_font_inputs: RootFontInputs,
- /// Where the element stands among its siblings, when its winners read it.
- sibling_position: Option<SiblingPosition>,
-}
-
-/// What a first record reads of the parent's style: its inherited groups, its custom-property
-/// environment, its dependency flags, and the display the box-type transformation takes as the
-/// parent's. A state that explicitly inherits a non-inherited property reads the parent's whole
-/// table, so it keys on the parent's record instead.
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-struct ColdRecordParent {
- record: u64,
- inherited_groups: u32,
- environment: u64,
- dependency_flags: u8,
- parent_blockifies: bool,
-}
-
-/// What a warm record is derived from: the record it replaces, the winner state, the element
-/// facts, the parent, the custom-property environment, the root's font inputs, the monospace
-/// recascade and the sibling position a tree-counting function reads. A record whose winners read
-/// `attr()` has none: it is the element's alone.
-type RecordCohortKey = (
- u64,
- CascadeStateID,
- u32,
- RecordDeltaParent,
- u64,
- RootFontInputs,
- i32,
- Option<SiblingPosition>,
-);
-
-/// A first record the engine keeps for reuse, with the swap eligibility its assignment carries,
-/// the style groups it read straight from the parent through an explicit `inherit`, which every
-/// element it answers for marks its own parent with, and whether it reads the element's place
-/// among its siblings, which every element it answers for is noted as reading.
-#[derive(Clone, Copy)]
-pub(super) struct ColdRecord {
- record: computed::FinalStyleRecordID,
- swap_eligible: bool,
- explicitly_inherited_groups: u32,
- reads_sibling_position: bool,
-}
-
-/// The proof that a record reads no resource context: no value its winners give it resolves a
-/// `url()` against a style sheet's or the document's base URL. The engine keeps only such records
-/// across transactions, so a move of those base URLs, which every `history.pushState()` makes
-/// without a `<base>`, leaves nothing it keeps to forget.
-#[derive(Clone, Copy)]
-pub(super) struct ReadsNoResourceContexts(());
-
-/// What a record computed from a winner state reads beside the state's winners: the element's
-/// place among its siblings, and whether a `url()` resolves against a resource context.
-#[derive(Clone, Copy)]
-pub(super) struct StateRecordReads {
- pub(super) sibling_position: bool,
- pub(super) no_resource_contexts: Option<ReadsNoResourceContexts>,
-}
-
-/// The value-independent half of a first-record key. Records under the same key may seed one
-/// another, with the semantic cascade delta selecting the values which must be recomputed.
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-pub(super) struct ColdRecordDonorKey {
- parent: ColdRecordParent,
- generation: u64,
- property_shape_hash: u64,
- facts: u32,
- pseudo_styles: u64,
- environment: u64,
- font_environment_generation: u64,
- root_font_inputs: RootFontInputs,
- sibling_position: Option<SiblingPosition>,
-}
-
-#[derive(Clone, Copy)]
-pub(super) struct ColdRecordDonor {
- state: CascadeStateID,
- record: ColdRecord,
-}
-
-const MAXIMUM_COLD_RECORD_DONORS_PER_KEY: usize = 4;
-
-/// First records the engine keeps for reuse; cleared wholesale past this many entries.
-const COLD_RECORD_CACHE_LIMIT: usize = 4096;
-
-/// A record the engine derived for a published reaction, awaiting C++'s installation.
-#[derive(Clone)]
-pub(super) struct PendingEngineComputedRecord {
- node: StyleNodeID,
- /// The pseudo-element the record is for, or `u8::MAX` for the element's own.
- pseudo_kind: u8,
- old_style_record: computed::FinalStyleRecordID,
- new_style_record: computed::FinalStyleRecordID,
- /// What the element's record took the place of, which reverting it restores. None for a
- /// pseudo-element's record.
- replaced: Option<computed::ReplacedColumns>,
- /// The winner state the record was derived from; an implicit marker without rules has none.
- cascade_state: Option<(u64, CascadeStateID)>,
- /// Longhands the drive evaluated for the record; counted once C++ installs it.
- longhand_evaluations: u32,
- /// Whether the host owes the element the transition step once it installs the record: the
- /// record moves, and either the one it replaces declares transitions or the move changes the
- /// declarations.
- owes_a_transition_step: bool,
- /// The composition the element's animations laid over the record this one replaces, detached
- /// and pinned until C++ installs the record, computes one itself, or the derivation is reverted.
- detached_composition: Option<computed::DetachedComposition>,
-}
-
-/// What one flush accumulates while deriving engine-computed records: the record each cohort
-/// (an old record moved to a winner state) derived, and the cascade each winner state describes.
-/// Which of a parent's inputs to its children's records may have moved under a record.
-#[derive(Clone, Copy, Default)]
-pub(super) struct ParentInputsMoved {
- /// The parent's inherited style groups.
- pub(super) inherited_style: bool,
- /// The inherited groups named by the reaction, or zero where they are not known.
- pub(super) inherited_style_groups: u8,
- /// The parent's display, which the children's box-type transformation reads.
- pub(super) display: bool,
-}
-
-impl ParentInputsMoved {
- pub(super) fn any(self) -> bool {
- self.inherited_style || self.display
- }
-}
-
-/// Why a row's record is driven again in full, its pseudo-elements with it, while its winners
-/// stand: inputs no winner shows moved under it.
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub(super) enum FullDriveReason {
- /// A descendant recompute, for the root's font metrics or an ancestor's direction, writing
- /// mode or container type, or an ancestor leaving display:none, which cleared the element's
- /// style on the way in.
- AncestorChange,
- /// A `@function` the element calls, or a counter style its record or a pseudo-element's
- /// resolved, moved.
- NamedRuleContext,
- /// A face the element's font cascade names became available or failed, or the document's
- /// `@font-feature-values` moved.
- FontEnvironment,
- /// A container moved that the element's or a pseudo-element's values measure, through a
- /// container-relative length or a substitution.
- ContainerMoved,
- /// A style pass gave the row up, and with it what moved under the record that only the pass
- /// saw, such as the viewport.
- PassGivenUp,
-}
-
-/// What a declaration of `property` written as `value` reads beyond the cascade, as `cascade::STATE_READS_*` bits:
-/// what a longhand substitutes from beside its custom-property environment, and what its value reads of the element
-/// and its containers.
-pub(super) fn written_value_reads(property: u16, value: &crate::css::style_value::RetainedStyleValueData) -> u8 {
- use crate::css::style_value::StyleValueData;
- let mut reads = 0;
- if property >= crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID
- && matches!(
- value.data(),
- StyleValueData::Unresolved { .. } | StyleValueData::PendingSubstitution { .. }
- )
- {
- if custom_property_cascade::value_reads_attributes(value.data()) {
- reads |= cascade::STATE_READS_ATTRIBUTES;
+ )?;
+ if publication.slot_allocated {
+ self.retained.counters.bump(Counter::AnimationOverlaySlotsAllocated);
}
- if custom_property_cascade::value_reads_inherited_values(value.data()) {
- reads |= cascade::STATE_READS_INHERIT_FUNCTION;
+ if publication.slot_released {
+ self.retained.counters.bump(Counter::AnimationOverlaySlotsReleased);
}
- if custom_property_cascade::value_reads_conditions(value.data()) {
- reads |= cascade::STATE_READS_IF_FUNCTION;
+ if publication.record_updated {
+ self.retained.counters.bump(Counter::AnimationOverlayRecordsUpdated);
}
- if custom_property_cascade::value_calls_custom_functions(value.data()) {
- reads |= cascade::STATE_READS_CUSTOM_FUNCTION;
+ self.retained
+ .counters
+ .set(Counter::LiveAnimationOverlayRecords, publication.live_records as u64);
+ if let Some(held_composition) = held_composition {
+ self.note_composition_moved(target.node(), held_composition);
}
+ Some(publication)
}
- let dependencies = crate::css::style_compute::collect_external_value_dependencies(value.data());
- if dependencies.uses_tree_counting_function {
- reads |= cascade::STATE_READS_SIBLING_POSITION;
- }
- if dependencies.has_unfixed_random_sharing && value_draws_element_random_base(value.data()) {
- reads |= cascade::STATE_READS_ELEMENT_RANDOM_BASE;
- }
- if dependencies.container_relative_length_unit_mask != 0 {
- reads |= cascade::STATE_READS_CONTAINER_UNITS;
- }
- reads
-}
-
-/// Static checks attached to the original declaration spelling at input preparation.
-#[derive(Clone, Copy, PartialEq, Eq)]
-pub(super) struct WrittenValueChecks {
- whole_context_free: bool,
- longhand_context_free: Option<bool>,
}
-impl WrittenValueChecks {
- pub(super) fn prepare(property: u16, value: &crate::css::style_value::RetainedStyleValueData) -> Self {
- use crate::css::style_value::StyleValueData;
- let whole_context_free = value_computes_without_document_context(value.data());
- let longhand_context_free = match value.data() {
- StyleValueData::Unresolved { .. } | StyleValueData::PendingSubstitution { .. } => None,
- StyleValueData::Shorthand { .. } => Some(
- shorthand_longhand_value(property, value.data())
- .is_some_and(|value| value_computes_without_document_context(value.data())),
- ),
- _ => Some(whole_context_free),
- };
- Self {
- whole_context_free,
- longhand_context_free,
- }
- }
+/// The places of the element children of parents with many of them, as
+/// [`RetainedState::sibling_position`] counts them, at one version of the tree's DOM order.
+#[derive(Default)]
+pub(super) struct SiblingPositionCache {
+ dom_order_version: u64,
+ /// How many element children each parent counted has.
+ counts: super::fast_hash::FastMap<StyleNodeID, u32>,
+ /// The place of each counted child among its parent's element children, counted from one.
+ indices: super::fast_hash::FastMap<StyleNodeID, u32>,
}
-#[derive(Clone, Default)]
-pub(super) struct EngineComputabilityScratch {
- /// What a record computed from the state reads beside its winners, or `None` when the engine
- /// computes none from it.
- // NB: Equal winner states can have different per-node written declaration inputs.
- states: HashMap<(StyleNodeID, u64, CascadeStateID, u64, u64), Option<StateRecordReads>>,
-}
+impl SiblingPositionCache {
+ /// How many element children a parent has before their places are kept: fewer are counted again
+ /// as quickly as they are looked up.
+ const MIN_CHILDREN: usize = 32;
-impl EngineComputabilityScratch {
- fn remember(&mut self, key: (StyleNodeID, u64, CascadeStateID, u64, u64), admitted: Option<StateRecordReads>) {
- if self.states.len() >= COLD_RECORD_CACHE_LIMIT {
- self.states.clear();
+ /// Forgets the places counted at a version of the DOM order other than `dom_order_version`.
+ fn forget_unless_at(&mut self, dom_order_version: u64) {
+ if self.dom_order_version != dom_order_version {
+ self.counts.clear();
+ self.indices.clear();
+ self.dom_order_version = dom_order_version;
}
- self.states.insert(key, admitted);
- }
-}
-
-#[derive(Clone, Default)]
-pub(super) struct EngineComputedRecordScratch {
- pub(super) font_drive: drive::FontDriveScratch,
- /// Whether this flush carries a document environment change. A record's winners stand
- /// through one while the values they computed to may not, so such a record is driven again
- /// in full against the document's inputs rather than kept.
- pub(super) document_environment_moved: bool,
- /// Whether the viewport moved since the last flush drove records. A record holding a value
- /// resolved against it cannot stand, whatever its winners did.
- pub(super) viewport_moved: bool,
- /// Whether the row being derived had its selector answer or its declarations move this flush
- /// without its winners necessarily being published again.
- pub(super) answer_or_declarations_moved: bool,
- /// Whether the row's only reaction is that the element's pseudo-element inputs may have
- /// changed (a deferred ::selection becoming observable): its own record stands where its
- /// winners do.
- pub(super) pseudo_inputs_alone: bool,
- pub(super) prepared_root_font: Option<(StyleNodeID, ParentInputsMoved, drive::FontDriveScratch)>,
- // NB: Preserve the root's existing remaining-phase context after preparing consumer inputs.
- root_element_inputs: Option<(StyleNodeID, RootFontInputs)>,
- root_font_inputs_changed: bool,
- pending_element: Option<drive::PendingElement>,
- next_pseudo: usize,
- pseudo_uses_substitution: bool,
- /// What the element being derived noted about substituted winners, when its computation
- /// reached the point of deciding. A record that stands unchanged notes nothing.
- noted_substitution: Option<bool>,
- /// Whether the element derived last was computed with a substituted winner: what the flush
- /// publishes beside its record, decided by the step rather than read back out of the
- /// retained set.
- pub(super) element_uses_substitution: bool,
- /// The non-inherited style groups the element being derived read straight from its parent
- /// through an explicit `inherit`, and those its pseudo-elements read from it, which the row
- /// carries for C++ to mark the parent with.
- pub(super) element_explicitly_inherited_groups: u32,
- /// Whether the host applies the animation plan of a record this scratch derives once it has
- /// installed it: a style update's batch and its retries do, a record demand does not.
- pub(super) host_applies_animation_plans: bool,
- /// The elements whose rows this flush settled that the host composes once it installs their
- /// records: their animations, and those the records' plans start, sampled over them.
- nodes_composed_by_the_host: HashSet<StyleNodeID>,
- /// The nodes whose substituted-record fact the step decided, in the order it decided them.
- /// The boundary that installs the record applies them.
- substitution_effects: Vec<(StyleNodeID, bool)>,
- /// Warm records derived this flush, by what they were derived from, with the style groups
- /// they explicitly inherit and whether they read the element's place among its siblings.
- cohorts: HashMap<RecordCohortKey, (computed::FinalStyleRecordID, u32, bool)>,
- pub(super) inherited_group_swaps:
- HashMap<(computed::FinalStyleRecordID, computed::FinalStyleRecordID, u8), computed::FinalStyleRecordID>,
- computability: EngineComputabilityScratch,
- /// What each node the walk has reached tells its children: whether the chain above it is
- /// confined, and whether it resolved the record its children inherit from. A column with
- /// touched-page allocation, because the walk writes a row for every node it processes and
- /// reads one for every node's parent.
- pub(super) derived_child_inputs: column::PagedColumn<column::PagedValuePage<DerivedChildInputs>>,
- /// First records derived this flush, by what they were derived from.
- pub(super) cold_cohorts: HashMap<ColdRecordKey, ColdRecord>,
- pub(super) stores: HashMap<(CascadeStateID, u64), std::sync::Arc<WinnerStore>>,
- /// The states whose store, under an environment, substituted a custom property into a winner.
- pub(super) substituted_states: HashSet<(CascadeStateID, u64)>,
- /// Pseudo-element records derived this flush, by what they were derived from.
- pub(super) pseudo_cohorts: HashMap<PseudoCohortKey, computed::FinalStyleRecordID>,
- pub(super) pseudo_stores: HashMap<(u8, CascadeStateID, u64), std::sync::Arc<WinnerStore>>,
- /// The nodes whose custom-property environment this flush has brought up to date.
- current_custom_property_environments: HashMap<StyleNodeID, u64>,
- /// The pseudo-element records settled beside the element derived last.
- pub(super) pseudo_deltas: Vec<PseudoRecordDelta>,
- /// The custom-property environment of the pseudo-element a read settled without a box.
- pub(super) boxless_read_environment: u64,
- /// The pseudo-element rules that flipped for the element being derived.
- pub(super) flipped_pseudo_rules: u64,
- /// Whether the drive answers a read-only demand, which holds no leave to republish winners.
- read_only: bool,
-}
-
-/// What one node tells its flat-tree children, decided where the node settles and read by the
-/// children in the same pass: whether the node resolved the record its children inherit from, and
-/// the accumulated proof about the chain above it, so a child reads one row instead of walking to
-/// the document element for every gate it has to pass.
-#[derive(Clone, Copy, Default)]
-pub(super) struct DerivedChildInputs {
- /// Whether the node's record settled this flush: what its descendants inherit from is in place.
- pub(super) settled: bool,
- /// Whether the node is a row of this flush whose record the engine left to the host: the
- /// record, and the container inputs it publishes, are installed after the flush. A row the
- /// walk keeps only for its chain is no such row.
- pub(super) declined: bool,
- /// Whether the node is a row of this flush answered as hidden, in a display:none subtree, as
- /// is everything that inherits from it.
- pub(super) hidden: bool,
- /// Whether the node took an inherited-style reaction and resolved no record of its own, so
- /// its immediate children cannot take the direct inherited-group path. Deliberately separate
- /// from the chain proof: that is the accumulated confinement argument, this is the immediate
- /// parent's own unresolved fact.
- pub(super) inheritance_unresolved: bool,
- /// The proof about everything from this node upwards, folded on the first ask a child makes
- /// and kept for the asks after it.
- pub(super) chain: Option<AncestorChain>,
-}
-
-/// The published chain from one node to the root, as a child's gate reads it.
-#[derive(Clone, Copy)]
-pub(super) struct AncestorChain {
- /// Whether any published node from this one to the root publishes a change the engine cannot
- /// prove confined. Once an unsettled node sits below one of those, no descendant's record is
- /// exact.
- unconfined_above: bool,
- /// `None` when an unsettled gap sits below an unconfined published ancestor, and otherwise
- /// whether a child relies on an ancestor this flush settled.
- proof: Option<bool>,
-}
-
-impl AncestorChain {
- /// What the document element's parent says: nothing above it, and nothing unsettled.
- pub(super) const ROOT: Self = Self {
- unconfined_above: false,
- proof: Some(false),
- };
-
- /// The proof a child of this node needs.
- pub(super) fn ancestors_are_confined(self) -> Option<bool> {
- self.proof
}
- /// Fold one node onto what its parent says. `published` says the flush published a reaction
- /// for the node, `unconfined` that the published change may move something a descendant
- /// inherits, and `settled` that the node's record is in place.
- ///
- /// This is the upward walk written as a recurrence. The walk carries "something closer to the
- /// child is unsettled" downward and stops at the first unconfined published ancestor once it
- /// is set, which is exactly `unconfined_above` read from the unsettled node.
- pub(super) fn fold(parent: Self, published: bool, unconfined: bool, settled: bool) -> Self {
- let unconfined_here = published && unconfined;
- let proof = if unconfined_here && !settled {
- None
- } else if settled {
- parent.proof.map(|relied| unconfined_here || relied)
- } else if parent.unconfined_above {
- None
- } else {
- Some(unconfined_here)
- };
- Self {
- unconfined_above: unconfined_here || parent.unconfined_above,
- proof,
- }
+ fn position_of(&self, parent: StyleNodeID, node: StyleNodeID) -> Option<SiblingPosition> {
+ Some(SiblingPosition {
+ count: *self.counts.get(&parent)?,
+ index: *self.indices.get(&node)?,
+ })
}
-}
-
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-enum RecordDeltaParent {
- Exact(u64),
- Inputs(ColdRecordParent),
-}
-
-/// Which element and pseudo winner rows must reflect this update's exact rule flips.
-#[derive(Clone, Copy, Default)]
-pub(super) struct FlippedRules {
- element: bool,
- pseudos: u64,
-}
-impl FromIterator<Option<u16>> for FlippedRules {
- fn from_iter<T: IntoIterator<Item = Option<u16>>>(kinds: T) -> Self {
- let mut result = Self::default();
- for kind in kinds {
- match kind {
- None => result.element = true,
- Some(kind) => {
- // NB: Only the existing synthetic pseudo inventory consumes these bits.
- if let Some(bit) = 1_u64.checked_shl(u32::from(kind)) {
- result.pseudos |= bit;
- }
- }
- }
+ fn insert(&mut self, parent: StyleNodeID, children: &[StyleNodeID]) {
+ self.counts.insert(parent, children.len() as u32);
+ for (index, &child) in children.iter().enumerate() {
+ self.indices.insert(child, index as u32 + 1);
}
- result
- }
-}
-
-impl EngineComputedRecordScratch {
- /// Takes `node` as an element whose composition its children need not wait for: what the host composes over its
- /// record moves nothing they inherit.
- pub(super) fn forget_composed_by_the_host(&mut self, node: StyleNodeID) {
- self.nodes_composed_by_the_host.remove(&node);
}
}
-/// What a drive computes for: the node whose record it inherits from (the flat-tree parent, or
-/// the originating element of a pseudo-element) and the element facts the computation's
-/// adjustments read.
-#[derive(Clone, Copy)]
-pub(super) struct DriveSubject {
- /// What is being driven, element or pseudo-element. A drive that suspends to wait for a font
- /// names it, so the suspended drive can only be resumed by the one it belongs to.
- target: computed::ComputedStyleTarget,
- /// The flat-tree parent the element inherits from; the document element has none and
- /// inherits from the initial values.
- parent: Option<StyleNodeID>,
- facts: u32,
+/// Where an element stands among its element siblings, counted from one: what `sibling-count()`
+/// and `sibling-index()` read.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
+pub(super) struct SiblingPosition {
+ pub(super) count: u32,
+ pub(super) index: u32,
}
/// What a demand for an element's record settles: the record with the groups it explicitly
@@ -5130,52 +787,12 @@ pub(super) struct DriveSubject {
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct DemandedEngineRecord {
pub(crate) style_record: u64,
- pub(crate) explicitly_inherited_groups: u32,
- pub(crate) owes_an_animation_plan: bool,
- pub(crate) owes_a_transition_step: bool,
- pub(crate) composed_by_the_host: bool,
pub(crate) pseudo_records_present: u16,
pub(crate) pseudo_records: [u64; bridge::PSEUDO_RECORD_SLOTS],
}
const _: () = assert!(pseudo_kind::SYNTHETIC_COUNT == bridge::PSEUDO_RECORD_SLOTS);
-/// A pseudo-element record the engine settled beside its originating element's; a removal when
-/// the new record is none.
-#[derive(Clone, Copy)]
-pub(super) struct PseudoRecordDelta {
- pub(super) kind: u8,
- pub(super) old_style_record: computed::FinalStyleRecordID,
- pub(super) new_style_record: computed::FinalStyleRecordID,
-}
-
-/// What a pseudo-element record is derived from: the originating element's inherited style,
-/// display, dependency flags and custom-property environment (and its record, when the state
-/// inherits a non-inherited property from it), the pseudo-element's winner state and the
-/// element facts and font environment the drive reads.
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-pub(super) struct PseudoCohortKey {
- /// What the monospace font-size recascade gives the pseudo-element, as for an element's cohort.
- monospace_recascaded_font_size: i32,
- parent_record: u64,
- /// For a highlight pseudo-element, the record of the same pseudo-element of its nearest
- /// ancestor it inherits from.
- highlight_parent_record: u64,
- inherited_groups: u32,
- parent_blockifies: bool,
- dependency_flags: u8,
- environment: u64,
- kind: u8,
- generation: u64,
- state: Option<CascadeStateID>,
- facts: u32,
- font_environment_generation: u64,
- root_font_inputs: RootFontInputs,
- /// Where the originating element stands among its siblings, when the pseudo-element's winners
- /// read it.
- sibling_position: Option<SiblingPosition>,
-}
-
/// The synthetic pseudo-element kinds, as the C++ `PseudoElement` enumeration numbers them.
pub(super) mod pseudo_kind {
pub(in crate::css::style) const AFTER: u8 = 0;
@@ -5188,27 +805,7 @@ pub(super) mod pseudo_kind {
pub(in crate::css::style) const SEARCH_TEXT_CURRENT: u8 = 7;
pub(in crate::css::style) const SELECTION: u8 = 8;
pub(in crate::css::style) const SPELLING_ERROR: u8 = 9;
- pub(in crate::css::style) const VIEW_TRANSITION: u8 = 10;
pub(in crate::css::style) const SYNTHETIC_COUNT: usize = 11;
- /// Every kind, in the order a settlement goes through them: first the ones a style update
- /// settles, then the ones only a read asks for.
- pub(in crate::css::style) const SETTLEMENT_ORDER: [u8; SYNTHETIC_COUNT] = [
- BEFORE,
- AFTER,
- FIRST_LETTER,
- SELECTION,
- SEARCH_TEXT,
- SEARCH_TEXT_CURRENT,
- SPELLING_ERROR,
- BACKDROP,
- MARKER,
- FIRST_LINE,
- VIEW_TRANSITION,
- ];
- /// The kinds an element in the host's shadow tree backs, as a mask.
- pub(in crate::css::style) const ELEMENT_REFERENCE_KINDS: u64 =
- ((1 << (super::bridge::LAST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND + 1)) - 1)
- & !((1 << super::bridge::FIRST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND) - 1);
/// https://drafts.csswg.org/css-pseudo-4/#highlight-pseudos
pub(in crate::css::style) const fn is_highlight(kind: u8) -> bool {
@@ -5216,374 +813,30 @@ pub(super) mod pseudo_kind {
}
}
-/// The element facts a pseudo-element's computation reads: the C++ adjustments for what the
-/// originating element is stay off for its pseudo-elements, past the ones about its markup
-/// language.
-const PSEUDO_ELEMENT_ADJUSTMENT_FACTS: u32 = {
- use bridge::element_adjustment_fact as fact;
- fact::IS_MATHML
- | fact::IS_MATHML_MTABLE
- | fact::IS_MATHML_MTR
- | fact::IS_MATHML_MTD
- | fact::IS_TH
- | fact::HAS_ANIMATIONS
-};
-
-/// The value a shorthand value carries for one of its longhands, through nested shorthands.
-/// The `unset` keyword, which a declaration invalid at computed-value time computes as.
-fn unset_value() -> crate::css::style_value::RetainedStyleValueData {
- crate::css::style_value::RetainedStyleValueData::from_owned(crate::css::style_value::StyleValueData::Keyword {
- keyword: crate::css::style_compute::keyword::UNSET,
- })
-}
-
-fn invalid_as_unset(
- value: crate::css::style_value::RetainedStyleValueData,
-) -> crate::css::style_value::RetainedStyleValueData {
- match value.data() {
- crate::css::style_value::StyleValueData::GuaranteedInvalid => unset_value(),
- _ => value,
- }
-}
-
-/// The longhand's part of a substituted shorthand value, as the cascade expands it.
-fn expanded_longhand_value(
- shorthand: u16,
- property: u16,
- value: &crate::css::style_value::RetainedStyleValueData,
-) -> Option<crate::css::style_value::RetainedStyleValueData> {
- let mut found = None;
- crate::css::style_compute::expand_shorthands_with(shorthand, value, false, &mut |longhand, data, _| {
- if longhand == property && found.is_none() {
- found = Some(data.clone());
- }
- });
- found
-}
-
-fn shorthand_longhand_value(
- property: u16,
- data: &crate::css::style_value::StyleValueData,
-) -> Option<crate::css::style_value::RetainedStyleValueData> {
- let crate::css::style_value::StyleValueData::Shorthand {
- sub_properties, values, ..
- } = data
- else {
- return None;
- };
- for (&sub_property, sub_value) in sub_properties.as_slice().iter().zip(values.as_slice()) {
- if sub_property == property {
- return Some(sub_value.clone());
- }
- if let Some(found) = shorthand_longhand_value(property, sub_value.data()) {
- return Some(found);
- }
- }
- None
-}
-
-/// Whether a longhand computes in the drive's remaining phase: after the font, line-height and
-/// color-scheme stages, whose outputs the engine does not derive itself yet.
-fn property_computes_in_remaining_phase(property: u16) -> bool {
- use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LONGHAND_WORD_COUNT};
- use crate::css::style_compute::{LONGHAND_DRIVE_PHASE_REMAINING, property_computation_order_for_phase};
- static REMAINING: std::sync::OnceLock<[u64; LONGHAND_WORD_COUNT]> = std::sync::OnceLock::new();
- let words = REMAINING.get_or_init(|| {
- let mut words = [0_u64; LONGHAND_WORD_COUNT];
- for &property in property_computation_order_for_phase(LONGHAND_DRIVE_PHASE_REMAINING) {
- let index = usize::from(property - FIRST_LONGHAND_PROPERTY_ID);
- words[index / 64] |= 1 << (index % 64);
- }
- words
- });
- let Some(index) = property.checked_sub(FIRST_LONGHAND_PROPERTY_ID).map(usize::from) else {
- return false;
- };
- index / 64 < words.len() && words[index / 64] & (1 << (index % 64)) != 0
-}
-
-/// Whether a longhand is read by the box-type transformation, which rewrites the computed display.
-/// A `-webkit-box` becomes a block container while its `-webkit-box-orient` and `continue` say
-/// that `-webkit-line-clamp` applies to it.
-fn property_feeds_box_type_transformation(property: u16) -> bool {
- use crate::css::property_metadata::property_id as prop;
- matches!(
- property,
- prop::DISPLAY | prop::POSITION | prop::FLOAT | prop::_WEBKIT_BOX_ORIENT | prop::CONTINUE
- )
-}
-
-/// Whether a longhand's new value would start an animation or a transition in the C++
-/// computation, register anchor names there, or feed the counter-style environment identity it
-/// resolves.
-/// The longhands the drive's font resolution selects a font by, which its request carries.
-fn font_resolution_selects_by(property: u16) -> bool {
- use crate::css::property_metadata::property_id as prop;
- matches!(
- property,
- prop::FONT_FAMILY
- | prop::FONT_STYLE
- | prop::FONT_WEIGHT
- | prop::FONT_WIDTH
- | prop::FONT_OPTICAL_SIZING
- | prop::FONT_SIZE_ADJUST
- )
-}
-
-/// The computed style groups a moved longhand reaches. One the font group carries feeds no group of
-/// its own and reaches every value the font feeds, through the font group: a delta moving it is
-/// driven in full, as is one moving a longhand no registered group names.
-fn moved_longhand_groups(property: u16) -> u32 {
- use crate::css::computed_value_types::STYLE_GROUP_INDEX_FONT;
- match StyleGroupMasks::get().dependencies(property) {
- 0 if font_group_carries_longhand(property) => 1 << STYLE_GROUP_INDEX_FONT,
- 0 => (1 << crate::css::table_group_builder::group_index::COUNT) - 1,
- groups => groups,
- }
-}
-
-/// The font-phase longhands the font group carries without a group binding of their own.
-fn font_group_carries_longhand(property: u16) -> bool {
- use crate::css::property_metadata::property_id as prop;
- font_resolution_selects_by(property)
- || matches!(
- property,
- prop::FONT_FEATURE_SETTINGS
- | prop::FONT_KERNING
- | prop::FONT_LANGUAGE_OVERRIDE
- | prop::FONT_VARIANT_ALTERNATES
- | prop::FONT_VARIANT_CAPS
- | prop::FONT_VARIANT_EAST_ASIAN
- | prop::FONT_VARIANT_EMOJI
- | prop::FONT_VARIANT_LIGATURES
- | prop::FONT_VARIANT_NUMERIC
- | prop::FONT_VARIANT_POSITION
- | prop::FONT_VARIATION_SETTINGS
- | prop::MATH_DEPTH
- | prop::MATH_SHIFT
- | prop::MATH_STYLE
- | prop::TEXT_RENDERING
- )
-}
-
-/// What a winner store is built for: a drive reads the winners admission proved.
-#[derive(Clone, Copy, PartialEq, Eq)]
-enum StoreUse {
- Admission,
- Drive,
-}
-
-/// Whether the property is one of the `animation-*` longhands that declare an element's CSS
-/// animations, which the plan a record decides starts, retimes and cancels.
-fn property_declares_css_animations(property: u16) -> bool {
- use crate::css::property_metadata::property_id as prop;
- matches!(
- property,
- prop::ANIMATION_COMPOSITION
- | prop::ANIMATION_DELAY
- | prop::ANIMATION_DIRECTION
- | prop::ANIMATION_DURATION
- | prop::ANIMATION_FILL_MODE
- | prop::ANIMATION_ITERATION_COUNT
- | prop::ANIMATION_NAME
- | prop::ANIMATION_PLAY_STATE
- | prop::ANIMATION_RANGE_END
- | prop::ANIMATION_RANGE_START
- | prop::ANIMATION_TIMELINE
- | prop::ANIMATION_TIMING_FUNCTION
- )
-}
-
-/// Whether the property is one of the `transition-*` longhands that declare which changes of an
-/// element's values start transitions.
-fn property_declares_transitions(property: u16) -> bool {
- use crate::css::property_metadata::property_id as prop;
- matches!(
- property,
- prop::TRANSITION_BEHAVIOR
- | prop::TRANSITION_DELAY
- | prop::TRANSITION_DURATION
- | prop::TRANSITION_PROPERTY
- | prop::TRANSITION_TIMING_FUNCTION
- )
-}
-
-/// Whether a winner of the property keeps its record in C++, which starts animations and
-/// transitions from what it computes: a property of the animation group, and anything that is not a
-/// longhand.
-fn property_starts_animation(property: u16) -> bool {
- use crate::css::property_metadata::{
- FIRST_LONGHAND_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID, property_id as prop, property_style_group_index,
- };
- if !(FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID).contains(&property) {
- return true;
- }
- // A view transition name is a plain computed value; it starts nothing. So is a named timeline:
- // what finds it is an animation that names it in `animation-timeline`, which reads it from
- // whichever record the element holds when the animation starts.
- !matches!(
- property,
- prop::VIEW_TRANSITION_NAME
- | prop::SCROLL_TIMELINE_NAME
- | prop::SCROLL_TIMELINE_AXIS
- | prop::TIMELINE_SCOPE
- | prop::VIEW_TIMELINE_NAME
- | prop::VIEW_TIMELINE_AXIS
- | prop::VIEW_TIMELINE_INSET
- ) && property_style_group_index(property)
- .is_some_and(|group| usize::from(group) == crate::css::table_group_builder::group_index::ANIMATION)
-}
-
-/// Whether the drive holds what a value with these dependencies reads beyond the record, the
-/// parent and the document's computation inputs: the base URLs a `url()` resolves against when
-/// `resources_are_known`, the element's place among its siblings when the retained tree knows
-/// it, and for an element-keyed value, the random base values the store draws for it and the
-/// bases its container-relative lengths resolve against.
-fn drive_holds_value_inputs(
- dependencies: &crate::css::style_compute::ExternalValueDependencies,
- resources_are_known: bool,
- sibling_position_is_known: impl FnOnce() -> bool,
-) -> bool {
- (resources_are_known
- || (!dependencies.needs_document_base_url && !dependencies.may_need_style_sheet_resource_context))
- && (!dependencies.uses_tree_counting_function || sibling_position_is_known())
-}
-
-/// Whether a value resolves against the element itself: a `random()` it draws, or a
-/// container-relative length its query containers measure.
-fn value_resolves_against_the_element(dependencies: &crate::css::style_compute::ExternalValueDependencies) -> bool {
- dependencies.uses_random_function
- || dependencies.has_unfixed_random_sharing
- || dependencies.container_relative_length_unit_mask != 0
-}
-
-/// Whether a value holds a random function whose random caching key names the element.
-fn value_draws_element_random_base(value: &StyleValueData) -> bool {
- let mut sharings = Vec::new();
- crate::css::style_compute::collect_unfixed_random_sharings_in_value(value, &mut sharings);
- sharings.into_iter().any(|sharing| {
- // SAFETY: The value retains every sharing in it.
- !crate::css::style_compute::random_caching_key(unsafe { &*sharing }).1
- })
-}
-
-/// Whether a written value computes from the record, the parent and the document's computation
-/// inputs alone: no custom-property substitution, and none of the element or sheet facts the C++
-/// computation gathers per drive.
-fn value_computes_without_document_context(value: &StyleValueData) -> bool {
- // A longhand a shorthand written with a substitution declares holds a pending substitution
- // until the shorthand resolves.
- !matches!(
- value,
- StyleValueData::Unresolved { .. } | StyleValueData::PendingSubstitution { .. }
- ) && crate::css::style_compute::value_is_computationally_independent(value).is_some_and(|_| {
- let dependencies = crate::css::style_compute::external_value_dependencies(value);
- !value_resolves_against_the_element(&dependencies) && drive_holds_value_inputs(&dependencies, false, || false)
- })
-}
-
#[cfg(test)]
mod tests {
use super::*;
- #[test]
- fn cold_ancestor_refreshes_inheritance_without_losing_own_custom_properties() {
- use crate::css::custom_properties::CustomPropertyStore;
- use crate::css::style_value::RetainedStyleValueData;
- use std::sync::Arc;
-
- let inherited_name = ak::Utf16FlyString::from_utf16(&"--inherited".encode_utf16().collect::<Vec<_>>());
- let own_name = ak::Utf16FlyString::from_utf16(&"--own".encode_utf16().collect::<Vec<_>>());
- let make_store = |parent: Option<Arc<CustomPropertyStore>>, name: &ak::Utf16FlyString, value| {
- let value = RetainedStyleValueData::from_owned(StyleValueData::Number { value });
- // SAFETY: The parent is null or retained by this test, and both the name and value
- // remain live while cascaded_child retains them.
- unsafe {
- CustomPropertyStore::cascaded_child(parent, vec![(name.raw_identity(), false, value.pointer().cast())])
- }
- };
- let old_parent = make_store(None, &inherited_name, 1.0);
- let new_parent = make_store(None, &inherited_name, 2.0);
- let own = make_store(Some(old_parent.clone()), &own_name, 42.0);
- let mut engine = StyleEngine::new();
- let mut raw_nodes = [0; 3];
- engine.allocate_style_nodes(&mut raw_nodes);
- let [root, ancestor, inheritor] = raw_nodes.map(|node| StyleNodeID::from_raw(node).unwrap());
- engine.tree.set_parent(ancestor, Some(root));
- engine.tree.set_parent(inheritor, Some(root));
- for (identity, store) in [(1, &old_parent), (2, &new_parent), (3, &own)] {
- engine
- .retained
- .custom_property_environments
- .retain(identity, Some(store));
- }
- for (node, environment) in [(root, 1), (ancestor, 3), (inheritor, 1)] {
- engine.publish_computed_groups(
- computed::ComputedStyleTarget::new(node, u8::MAX),
- &[],
- 0,
- environment,
- computed::ComputedMetadataInput {
- pseudo_element_styles: 0,
- dependency_flags: 0,
- counter_style_environment_identity: 0,
- animation_overlay_identity: 0,
- animated_overlay: HostShared::null(),
- animation_overlay_payloads: &[],
- longhand_table: HostShared::null(),
- },
- );
- }
- let mut scratch = EngineComputedRecordScratch::default();
- scratch.current_custom_property_environments.insert(root, 2);
- let retained = &mut engine.retained;
- let current = retained
- .current_custom_property_environment(ancestor, &Default::default(), &mut scratch)
- .unwrap();
- let store = retained.custom_property_environments.store(current).unwrap();
- assert!(matches!(
- store.get(inherited_name.raw_identity()).unwrap().value.data(),
- StyleValueData::Number { value: 2.0 }
- ));
- assert!(matches!(
- store.get(own_name.raw_identity()).unwrap().value.data(),
- StyleValueData::Number { value: 42.0 }
- ));
- assert_eq!(
- retained.current_custom_property_environment(inheritor, &Default::default(), &mut scratch),
- Some(2)
- );
- }
-
#[test]
fn retained_highlight_inheritance_parent_uses_nearest_ancestor_pseudo_record() {
let mut engine = StyleEngine::new();
let mut raw_nodes = [0; 4];
engine.allocate_style_nodes(&mut raw_nodes);
let [root, parent, child, slot] = raw_nodes.map(|node| StyleNodeID::from_raw(node).unwrap());
- engine.tree.set_parent(parent, Some(root));
- engine.tree.set_parent(child, Some(parent));
- let retained = &mut engine.retained;
- retained.tree.set_assigned_slot(child, Some(slot));
- retained.tree.set_parent(slot, Some(root));
+ let projection = &mut engine.retained.projection;
+ projection.set_parent(parent, Some(root));
+ projection.set_parent(child, Some(parent));
+ projection.set_assigned_slot(child, Some(slot));
+ projection.set_parent(slot, Some(root));
+ projection.commit();
let publish = |engine: &mut StyleEngine, node, pseudo_kind| {
- engine
- .publish_computed_groups(
- computed::ComputedStyleTarget::new(node, pseudo_kind),
- &[],
- 0,
- 0,
- computed::ComputedMetadataInput {
- pseudo_element_styles: 0,
- dependency_flags: 0,
- counter_style_environment_identity: 0,
- animation_overlay_identity: 0,
- animated_overlay: HostShared::null(),
- animation_overlay_payloads: &[],
- longhand_table: HostShared::null(),
- },
- )
- .style_record_identity
+ engine.install_test_record(
+ computed::ComputedStyleTarget::new(node, pseudo_kind),
+ None,
+ None,
+ // NB: Told apart by node, so that each node's record is its own.
+ u64::from(node.raw()),
+ )
};
let root_record = publish(&mut engine, root, 0);
assert_eq!(
@@ -5600,455 +853,6 @@ mod tests {
Some(slot_record)
);
}
-
- #[test]
- fn pending_shorthand_lookup_returns_the_outermost_shorthand() {
- use crate::css::property_metadata::property_id;
- use crate::css::style_value::{RetainedStyleValueData, StyleValueData};
-
- let mut engine = StyleEngine::new();
- let sheet = engine.program.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);
- for (shorthand, nested_shorthand) in [
- (property_id::BACKGROUND, property_id::BACKGROUND_POSITION),
- (property_id::BORDER, property_id::BORDER_WIDTH),
- (property_id::FONT, property_id::FONT_VARIANT),
- ] {
- let rule = engine.program.append_rule(sheet, None, RuleKind::Style);
- let original = RetainedStyleValueData::from_owned(StyleValueData::Number { value: 1.0 });
- let pending = RetainedStyleValueData::from_owned(StyleValueData::PendingSubstitution {
- original_shorthand_value: original.clone_retained(),
- });
- let declared = |property| DeclaredProperty {
- property,
- important: false,
- operator: CascadeOperator::Declared,
- value: SpecifiedValueID(1),
- };
- engine.program.set_rule_declared_properties(
- rule,
- vec![declared(shorthand), declared(nested_shorthand)],
- vec![original.clone_retained(), pending.clone_retained()],
- vec![],
- vec![],
- );
- let (found_property, found_value) = engine
- .shorthand_declaration_written_as(StyleNodeID::element(1), WinnerSource::Rule(rule), pending.pointer())
- .unwrap();
- assert_eq!(found_property, shorthand);
- assert!(std::ptr::eq(found_value.pointer(), original.pointer()));
- }
- }
-
- #[test]
- fn computability_scratch_keeps_element_declaration_inputs_separate() {
- use crate::css::style_value::RetainedStyleValueData;
-
- let mut engine = StyleEngine::new();
- let mut raw_nodes = [0; 2];
- engine.allocate_style_nodes(&mut raw_nodes);
- let [first, second] = raw_nodes.map(|node| StyleNodeID::from_raw(node).unwrap());
- let declaration = DeclaredProperty {
- property: crate::css::property_metadata::property_id::OPACITY,
- important: false,
- operator: CascadeOperator::Declared,
- value: SpecifiedValueID(1),
- };
- let kind = ElementDeclarationKind::InlineStyle;
- let written = RetainedStyleValueData::from_owned(StyleValueData::Number { value: 0.5 });
- engine
- .facts
- .set_element_declared_properties(first, kind, vec![(declaration, written)]);
- // The second element declares nothing, so the winner names no declaration of its own.
- let winner = PropertyWinner {
- property: declaration.property,
- important: false,
- key: SpecifiedWinnerKey {
- value: declaration.value,
- operator: declaration.operator,
- continuation: cascade::CascadeContinuationID::default(),
- animation_relevance: 0,
- important: false,
- },
- priority: CascadePriority::exact_output_placeholder(),
- source: WinnerSource::Element(kind),
- };
- let state = engine.winner_groups.intern_sorted(&[winner], None);
- // Missing declaration inputs must not cache an answer that hides a later complete summary.
- assert!(engine.state_summary(second, state).has_unknown_values);
- assert!(engine.winner_groups.state_summary(state).is_none());
- let summary = engine.state_summary(first, state);
- assert!(!summary.has_unknown_values);
- assert!(!summary.has_substitutions);
- assert_eq!(engine.winner_groups.state_summary(state), Some(summary));
- let cascade_state = (0, state);
- for order in [[first, second], [second, first]] {
- let mut scratch = EngineComputabilityScratch::default();
- for node in order {
- assert_eq!(
- engine
- .computable_state_record_reads(node, cascade_state, &mut scratch)
- .is_some(),
- node == first,
- );
- }
- }
- }
-
- #[test]
- fn pending_records_acknowledge_and_rollback_independently_by_node() {
- let mut engine = StyleEngine::new();
- let mut raw_nodes = [0; 3];
- engine.allocate_style_nodes(&mut raw_nodes);
- let [first, second, third] = raw_nodes.map(|node| StyleNodeID::from_raw(node).unwrap());
- let mut scratch = EngineComputedRecordScratch::default();
- let publish = |engine: &mut StyleEngine, node, pseudo_kind| {
- let replaced = engine.computed_group_sets.replaced_columns(node);
- let record = engine
- .publish_computed_groups(
- computed::ComputedStyleTarget::new(node, pseudo_kind),
- &[],
- 0,
- 0,
- computed::ComputedMetadataInput {
- pseudo_element_styles: 0,
- dependency_flags: 0,
- counter_style_environment_identity: 0,
- animation_overlay_identity: 0,
- animated_overlay: HostShared::null(),
- animation_overlay_payloads: &[],
- longhand_table: HostShared::null(),
- },
- )
- .style_record_identity;
- engine
- .engine_computed_records_pending
- .entry(node)
- .or_default()
- .push(PendingEngineComputedRecord {
- node,
- pseudo_kind,
- old_style_record: computed::FinalStyleRecordID::NONE,
- new_style_record: record,
- replaced: (pseudo_kind == u8::MAX).then_some(replaced),
- cascade_state: None,
- longhand_evaluations: 1,
- owes_a_transition_step: false,
- detached_composition: None,
- });
- record
- };
- let first_record = publish(&mut engine, first, u8::MAX);
- publish(&mut engine, third, u8::MAX);
- let second_record = publish(&mut engine, second, u8::MAX);
- let first_pseudo = publish(&mut engine, first, 0);
- publish(&mut engine, third, 0);
-
- // Acknowledge out of publication order, including a repeated acknowledgement.
- engine.acknowledge_engine_computed_record(second);
- engine.acknowledge_engine_computed_record(second);
- assert_eq!(engine.counters.get(Counter::EngineComputedLonghandEvaluations), 1);
- engine.acknowledge_engine_computed_record(first);
- assert_eq!(engine.counters.get(Counter::EngineComputedLonghandEvaluations), 3);
-
- engine.abandon_engine_computed_record(third, &mut scratch);
- assert_eq!(engine.computed_group_sets.assigned_style_record(third), None);
- assert_eq!(engine.computed_group_sets.pseudo_style_record(third, 0), None);
- assert!(engine.engine_computed_records_pending.is_empty());
-
- // A later batch can use the same node, and discarding it leaves installed nodes alone.
- publish(&mut engine, third, u8::MAX);
- publish(&mut engine, third, 0);
- engine.discard_engine_computed_records();
- engine.acknowledge_engine_computed_record(third);
- assert!(engine.engine_computed_records_pending.is_empty());
- assert_eq!(engine.counters.get(Counter::EngineComputedLonghandEvaluations), 3);
- assert_eq!(engine.computed_group_sets.assigned_style_record(third), None);
- assert_eq!(engine.computed_group_sets.pseudo_style_record(third, 0), None);
- assert_eq!(
- engine.computed_group_sets.assigned_style_record(first),
- Some(first_record)
- );
- assert_eq!(
- engine.computed_group_sets.assigned_style_record(second),
- Some(second_record)
- );
- assert_eq!(
- engine.computed_group_sets.pseudo_style_record(first, 0),
- Some(first_pseudo)
- );
- }
-
- #[test]
- fn a_record_the_host_computes_instead_releases_the_detached_composition() {
- let mut engine = StyleEngine::new();
- let mut raw_node = [0];
- engine.allocate_style_nodes(&mut raw_node);
- let node = StyleNodeID::from_raw(raw_node[0]).unwrap();
- let target = computed::ComputedStyleTarget::new(node, u8::MAX);
- let animated_overlay = crate::css::animated_overlay::AnimatedOverlay::default();
- let composition = engine
- .publish_computed_groups(
- target,
- &[],
- 0,
- 0,
- computed::ComputedMetadataInput {
- pseudo_element_styles: 0,
- dependency_flags: 0,
- counter_style_environment_identity: 0,
- animation_overlay_identity: 1,
- animated_overlay: HostShared::new(std::ptr::from_ref(&animated_overlay)),
- animation_overlay_payloads: &[],
- longhand_table: HostShared::null(),
- },
- )
- .style_record_identity;
- let detached = engine.computed_group_sets.detach_composition(node);
- assert!(detached.is_some());
- assert!(
- engine
- .computed_group_sets
- .underlying_style_record(composition)
- .is_some()
- );
- engine
- .engine_computed_records_pending
- .entry(node)
- .or_default()
- .push(PendingEngineComputedRecord {
- node,
- pseudo_kind: u8::MAX,
- old_style_record: composition,
- new_style_record: computed::FinalStyleRecordID::NONE,
- replaced: None,
- cascade_state: None,
- longhand_evaluations: 0,
- owes_a_transition_step: true,
- detached_composition: detached,
- });
-
- engine.forget_engine_computed_record(target);
- assert!(engine.engine_computed_records_pending.is_empty());
- assert!(
- engine
- .computed_group_sets
- .underlying_style_record(composition)
- .is_none()
- );
- }
-
- #[test]
- fn a_pseudo_element_composition_detaches_and_reattaches() {
- let mut engine = StyleEngine::new();
- let mut raw_node = [0];
- engine.allocate_style_nodes(&mut raw_node);
- let node = StyleNodeID::from_raw(raw_node[0]).unwrap();
- let target = computed::ComputedStyleTarget::new(node, pseudo_kind::BEFORE);
- let animated_overlay = crate::css::animated_overlay::AnimatedOverlay::default();
- let metadata = |animated_overlay: HostShared<crate::css::animated_overlay::AnimatedOverlay>| {
- computed::ComputedMetadataInput {
- pseudo_element_styles: 0,
- dependency_flags: 0,
- counter_style_environment_identity: 0,
- animation_overlay_identity: u64::from(!animated_overlay.is_null()),
- animated_overlay,
- animation_overlay_payloads: &[],
- longhand_table: HostShared::null(),
- }
- };
- let composition = engine
- .publish_computed_groups(
- target,
- &[],
- 0,
- 0,
- metadata(HostShared::new(std::ptr::from_ref(&animated_overlay))),
- )
- .style_record_identity;
-
- // A record settled beneath the composition takes its place, while the composition stays
- // live for the host that holds it.
- let detached = engine.computed_group_sets.detach_composition_of(target).unwrap();
- let settled = engine
- .publish_computed_groups(target, &[], 0, 0, metadata(HostShared::null()))
- .style_record_identity;
- assert_eq!(settled, detached.base);
- assert!(
- engine
- .computed_group_sets
- .underlying_style_record(composition)
- .is_some()
- );
-
- // The host never installed it: the composition is laid over the pseudo-element's record
- // again.
- engine.computed_group_sets.reattach_composition_of(target, detached);
- assert_eq!(
- engine
- .computed_group_sets
- .pseudo_style_record(node, pseudo_kind::BEFORE),
- Some(composition)
- );
- }
-
- #[test]
- fn an_animation_sampled_beneath_a_pending_derivation_composes_over_the_installed_record() {
- let mut engine = StyleEngine::new();
- let mut raw_node = [0];
- engine.allocate_style_nodes(&mut raw_node);
- let node = StyleNodeID::from_raw(raw_node[0]).unwrap();
- let target = computed::ComputedStyleTarget::new(node, u8::MAX);
- let animated_overlay = crate::css::animated_overlay::AnimatedOverlay::default();
- let overlay = HostShared::new(std::ptr::from_ref(&animated_overlay));
- let metadata =
- |counter_style_environment_identity, animated_overlay: HostShared<_>| computed::ComputedMetadataInput {
- pseudo_element_styles: 0,
- dependency_flags: 0,
- counter_style_environment_identity,
- animation_overlay_identity: u64::from(!animated_overlay.is_null()),
- animated_overlay,
- animation_overlay_payloads: &[],
- longhand_table: HostShared::null(),
- };
- let installed = engine
- .publish_computed_groups(target, &[], 0, 0, metadata(1, overlay))
- .style_record_identity;
- let installed_base = engine.computed_group_sets.underlying_style_record(installed).unwrap();
- let derive = |engine: &mut StyleEngine, old_style_record| {
- let detached_composition = engine.computed_group_sets.detach_composition(node);
- let replaced = engine.computed_group_sets.replaced_columns(node);
- let derived = engine
- .publish_computed_groups(target, &[], 0, 0, metadata(2, HostShared::null()))
- .style_record_identity;
- engine
- .engine_computed_records_pending
- .entry(node)
- .or_default()
- .push(PendingEngineComputedRecord {
- node,
- pseudo_kind: u8::MAX,
- old_style_record,
- new_style_record: derived,
- replaced: Some(replaced),
- cascade_state: None,
- longhand_evaluations: 0,
- owes_a_transition_step: false,
- detached_composition,
- });
- derived
- };
- let derived = derive(&mut engine, installed);
-
- let sampled = engine
- .publish_animation_overlay_impl(target, installed, 2, overlay, &[])
- .unwrap()
- .style_record;
- assert_eq!(
- engine.computed_group_sets.underlying_style_record(sampled),
- Some(installed_base)
- );
- assert_eq!(engine.computed_group_sets.assigned_style_record(node), Some(derived));
-
- engine.discard_engine_computed_records();
- assert_eq!(engine.computed_group_sets.assigned_style_record(node), Some(sampled));
-
- let derived = derive(&mut engine, sampled);
- let cancelled = engine
- .publish_animation_overlay_impl(target, sampled, 0, HostShared::null(), &[])
- .unwrap()
- .style_record;
- assert_eq!(cancelled, installed_base);
- assert_eq!(engine.computed_group_sets.assigned_style_record(node), Some(derived));
- assert!(engine.computed_group_sets.underlying_style_record(sampled).is_none());
- }
-
- #[test]
- fn animations_sampled_beneath_a_derivation_of_the_installed_base_survive_its_discard() {
- let animated_overlay = crate::css::animated_overlay::AnimatedOverlay::default();
- let overlay = HostShared::new(std::ptr::from_ref(&animated_overlay));
- let metadata = |animated_overlay: HostShared<_>| computed::ComputedMetadataInput {
- pseudo_element_styles: 0,
- dependency_flags: 0,
- counter_style_environment_identity: 0,
- animation_overlay_identity: u64::from(!animated_overlay.is_null()),
- animated_overlay,
- animation_overlay_payloads: &[],
- longhand_table: HostShared::null(),
- };
- let derive_installed_base = |source_identities: &[u64]| {
- let mut engine = StyleEngine::new();
- let mut raw_node = [0];
- engine.allocate_style_nodes(&mut raw_node);
- let node = StyleNodeID::from_raw(raw_node[0]).unwrap();
- let target = computed::ComputedStyleTarget::new(node, u8::MAX);
- let installed = engine
- .publish_computed_groups(target, &[], 0, 0, metadata(overlay))
- .style_record_identity;
- let detached_composition = engine.computed_group_sets.detach_composition(node);
- let replaced = engine.computed_group_sets.replaced_columns(node);
- let derived = engine
- .publish_computed_groups(target, &[], 0, 0, metadata(HostShared::null()))
- .style_record_identity;
- assert_eq!(
- engine.computed_group_sets.underlying_style_record(installed),
- Some(derived)
- );
- engine
- .engine_computed_records_pending
- .entry(node)
- .or_default()
- .push(PendingEngineComputedRecord {
- node,
- pseudo_kind: u8::MAX,
- old_style_record: installed,
- new_style_record: derived,
- replaced: Some(replaced),
- cascade_state: None,
- longhand_evaluations: 0,
- owes_a_transition_step: false,
- detached_composition,
- });
- let mut sampled = installed;
- for &source_identity in source_identities {
- let animated_overlay = if source_identity == 0 {
- HostShared::null()
- } else {
- overlay
- };
- sampled = engine
- .publish_animation_overlay_impl(target, sampled, source_identity, animated_overlay, &[])
- .unwrap()
- .style_record;
- }
- (engine, node, derived, sampled)
- };
-
- for source_identities in [&[2][..], &[1], &[0], &[0, 2], &[2, 0, 3]] {
- let (mut engine, node, _, sampled) = derive_installed_base(source_identities);
- engine.discard_engine_computed_records();
- assert_eq!(engine.computed_group_sets.assigned_style_record(node), Some(sampled));
- assert_eq!(
- engine.computed_group_sets.live_animation_overlay_records(),
- usize::from(source_identities.last() != Some(&0))
- );
- engine.computed_group_sets.remove(node);
- assert_eq!(engine.computed_group_sets.live_animation_overlay_records(), 0);
- }
-
- let (mut engine, node, derived, _) = derive_installed_base(&[0, 2]);
- engine.acknowledge_engine_computed_record(node);
- let target = computed::ComputedStyleTarget::new(node, u8::MAX);
- let sampled = engine
- .publish_animation_overlay_impl(target, derived, 3, overlay, &[])
- .unwrap()
- .style_record;
- assert_eq!(
- engine.computed_group_sets.underlying_style_record(sampled),
- Some(derived)
- );
- assert_eq!(engine.computed_group_sets.assigned_style_record(node), Some(sampled));
- assert_eq!(engine.computed_group_sets.live_animation_overlay_records(), 1);
- }
}
impl StyleEngine {
@@ -6064,101 +868,34 @@ impl StyleEngine {
impl StyleEngine {
pub(super) fn refill_font_request(&mut self, node: StyleNodeID, request: font_resolution::FontRequest) {
- self.retained.counters.bump(Counter::FontRefillRounds);
- self.retained.counters.bump(Counter::FontResolutionRequests);
- // NB: Use resident selector-tree depth for this diagnostic. It is not a flat-tree
- // dependency-span proof and must not buy an ancestor traversal just for counting.
- self.retained.counters.set(
+ let resolver = self.host.font_resolver.as_ref().expect("a request has a font resolver");
+ self.retained.refill_font_request(resolver, node, request);
+ }
+}
+
+impl RetainedState {
+ /// Resolve `request` through `resolver` into the font resolution cache, between passes or the
+ /// rounds of one, on the thread that runs them.
+ pub(super) fn refill_font_request(
+ &mut self,
+ resolver: &font_resolution::FontResolverHost,
+ node: StyleNodeID,
+ request: font_resolution::FontRequest,
+ ) {
+ self.counters.bump(Counter::FontRefillRounds);
+ self.counters.bump(Counter::FontResolutionRequests);
+ // NB: Use the selector-tree depth for this diagnostic. It is not a flat-tree dependency-span proof. A refill
+ // round is rare, so its walk of the ancestors is not on any hot path.
+ self.counters.set(
Counter::FontRefillBlockedDepth,
- self.retained
- .counters
+ self.counters
.get(Counter::FontRefillBlockedDepth)
- .max(u64::from(self.tree.depth(node)) + 1),
+ .max(u64::from(self.element_depth(node)) + 1),
);
- let resolver = self.host.font_resolver.as_ref().expect("a request has a font resolver");
let resolutions = self
- .retained
.font_resolution
.as_mut()
.expect("a request has a font resolution cache");
resolver.refill(resolutions, request);
}
}
-
-impl StyleEngine {
- /// Establish the document element's font input before the consumer pass. The root's
- /// remaining properties and pseudos complete in their normal canonical position.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn prepare_root_font_inputs(
- &mut self,
- node: StyleNodeID,
- cascade_winners_are_complete: bool,
- exact_flipped_rules: Option<FlippedRules>,
- parent_inputs_moved: ParentInputsMoved,
- full_drive_reason: Option<FullDriveReason>,
- scratch: &mut EngineComputedRecordScratch,
- ) {
- let inputs = self.document_style_computation_inputs;
- scratch.root_element_inputs = Some((node, RootFontInputs::from_document(&inputs)));
- let probe = |state: &mut Self, scratch: &mut EngineComputedRecordScratch| {
- state.engine_computed_element_record_delta(
- node,
- cascade_winners_are_complete,
- exact_flipped_rules,
- parent_inputs_moved,
- full_drive_reason,
- scratch,
- FontDriveGoal::RootInputs,
- )
- };
- let mut answer = probe(self, scratch);
- if let Err(Unanswered::Suspended(Suspension::Font)) = answer {
- // NB: A root font miss completes at this preparation boundary. Consumers need
- // current metrics even when their first records install in this same pass.
- let request = scratch.font_drive.take_suspended_request();
- self.refill_font_request(node, request);
- answer = probe(self, scratch);
- }
- // An unproven or refused probe keeps the host's root-metric route.
- let prepared = match answer {
- Ok(ElementAnswer::RootInputs(prepared)) => prepared,
- Ok(ElementAnswer::Delta(_)) | Err(_) => None,
- };
- if let Some(root_inputs) = prepared {
- scratch.root_font_inputs_changed = RootFontInputs::from_document(&inputs) != root_inputs;
- root_inputs.apply_to(&mut self.document_style_computation_inputs);
- self.retained.counters.bump(Counter::RootFontInputsPrepared);
- } else {
- // NB: Preserve the current host root-metric route. Unproven font inputs do not
- // make every descendant wait for the host.
- self.retained.counters.bump(Counter::RootFontInputsUnprovenFallbacks);
- }
- if scratch.font_drive.is_pending_for(node) {
- scratch.prepared_root_font = Some((node, parent_inputs_moved, std::mem::take(&mut scratch.font_drive)));
- }
- self.apply_substitution_effects(scratch);
- }
-}
-
-impl EngineComputedRecordScratch {
- /// The scratch of the next wave of a style pass, which drives its rows under what the pass
- /// moved under every row. What it cached of the rows the host installed since is gone.
- pub(super) fn for_next_wave(&self) -> Self {
- Self {
- document_environment_moved: self.document_environment_moved,
- viewport_moved: self.viewport_moved,
- root_font_inputs_changed: self.root_font_inputs_changed,
- host_applies_animation_plans: true,
- ..Self::default()
- }
- }
-}
-
-/// A walk's scratch is movable to the worker that owns it for the length of that walk, and comes
-/// back at the join. Nothing in it is shared while the walk runs, so `Send` is the whole bound:
-/// the values a half-built record carries are borrowed through `HostShared`, and a frozen
-/// `ComputedLonghandTable` fills its lazy memos atomically.
-const _: () = {
- const fn assert_send<T: Send>() {}
- assert_send::<EngineComputedRecordScratch>();
-};
diff --git a/Libraries/LibWeb/Rust/src/css/style/reaction_application.rs b/Libraries/LibWeb/Rust/src/css/style/reaction_application.rs
index 0a0c9b1105f..6bbc2799e86 100644
--- a/Libraries/LibWeb/Rust/src/css/style/reaction_application.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/reaction_application.rs
@@ -4,29 +4,17 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! Applying the reactions of a style transaction to the elements they name.
+//! Applying the reactions of a style update to the elements they name.
//!
-//! The engine decides what each reaction installs: the record it settled, a record it demands now, or nothing, where
-//! it refuses the reaction. The host installs a record on its element, runs the element's animations and transitions,
+//! The engine decides what each reaction installs: the record it settled, or a record it demands now. The host installs a record on its element, runs the element's animations and transitions,
//! invalidates its layout, and reports what the installation did, from which the engine derives the reactions of the
//! element's children.
use super::StyleNodeID;
-use super::boundary::StyleChange;
-use super::bridge::{
- FfiEngineComputedRecord, FfiRecordDemand, FfiStyleDelta, FfiStyleDeltaDamage, FfiStyleDeltaGap,
- FfiStyleInvalidationField, PSEUDO_RECORD_SLOTS, close_style_reactions_over_inheritance,
- sort_style_deltas_for_direct_application,
-};
-use super::engine_calls::{
- absorb_element_style_input, has_deferred_element_style_input, note_bound_failure_trace, with_engine,
-};
-use super::publication::RecordDemand;
-use super::transaction::{
- STYLE_REACTION_ANCESTOR_BECAME_VISIBLE, STYLE_REACTION_INHERITED_CUSTOM_PROPERTIES, STYLE_REACTION_INHERITED_STYLE,
- STYLE_REACTION_PUBLISHED_STYLE, STYLE_REACTION_RECOMPUTE_DESCENDANT_STYLES, STYLE_REACTION_RECOMPUTE_STYLE,
-};
-use crate::render_state::{ArenaChange, BegunRead, DocumentHost};
+use super::engine_calls::{has_deferred_element_style_input, with_engine};
+use super::pipeline::install::{StyleInstallation, StyleSwap};
+use super::pipeline::main_effects::InstalledElementEffects;
+use crate::render_state::{BegunRead, DocumentHost};
/// A `Web::DOM::Element`, which Rust names by pointer only.
#[repr(C)]
@@ -54,20 +42,6 @@ impl HostElementPtr {
}
}
-/// The custom-property environment an engine-computed record was published with, as it stands to the one the element
-/// inherits now.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[repr(u8)]
-#[expect(dead_code, reason = "C++ constructs the variants")]
-pub enum FfiRecordEnvironment {
- /// The engine resolved no environment for the record over the one the element inherits.
- Uninstallable = 0,
- /// The environment the element inherits.
- Inherited = 1,
- /// An environment the engine resolved over the one the element inherits.
- ResolvedOverInherited = 2,
-}
-
/// The element a style node names, as the host holds it while it applies a reaction to it.
#[derive(Clone, Copy)]
#[repr(C)]
@@ -79,8 +53,6 @@ pub struct FfiReactionElement {
pub connected: bool,
pub has_style: bool,
pub style_record: u64,
- /// Whether the element's style reads its custom-property environment through `var()` or `inherit()`.
- pub reads_environment: bool,
/// Whether the style the element holds has display:none.
pub display_none: bool,
}
@@ -115,44 +87,6 @@ pub enum FfiTargetedStyleAnswer {
NeedsStyleUpdate,
}
-/// What a targeted update of an element in an inheritance chain did, for the elements below it.
-#[derive(Clone, Copy, Default)]
-#[repr(C)]
-pub struct FfiTargetedStyleReaction {
- /// The update moved what the element's descendants inherit or how their boxes are built.
- pub descendants_need_recompute: bool,
- /// The update asks for the element's descendants to compute their styles again.
- pub recompute_descendant_styles: bool,
-}
-
-/// What moving a pseudo-element from one record to another damages, where the engine answered it.
-#[derive(Clone, Copy, Default)]
-#[repr(C)]
-pub struct FfiPseudoRecordDamage {
- pub old_style_record: u64,
- pub new_style_record: u64,
- /// An `FfiStyleInvalidationField` word with `EngineComputed` set, or zero where the engine answered nothing.
- pub damage: u32,
-}
-
-/// A record the host installs on an element, as one the engine computed, with the pseudo-element records beside it.
-#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct FfiRecordInstallation {
- /// The element's reaction, holding the record and what it says about the installation.
- pub delta: FfiStyleDelta,
- /// Whether the host acknowledges the record to the engine once it holds it.
- pub acknowledge: bool,
- /// What moving the element from the reaction's old record to its new one damages, where the engine answered it: an
- /// `FfiStyleInvalidationField` word with `EngineComputed` set, or zero.
- pub damage: u32,
- /// The synthetic pseudo-element kinds whose records install beside the element's, as a bit per kind; a present
- /// slot holding zero is a removal.
- pub pseudo_records_present: u16,
- pub pseudo_records: [u64; PSEUDO_RECORD_SLOTS],
- pub pseudo_damages: [FfiPseudoRecordDamage; PSEUDO_RECORD_SLOTS],
-}
-
/// What the reaction passes of a style update did, for the host's counters.
#[derive(Clone, Copy, Default)]
#[repr(C)]
@@ -162,75 +96,28 @@ pub struct FfiStyleReactionCounts {
pub batch_runs: u32,
pub reaction_elements: u32,
pub published_reactions: u32,
- pub materialized_gaps: u32,
- pub record_deltas_applied: u32,
pub pass_guard_hits: u32,
pub apply_microseconds: u64,
}
-/// A style transaction the host took, whose reactions live until the host takes the next one.
-#[derive(Clone, Copy)]
-#[repr(C)]
-pub struct FfiTakenStyleTransaction {
- pub reactions: *const FfiStyleDelta,
- pub count: usize,
- pub scoped: bool,
- /// The transaction holds nothing but the child reactions the engine derived from the reactions the host applied
- /// last: one more generation of the same style change, not a new one.
- pub only_derived_child_reactions: bool,
- /// The elements connected to the document as the transaction was taken.
- pub connected_element_count: u32,
-}
-
unsafe extern "C" {
- fn web_css_republish_moved_environment(
- application: *mut HostStyleReactionApplication,
- node: u32,
- style_record: u64,
- replaced: u64,
- new_inheritable: *const std::ffi::c_void,
- );
- fn web_css_rebuild_custom_property_environment(
- application: *mut HostStyleReactionApplication,
- node: u32,
- new_inheritable: *const std::ffi::c_void,
- );
fn web_css_style_inheritance_parent(
application: *mut HostStyleReactionApplication,
element: *mut HostElement,
) -> FfiReactionElement;
- fn web_css_apply_targeted_style_reaction(
- application: *mut HostStyleReactionApplication,
- element: *mut HostElement,
- installation: *const FfiRecordInstallation,
- descendant_style_recompute_needed: bool,
- ) -> FfiTargetedStyleReaction;
- fn web_css_take_style_transaction(
- application: *mut HostStyleReactionApplication,
- flown: bool,
- ) -> FfiTakenStyleTransaction;
- fn web_css_has_pending_style_transaction(application: *mut HostStyleReactionApplication) -> bool;
+ fn web_css_run_style_update(application: *mut HostStyleReactionApplication, flown: bool);
+ fn web_css_has_pending_style_update(application: *mut HostStyleReactionApplication) -> bool;
fn web_css_note_style_update_has_reactions(application: *mut HostStyleReactionApplication);
fn web_css_sample_animations_for_style_update(application: *mut HostStyleReactionApplication);
fn web_css_begin_style_update_pass(application: *mut HostStyleReactionApplication, first: bool);
fn web_css_style_reaction_element(application: *mut HostStyleReactionApplication, node: u32) -> FfiReactionElement;
- fn web_css_parent_style_has_animated_values(element: *mut HostElement) -> bool;
- fn web_css_engine_record_environment(
+ fn web_css_install_styles(
application: *mut HostStyleReactionApplication,
- element: *mut HostElement,
- style_record: u64,
- ) -> FfiRecordEnvironment;
- fn web_css_record_derived_element_style_input(
- application: *mut HostStyleReactionApplication,
- node: u32,
- reaction: u8,
- groups: u8,
- );
- fn web_css_apply_style_reaction(
- application: *mut HostStyleReactionApplication,
- element: *mut HostElement,
- reaction: u8,
- installation: *const FfiRecordInstallation,
+ swaps: *const StyleSwap,
+ swap_count: usize,
+ effects: *const InstalledElementEffects,
+ effect_count: usize,
+ document_damage: u32,
);
}
@@ -248,353 +135,20 @@ impl Application<'_> {
unsafe { web_css_style_reaction_element(self.host_application, node) }
}
- fn record_environment_is_installable(
- self,
- element: &FfiReactionElement,
- node: StyleNodeID,
- style_record: u64,
- ) -> bool {
- // SAFETY: As above, and the element is live while its reaction is applied.
- let environment =
- unsafe { web_css_engine_record_environment(self.host_application, element.element.0, style_record) };
- match environment {
- FfiRecordEnvironment::Uninstallable => false,
- FfiRecordEnvironment::Inherited => true,
- // Only an element whose cascade declares custom properties holds an environment the engine resolved over
- // the one it inherits. An element declaring none holds exactly what it inherits: its record was resolved
- // over the parent's environment before an earlier reaction of the batch moved it.
- FfiRecordEnvironment::ResolvedOverInherited => with_engine(self.read, self.host, |engine| {
- engine.node_declares_custom_properties(node)
- }),
- }
- }
-
- fn apply(self, element: &FfiReactionElement, reaction: u8, installation: Option<&FfiRecordInstallation>) {
- let installation = installation.map_or(std::ptr::null(), std::ptr::from_ref);
- // SAFETY: As above.
- unsafe { web_css_apply_style_reaction(self.host_application, element.element.0, reaction, installation) };
- }
-
- /// The engine's answer to a targeted demand for the element's record, where the host can install it. The engine
- /// resolved the record's environment over the parent's own; where the parent's inheritable environment differs,
- /// it takes back what the demand derived.
- fn answer_record_demand(self, element: &FfiReactionElement, node: StyleNodeID) -> Option<FfiEngineComputedRecord> {
- let demand = RecordDemand::Element(FfiRecordDemand::TargetedElement);
- let mut refusal = None;
- let answer = with_engine(self.read, self.host, |engine| {
- let answer = engine.answer_record_demand(node, demand);
- if let Err(unanswered) = &answer {
- refusal = Some(*unanswered);
- }
- super::bridge::ffi_record_demand_answer(engine, node, demand.is_read_only(), answer)
- })
- .record;
- if let Some(unanswered) = refusal {
- note_bound_failure_trace(self.host, || format!("unanswered:{unanswered:?}"));
- }
- if answer.style_record == 0 {
- note_bound_failure_trace(self.host, || "demand:none".to_string());
- return None;
- }
- if !self.record_environment_is_installable(element, node, answer.style_record) {
- note_bound_failure_trace(self.host, || format!("demand:uninstallable:{}", answer.style_record));
- self.host
- .queue_change(ArenaChange::Style(StyleChange::AbandonDemandedRecords {
- node: Some(node),
- }));
- return None;
- }
- note_bound_failure_trace(self.host, || format!("demand:record:{}", answer.style_record));
- Some(answer)
- }
-
- /// The engine declined the reaction. Nothing else computes styles: the element keeps the record it holds. The
- /// engine answers no demand below an ancestor that owes a style input, such as one whose custom-property animations
- /// published new values as an earlier reaction of the batch installed its record. That ancestor's style moves in
- /// the next transaction, so the reaction is owed to it too, which orders it after the ancestor's.
- fn refuse(self, node: StyleNodeID, reaction: u8, inherited_style_groups: u8) {
- let ancestor_owes_style_input = with_engine(self.read, self.host, |engine| {
- std::iter::successors(engine.retained.tree.inheritance_parent(node), |&ancestor| {
- engine.retained.tree.inheritance_parent(ancestor)
- })
- .any(|ancestor| engine.has_deferred_element_style_input(ancestor))
- });
- note_bound_failure_trace(self.host, || {
- format!(
- "refuse:{}",
- if ancestor_owes_style_input {
- "ancestor-owes"
- } else {
- "consume"
- }
- )
- });
- if ancestor_owes_style_input {
- // SAFETY: The host lends its application for the call that applies the batch.
- unsafe {
- web_css_record_derived_element_style_input(
- self.host_application,
- node.raw(),
- reaction,
- inherited_style_groups,
- );
- }
- return;
- }
- self.host
- .queue_change(ArenaChange::Style(StyleChange::ConsumeElementStyleInput {
- node: Some(node),
- }));
- }
-
- /// A reaction the engine did not settle in its transaction, or a targeted update: the record the engine demands
- /// for the element now, which installs as one the engine computed, moving the element from the record it holds. A
- /// refused demand refuses the reaction.
- fn demand(
- self,
- element: &FfiReactionElement,
- node: StyleNodeID,
- reaction: u8,
- inherited_style_groups: u8,
- ) -> Option<FfiRecordInstallation> {
- let Some(answer) = self.answer_record_demand(element, node) else {
- self.refuse(node, reaction, inherited_style_groups);
- return None;
- };
- let mut delta = FfiStyleDelta::unsettled(node, 0);
- delta.old_style_record = element.style_record;
- let mut installation = FfiRecordInstallation::new(delta, true);
- installation.settle(&answer);
- Some(installation)
- }
-}
-
-impl FfiStyleDelta {
- /// Leaves the reaction to the host to answer from the element's record demand.
- fn unsettle(&mut self) {
- self.gap = FfiStyleDeltaGap::Materialize;
- self.new_style_record = 0;
- self.damage = FfiStyleDeltaDamage::None;
- }
-
- /// What moving to the reaction's record damages, where the engine answered it.
- fn answered_damage(&self) -> u32 {
- if self.record_damage & FfiStyleInvalidationField::EngineComputed as u32 != 0 {
- self.record_damage
- } else {
- 0
- }
- }
-}
-
-impl FfiRecordInstallation {
- fn new(delta: FfiStyleDelta, acknowledge: bool) -> Self {
- Self {
- damage: delta.answered_damage(),
- delta,
- acknowledge,
- pseudo_records_present: 0,
- pseudo_records: [0; PSEUDO_RECORD_SLOTS],
- pseudo_damages: [FfiPseudoRecordDamage::default(); PSEUDO_RECORD_SLOTS],
- }
- }
-
- /// Installs the record the engine settled for the reaction by a demand, with the pseudo-element records it settled
- /// beside it.
- fn settle(&mut self, record: &FfiEngineComputedRecord) {
- let delta = &mut self.delta;
- delta.new_style_record = record.style_record;
- delta.uses_substitution = record.uses_substitution;
- delta.record_reads = record.record_reads;
- delta.explicitly_inherited_groups = record.explicitly_inherited_groups;
- delta.owes_an_animation_plan = record.owes_an_animation_plan;
- delta.owes_a_transition_step = record.owes_a_transition_step;
- delta.composed_by_the_host = record.composed_by_the_host;
- delta.damage = FfiStyleDeltaDamage::Full;
- delta.gap = FfiStyleDeltaGap::Computed;
- delta.record_damage = 0;
- self.damage = 0;
- self.pseudo_records_present = record.pseudo_records_present;
- self.pseudo_records = record.pseudo_records;
- }
-
- /// Installs the record of a pseudo-element reaction the batch published beside the element's.
- fn add_pseudo_element_delta(&mut self, delta: &FfiStyleDelta) {
- let kind = usize::from(delta.pseudo_kind);
- self.pseudo_records_present |= 1 << kind;
- self.pseudo_records[kind] = delta.new_style_record;
- self.pseudo_damages[kind] = FfiPseudoRecordDamage {
- old_style_record: delta.old_style_record,
- new_style_record: delta.new_style_record,
- damage: delta.answered_damage(),
+ /// A targeted update of `node`: the engine computes the record it demands for the element now, and the host takes
+ /// the installation of that record as it takes a style update's. Answers whether the engine could: where it could
+ /// not, the element keeps what it holds until the next style update.
+ fn demand(self, node: StyleNodeID) -> bool {
+ let Some(installation) = with_engine(self.read, self.host, |engine| engine.demand_installation(node)) else {
+ return false;
};
- }
-}
-
-/// Applies `reactions` in preorder, so every element's inheritance inputs are ready when it is applied. What an
-/// applied element's change means for its (flat-tree) children is the engine's to derive: it reads each application
-/// and derives the children's reactions as the next transaction of this style update.
-fn apply_style_reactions(
- application: Application<'_>,
- reactions: &[FfiStyleDelta],
- counts: &mut FfiStyleReactionCounts,
-) {
- let Application { host, read, .. } = application;
- let _noting = host.engine_memo().note_declaration_changes_during_apply();
- for (index, published) in reactions.iter().enumerate() {
- // A pseudo-element record installs with its element's, which leads it. An element the engine answered as
- // hidden needs no style until a read or its subtree's reveal asks for one.
- if published.pseudo_kind != u8::MAX || published.gap == FfiStyleDeltaGap::Hidden {
- continue;
- }
- let element = application.element(published.style_node);
- if element.element.is_null() {
- continue;
- }
- let node = StyleNodeID::from_raw(published.style_node).expect("a style reaction names an element");
- let mut delta = *published;
-
- // A host that rewrote the element's declarations while an earlier reaction was applied (a form control
- // restyling its shadow tree as its own style moves) leaves the record the engine computed from the old ones:
- // it is answered from its demand, over the declarations as they are now.
- if delta.gap == FfiStyleDeltaGap::Computed && host.engine_memo().declarations_changed_during_apply(node) {
- delta.unsettle();
- delta.reaction |= STYLE_REACTION_RECOMPUTE_STYLE;
- }
-
- // NB: An earlier reaction's environment move can republish the record an element holds over the moved
- // environment. A swap of its inherited groups computed over the record it held before would undo the move:
- // the reaction is
- // answered from its demand, over the record the element holds now.
- if delta.gap == FfiStyleDeltaGap::None && element.has_style && delta.old_style_record != element.style_record {
- delta.unsettle();
- }
-
- // A reaction the engine derived for this element while applying an earlier one in this batch joins the
- // element's own reaction where it covers it, which a demand for the element's record always does.
- let absorbed = absorb_element_style_input(
- host,
- read,
- node,
- delta.reaction,
- delta.inherited_style_groups,
- delta.gap == FfiStyleDeltaGap::Materialize,
- );
- if absorbed != 0 {
- delta.reaction = absorbed as u8;
- delta.inherited_style_groups = (absorbed >> 8) as u8;
- }
-
- // An engine-computed record installs on an element without style as a first record does, its style cleared on
- // entry to display:none included; other record deltas assume the style they move.
- // NB: A reaction that only lets an ancestor's reactions reach its descendants computes nothing of its own. If
- // an earlier display:none reaction cleared its style and no derived input reached it, leave it unstyled
- // until a read or reveal.
- if !element.has_style
- && (delta.gap == FfiStyleDeltaGap::None
- || (delta.gap == FfiStyleDeltaGap::Materialize && delta.reaction == 0))
- {
- continue;
- }
-
- let needs_regular_style_recompute = delta.reaction
- & (STYLE_REACTION_PUBLISHED_STYLE
- | STYLE_REACTION_RECOMPUTE_STYLE
- | STYLE_REACTION_RECOMPUTE_DESCENDANT_STYLES
- | STYLE_REACTION_ANCESTOR_BECAME_VISIBLE)
- != 0;
- let needs_custom_property_recompute = delta.reaction & STYLE_REACTION_INHERITED_CUSTOM_PROPERTIES != 0;
- let needs_inherited_style_recompute = delta.reaction & STYLE_REACTION_INHERITED_STYLE != 0;
- // An element declaring custom properties of its own layers them over the environment it inherits, which its
- // cascade decides.
- let computes_style = needs_regular_style_recompute
- || needs_inherited_style_recompute
- || (needs_custom_property_recompute
- && (element.reads_environment
- || with_engine(read, host, |engine| engine.node_declares_custom_properties(node))));
-
- // A reaction the engine did not settle in its transaction, and that computes the element's style, is answered
- // from its record demand, as a targeted update of the element is: the record installs as one the engine
- // computed, moving the element from the record it holds.
- let mut installation = None;
- if delta.gap == FfiStyleDeltaGap::Materialize
- && computes_style
- && let Some(answer) = application.answer_record_demand(&element, node)
- {
- delta.old_style_record = element.style_record;
- let mut demanded = FfiRecordInstallation::new(delta, true);
- demanded.settle(&answer);
- delta = demanded.delta;
- installation = Some(demanded);
- }
-
- if delta.reaction & STYLE_REACTION_PUBLISHED_STYLE != 0 {
- counts.published_reactions += 1;
- }
- if delta.gap == FfiStyleDeltaGap::Materialize {
- if delta.reaction & STYLE_REACTION_PUBLISHED_STYLE != 0 {
- counts.materialized_gaps += 1;
+ self.install_styles(&installation);
+ with_engine(self.read, self.host, |engine| {
+ for &record in &installation.pinned_records {
+ engine.unpin_layout_style_record(record);
}
- assert!(delta.new_style_record == 0 && delta.damage == FfiStyleDeltaDamage::None);
- } else {
- counts.record_deltas_applied += 1;
- // An engine-computed record is the engine's current answer for the element, which may have skipped a
- // delta the host never installed; it is applied against whatever the element holds now.
- assert!(delta.gap == FfiStyleDeltaGap::Computed || delta.old_style_record == element.style_record);
- assert!(delta.new_style_record != 0 && delta.damage == FfiStyleDeltaDamage::Full);
- }
-
- let installation = match delta.gap {
- FfiStyleDeltaGap::None => {
- assert!(!needs_regular_style_recompute && needs_inherited_style_recompute);
- assert!(!needs_custom_property_recompute);
- // The engine swapped the element's inherited groups for its parent's: the record installs as an
- // engine record. The engine refuses the swap to an element that animates, declares transitions, or
- // inherits from an animating parent. A parent this batch installed may have taken animated values
- // from its own ancestors since the engine swapped, which the element inherits in place of the base
- // ones: the reaction is answered from its demand.
- // SAFETY: The element is live while its reaction is applied.
- if unsafe { web_css_parent_style_has_animated_values(element.element.0) } {
- application.demand(&element, node, delta.reaction, delta.inherited_style_groups)
- } else {
- Some(FfiRecordInstallation::new(delta, false))
- }
- }
- FfiStyleDeltaGap::Computed => {
- // The engine computed the new record from this element's moved cascade winners, from its parent's
- // moved inherited style or display, or from its moved inherited custom-property environment.
- assert!(
- needs_regular_style_recompute || needs_inherited_style_recompute || needs_custom_property_recompute
- );
- // A demand settled the pseudo-elements beside the element's record; the reactions the batch published
- // beside the element's moved from a record the demand replaced.
- let installation = installation.unwrap_or_else(|| {
- let mut installation = FfiRecordInstallation::new(delta, true);
- reactions[index + 1..]
- .iter()
- .take_while(|next| next.style_node == delta.style_node && next.pseudo_kind != u8::MAX)
- .for_each(|pseudo_delta| installation.add_pseudo_element_delta(pseudo_delta));
- installation
- });
- if application.record_environment_is_installable(&element, node, delta.new_style_record) {
- Some(installation)
- } else {
- // The engine resolved the record's environment over the parent's own, which an earlier reaction of
- // the batch moved: the reaction is answered from a fresh demand.
- application.demand(&element, node, delta.reaction, delta.inherited_style_groups)
- }
- }
- // The engine declined the reaction's demand above.
- _ if computes_style => {
- application.refuse(node, delta.reaction, delta.inherited_style_groups);
- None
- }
- // A reaction that owes only a moved inherited environment on an element whose style reads none has nothing
- // left for the host: the engine moved the element's environment, and the record over it, when its
- // parent's moved.
- _ => None,
- };
- application.apply(&element, delta.reaction, installation.as_ref());
+ });
+ true
}
}
@@ -603,152 +157,119 @@ fn apply_style_reactions(
const MAX_STYLE_UPDATE_PASSES: u32 = 8;
impl Application<'_> {
- /// Takes the next style transaction of the update, the one computed beside the event loop first where the update
- /// drains it, and
- /// answers the reactions naming an element into `reactions`, and whether the batch is dense enough to match
- /// broadly.
- fn take_transaction(self, flown: bool, reactions: &mut Vec<FfiStyleDelta>) -> (bool, bool) {
- let taken = {
+ /// Takes the next style update of the host's update_style(), the one computed beside the event loop first where it
+ /// drains it, and answers the style installation the render side made of it for the host to swap in.
+ fn take_transaction(self, flown: bool) -> StyleInstallation {
+ {
let _taking = self.host.engine_memo().take_transactions_to_apply();
// SAFETY: The host lends its application for the call that updates the style.
- unsafe { web_css_take_style_transaction(self.host_application, flown) }
- };
- // SAFETY: The host's transaction lives until it takes the next one.
- let taken_reactions = unsafe { super::bridge::borrow(taken.reactions, taken.count) };
- reactions.clear();
- for reaction in taken_reactions {
- // The complete answer remains in the engine's transaction scratch under this node, which the reaction
- // names. An element removed while the transaction was computed beside the event loop has no style to
- // install: its removal is the next transaction's.
- if self.element(reaction.style_node).element.is_null() {
- let node = StyleNodeID::from_raw(reaction.style_node).expect("a style reaction names an element");
- assert!(
- self.host
- .engine_memo()
- .beside_flown_transaction
- .borrow()
- .contains(&node)
- );
- continue;
- }
- reactions.push(*reaction);
+ unsafe { web_css_run_style_update(self.host_application, flown) };
}
- // A reaction can name an element created by editing after its new inheritance parent was inserted, and an
- // element between a reaction and an ancestor that reacts too needs a reaction of its own for the reactions the
- // ancestor derives to reach the reaction. The engine closes a transaction's reactions over both as it computes
- // them, and orders them for application in preorder: every parent is ready before its descendants, and a
- // parent's derived reaction can merge into an unconsumed child reaction in the same batch. The reactions of a
- // transaction computed beside the event loop close only as the host drains them, over the elements it has now.
- if flown {
- let beside_flown_transaction = self.host.engine_memo().beside_flown_transaction.borrow();
- with_engine(self.read, self.host, |engine| {
- if close_style_reactions_over_inheritance(engine, reactions, &beside_flown_transaction) {
- sort_style_deltas_for_direct_application(engine, reactions);
- }
- });
+ self.host.take_transaction_installation().unwrap_or_default()
+ }
+
+ /// Has the host swap in the styles of `installation`, a style installation, and perform their side effects.
+ fn install_styles(self, installation: &StyleInstallation) {
+ // SAFETY: The host lends its application for the call that updates the style, and the slices live for it.
+ unsafe {
+ web_css_install_styles(
+ self.host_application,
+ installation.swaps.as_ptr(),
+ installation.swaps.len(),
+ installation.effects.as_ptr(),
+ installation.effects.len(),
+ installation.document_damage,
+ );
}
- // A reaction batch covering more than one sixteenth of the connected elements is dense enough that packing
- // the scope once is cheaper than repeatedly reconstructing cold element state while matching its elements.
- let prefers_broad_matching_batch =
- !taken.scoped || reactions.len() * 16 > taken.connected_element_count as usize;
- (prefers_broad_matching_batch, taken.only_derived_child_reactions)
}
fn has_pending_transaction(self) -> bool {
// SAFETY: As above.
- unsafe { web_css_has_pending_style_transaction(self.host_application) }
+ unsafe { web_css_has_pending_style_update(self.host_application) }
}
}
-/// Applies the reactions of the style transactions of one style update, from the first, computed beside the event
-/// loop where the update drains it, until the reactions they feed back settle. Each pass applies one transaction's
+/// Applies the reactions of the style updates of one update_style(), from the first, computed beside the event
+/// loop where it drains one, until the reactions they feed back settle. Each pass applies one transaction's
/// reactions, closed over the elements they inherit through, and the consequences produced while applying them become
/// the next transaction.
-fn update_style(
- application: Application<'_>,
- drains_flown_transaction: bool,
- root: Option<StyleNodeID>,
-) -> FfiStyleReactionCounts {
- let host = application.host;
+fn update_style(application: Application<'_>, drains_flown_transaction: bool) -> FfiStyleReactionCounts {
let mut counts = FfiStyleReactionCounts::default();
- let mut reactions = Vec::new();
- let (mut prefers_broad_matching_batch, mut only_derived_child_reactions) =
- application.take_transaction(drains_flown_transaction, &mut reactions);
+ let mut taken = application.take_transaction(drains_flown_transaction);
+ let is_empty = |installation: &StyleInstallation| installation.swaps.is_empty() && installation.effects.is_empty();
// SAFETY: The host lends its application for the call that updates the style.
unsafe {
- if !reactions.is_empty() {
+ if !is_empty(&taken) {
web_css_note_style_update_has_reactions(application.host_application);
}
web_css_sample_animations_for_style_update(application.host_application);
}
- if reactions.is_empty() && application.has_pending_transaction() {
- (prefers_broad_matching_batch, only_derived_child_reactions) =
- application.take_transaction(false, &mut reactions);
+ if is_empty(&taken) && application.has_pending_transaction() {
+ taken = application.take_transaction(false);
}
// SAFETY: As above.
unsafe { web_css_begin_style_update_pass(application.host_application, true) };
- if reactions.is_empty() {
+ if is_empty(&taken) {
return counts;
}
counts.had_reactions = true;
- let cold_matching_batch = root.map(|root| {
- host.queue_change(ArenaChange::Style(if prefers_broad_matching_batch {
- StyleChange::BeginColdMatchingBatch { root: Some(root) }
- } else {
- StyleChange::BeginAdaptiveColdMatchingBatch { root: Some(root) }
- }));
- });
-
let mut style_update_passes = 0;
let mut first_pass = true;
- while !reactions.is_empty() {
+ while !is_empty(&taken) {
let apply_started_at = std::time::Instant::now();
- // One more tree generation of the same style change is not a new pass of it.
- if !std::mem::take(&mut first_pass) && !only_derived_child_reactions {
+ if !std::mem::take(&mut first_pass) {
// SAFETY: As above.
unsafe { web_css_begin_style_update_pass(application.host_application, false) };
}
- let published_reactions = reactions
- .iter()
- .filter(|reaction| reaction.reaction & STYLE_REACTION_PUBLISHED_STYLE != 0)
- .count() as u32;
- if published_reactions > 0 && !only_derived_child_reactions {
+ let published_reactions = taken.swaps.len() as u32;
+ if published_reactions > 0 {
style_update_passes += 1;
if style_update_passes > MAX_STYLE_UPDATE_PASSES {
counts.pass_guard_hits += 1;
+ // NB: The render side noted the records the installation swaps in as the host's, so the host takes it
+ // before it stops.
+ application.install_styles(&taken);
counts.apply_microseconds += apply_started_at.elapsed().as_micros() as u64;
break;
}
}
-
- reactions.retain(|reaction| application.element(reaction.style_node).connected);
- if !reactions.is_empty() {
- if published_reactions > 0 {
- counts.batch_runs += 1;
- counts.reaction_elements += published_reactions;
- }
- apply_style_reactions(application, &reactions, &mut counts);
- reactions.clear();
- }
+ counts.batch_runs += 1;
+ counts.reaction_elements += published_reactions;
+ application.install_styles(&taken);
counts.apply_microseconds += apply_started_at.elapsed().as_micros() as u64;
- // Exact consequences produced while recomputing become the next transaction in this stabilization epoch. Take
- // it only after consuming the current published answers, since a new transaction retires their scratch.
- if application.has_pending_transaction() {
- (_, only_derived_child_reactions) = application.take_transaction(false, &mut reactions);
- }
- }
- if cold_matching_batch.is_some() {
- host.queue_change(ArenaChange::Style(StyleChange::EndColdMatchingBatch));
+ // The consequences produced while installing become the next transaction in this stabilization epoch.
+ taken = match application.has_pending_transaction() {
+ true => application.take_transaction(false),
+ false => StyleInstallation::default(),
+ };
}
counts
}
-/// Applies the reactions of the style transactions of a style update of the host's document, from the one computed
+/// Whether `LIBWEB_STYLE_SELFCHECK` asks for what `style_engine_self_check` does.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_self_check_is_enabled(host: &DocumentHost) -> bool {
+ host.engine_memo().style_self_check.is_enabled()
+}
+
+/// Checks what the engine holds for the host's document under `root`, its document element's style node or zero,
+/// against a cold pass, as `LIBWEB_STYLE_SELFCHECK` asks, once a style update has settled.
+#[unsafe(no_mangle)]
+pub extern "C" fn style_engine_self_check(host: &DocumentHost, read: &BegunRead, root: u32) {
+ let settings = host.engine_memo().style_self_check;
+ if let Some(root) = StyleNodeID::from_raw(root)
+ && settings.is_enabled()
+ {
+ with_engine(read, host, |engine| engine.run_self_check(root, settings));
+ }
+}
+
+/// Applies the reactions of the style updates of one update_style() of the host's document, from the one computed
/// beside the event loop
/// where `drains_flown_transaction`, through `host_application`, the host's state for applying them, and answers what
-/// they did for its counters. `root` is the document element's style node, or zero.
+/// they did for its counters.
///
/// # Safety
///
@@ -759,14 +280,13 @@ pub unsafe extern "C" fn style_engine_update_style(
read: &BegunRead,
host_application: *mut HostStyleReactionApplication,
drains_flown_transaction: bool,
- root: u32,
) -> FfiStyleReactionCounts {
let application = Application {
host,
read,
host_application,
};
- update_style(application, drains_flown_transaction, StyleNodeID::from_raw(root))
+ update_style(application, drains_flown_transaction)
}
/// What an inheritance chain holds, by depth from its first element.
@@ -843,15 +363,17 @@ impl Application<'_> {
embedding_document_layout_was_stale: bool,
) -> FfiTargetedStyleAnswer {
let scan = self.scan_inheritance_chain(first, true);
- note_bound_failure_trace(self.host, || {
- format!(
- "scan:{:?}/{:?}/{:?}",
- scan.topmost_requiring_style, scan.nearest_display_none, scan.topmost_display_none
- )
- });
if mode == FfiStyleUpdateMode::StopAtDisplayNone && scan.display_none_above_every_element_requiring_style() {
return FfiTargetedStyleAnswer::Unstyled;
}
+ // NB: The records the engine installs for a document it owns are current once the style update ran, but
+ // for those below an element that is not displayed, which no style update styles: a read in normal mode
+ // demands them again, as their inputs may have moved since they were demanded last.
+ if scan.topmost_requiring_style.is_none()
+ && (mode != FfiStyleUpdateMode::Normal || scan.nearest_display_none.is_none())
+ {
+ return FfiTargetedStyleAnswer::HeldStyle;
+ }
// Normal mode also re-cascades the target path under its display:none ancestors.
let mut topmost_element_to_recompute = scan.topmost_requiring_style;
if mode == FfiStyleUpdateMode::Normal && topmost_element_to_recompute.is_none() {
@@ -871,59 +393,19 @@ impl Application<'_> {
.take(topmost_element_to_recompute + 1)
.map(|element| element.style_node)
.collect();
- let mut descendant_style_recompute_needed = false;
- note_bound_failure_trace(self.host, || format!("chain:{}", chain.len()));
for &style_node in chain.iter().rev() {
let element = self.element(style_node);
- note_bound_failure_trace(self.host, || {
- format!(
- "node:{}:{}{}",
- style_node,
- if element.has_style { "styled" } else { "unstyled" },
- if element.element.is_null() { ",gone" } else { "" }
- )
- });
let Some(node) = StyleNodeID::from_raw(style_node).filter(|_| !element.element.is_null()) else {
return FfiTargetedStyleAnswer::HeldStyle;
};
- let installation = self.demand(
- &element,
- node,
- STYLE_REACTION_PUBLISHED_STYLE | STYLE_REACTION_RECOMPUTE_STYLE,
- 0,
- );
- let installation = installation.as_ref().map_or(std::ptr::null(), std::ptr::from_ref);
- // SAFETY: The host lends its application for the call, and the element is live while it is updated.
- let applied = unsafe {
- web_css_apply_targeted_style_reaction(
- self.host_application,
- element.element.0,
- installation,
- descendant_style_recompute_needed,
- )
- };
- descendant_style_recompute_needed |= applied.recompute_descendant_styles;
-
- // The engine can refuse a first style, which leaves the rest of the chain nothing to inherit from.
- let element = self.element(style_node);
- note_bound_failure_trace(self.host, || {
- format!(
- "after:{}{}:{}",
- if element.has_style { "styled" } else { "unstyled" },
- if element.display_none { ",none" } else { "" },
- element.style_record
- )
- });
- if !element.has_style {
+ if !self.demand(node) {
return FfiTargetedStyleAnswer::HeldStyle;
}
- if element.display_none {
- if mode == FfiStyleUpdateMode::StopAtDisplayNone {
- return FfiTargetedStyleAnswer::Unstyled;
- }
- descendant_style_recompute_needed = false;
+
+ let element = self.element(style_node);
+ if element.display_none && mode == FfiStyleUpdateMode::StopAtDisplayNone {
+ return FfiTargetedStyleAnswer::Unstyled;
}
- descendant_style_recompute_needed |= applied.descendants_need_recompute;
}
FfiTargetedStyleAnswer::HeldStyle
}
@@ -975,102 +457,3 @@ pub unsafe extern "C" fn style_engine_update_style_for_inheritance_chain(
};
application.update_style_for_inheritance_chain(first, mode, embedding_document_layout_was_stale)
}
-
-/// Moves the custom-property environments below `origin`, whose own moved as `moved` says, and acts on what the move
-/// reached, in flat tree preorder, through `host_application`.
-///
-/// Every styled descendant holds the environment it inherits by identity, and the engine keeps what each holds: it
-/// hands the moved environment to the descendants that hold the one the element handed down before, with their
-/// records. What is left is the host's: installing those records, the environments of element-backed pseudo-elements,
-/// which the engine does not keep, and the custom properties a descendant declares itself, built again over the moved
-/// environment. A descendant whose style reads the environment computes again.
-///
-/// # Safety
-///
-/// `host` must be a live document host, on its document's thread, `host_application` must be live for the call, the
-/// stores `moved` names must be null or live raw `Arc` pointers, and `moved.new_inheritable_data` must be null or a
-/// live `Web::CSS::CustomPropertyData`.
-#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_move_custom_property_environment(
- host: &DocumentHost,
- read: &BegunRead,
- host_application: *mut HostStyleReactionApplication,
- origin: u32,
- moved: super::bridge::FfiEnvironmentMove,
-) {
- use super::environment_move::{EnvironmentMove, EnvironmentMoveAction, NamedEnvironment};
- let Some(origin) = StyleNodeID::from_raw(origin) else {
- return;
- };
- let named = |environment: super::bridge::FfiNamedEnvironment| NamedEnvironment {
- identity: environment.identity,
- store: environment.store,
- };
- let environment_move = EnvironmentMove {
- old_environment: named(moved.old_environment),
- new_environment: named(moved.new_environment),
- old_inheritable: moved.old_inheritable,
- new_inheritable: named(moved.new_inheritable),
- new_inheritable_data: moved.new_inheritable_data,
- new_inheritable_declares: moved.new_inheritable_declares,
- };
- let (actions, moved_environments) = with_engine(read, host, |engine| {
- let mut actions = Vec::new();
- // SAFETY: Guaranteed by the caller.
- unsafe { engine.move_custom_property_environment(origin, &environment_move, |action| actions.push(action)) };
- // Each element the move left an environment takes the record republished over it.
- let mut moved_environments = Vec::new();
- for action in &actions {
- let EnvironmentMoveAction::Republish { node, .. } = *action else {
- continue;
- };
- moved_environments.push((
- node,
- None,
- engine.element_custom_property_data(node).expose_provenance(),
- ));
- moved_environments.extend(
- engine
- .pseudo_element_custom_property_environments(node)
- .map(|(pseudo, data)| (node, Some(pseudo), data.expose_provenance())),
- );
- }
- (actions, moved_environments)
- });
- host.engine_memo().held.borrow_mut().follow_moved(&moved_environments);
-
- for action in actions {
- // SAFETY: The host lends its application for the call, and the environment it moved to outlives it.
- unsafe {
- match action {
- EnvironmentMoveAction::Republish {
- node,
- style_record,
- replaced,
- } => web_css_republish_moved_environment(
- host_application,
- node.raw(),
- style_record,
- replaced,
- moved.new_inheritable_data,
- ),
- EnvironmentMoveAction::Rebuild(node) => {
- web_css_rebuild_custom_property_environment(
- host_application,
- node.raw(),
- moved.new_inheritable_data,
- );
- }
- // An element that has to compute again is recorded with a recompute reaction alone: its descendants
- // are the move's, or that computation's, to reach. (The engine fans an inherited custom-properties
- // reaction out to every child of an applied reaction.)
- EnvironmentMoveAction::Recompute(node) => web_css_record_derived_element_style_input(
- host_application,
- node.raw(),
- STYLE_REACTION_RECOMPUTE_STYLE,
- 0,
- ),
- }
- }
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs b/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs
index fae0c46734b..ac6f5bea3cd 100644
--- a/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/style_invalidation.rs
@@ -101,6 +101,7 @@ struct StyleInvalidation {
any_computed_value_changed: bool,
affects_hit_testing: bool,
repaint_highlights: bool,
+ white_space_collapse_changed: bool,
}
impl StyleInvalidation {
@@ -151,6 +152,7 @@ impl StyleInvalidation {
self.any_computed_value_changed |= other.any_computed_value_changed;
self.affects_hit_testing |= other.affects_hit_testing;
self.repaint_highlights |= other.repaint_highlights;
+ self.white_space_collapse_changed |= other.white_space_collapse_changed;
}
/// Whether the damage stays in the box of its element: no layout tree, stacking context, visual context, scroll
@@ -185,6 +187,7 @@ impl StyleInvalidation {
any_computed_value_changed: has(FfiStyleInvalidationField::AnyComputedValueChanged),
affects_hit_testing: has(FfiStyleInvalidationField::AffectsHitTesting),
repaint_highlights: has(FfiStyleInvalidationField::RepaintHighlights),
+ white_space_collapse_changed: has(FfiStyleInvalidationField::WhiteSpaceCollapseChanged),
}
}
@@ -204,6 +207,8 @@ impl StyleInvalidation {
u32::from(self.any_computed_value_changed) * FfiStyleInvalidationField::AnyComputedValueChanged as u32;
packed |= u32::from(self.affects_hit_testing) * FfiStyleInvalidationField::AffectsHitTesting as u32;
packed |= u32::from(self.repaint_highlights) * FfiStyleInvalidationField::RepaintHighlights as u32;
+ packed |=
+ u32::from(self.white_space_collapse_changed) * FfiStyleInvalidationField::WhiteSpaceCollapseChanged as u32;
packed
}
}
@@ -224,7 +229,8 @@ pub(super) fn main_effects_of_damage(
let effects = MainEffects::NONE
.with(MainEffects::REBUILD, rebuilds)
.with(MainEffects::SCROLL_SNAP, damage.resnap_scroll_container)
- .with(MainEffects::HIGHLIGHTS, damage.repaint_highlights && !rebuilds);
+ .with(MainEffects::HIGHLIGHTS, damage.repaint_highlights && !rebuilds)
+ .with(MainEffects::HOST_BOX_FACTS, damage.white_space_collapse_changed);
(effects, LayoutTreeRebuildRoot::from_raw(damage.rebuild_root))
}
@@ -593,6 +599,21 @@ fn property_invalidation(property: u16, old: ComputedValuesView<'_>, new: Comput
if matches!(property, property_id::CONTAINER_NAME | property_id::CONTAINER_TYPE) {
result.recompute_descendants = true;
}
+ // The clip that `overflow: clip` gives a box's visual context reaches out by the box's overflow-clip-margin.
+ if matches!(
+ property,
+ property_id::OVERFLOW_CLIP_MARGIN_TOP
+ | property_id::OVERFLOW_CLIP_MARGIN_RIGHT
+ | property_id::OVERFLOW_CLIP_MARGIN_BOTTOM
+ | property_id::OVERFLOW_CLIP_MARGIN_LEFT
+ ) {
+ result.ensure_visual_context(VISUAL_CONTEXT_UPDATE_VALUES);
+ }
+ if property == property_id::WHITE_SPACE_COLLAPSE {
+ let collapse = crate::css::css_enums::white_space_collapse::COLLAPSE;
+ result.white_space_collapse_changed =
+ (old.white_space_collapse() == collapse) != (new.white_space_collapse() == collapse);
+ }
if property == property_id::TEXT_DECORATION_LINE {
result.repaint_text_decorations = true;
} else if matches!(
diff --git a/Libraries/LibWeb/Rust/src/css/style/style_job.rs b/Libraries/LibWeb/Rust/src/css/style/style_job.rs
index ce312ca4e3c..b5fa14dd39d 100644
--- a/Libraries/LibWeb/Rust/src/css/style/style_job.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/style_job.rs
@@ -4,17 +4,15 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! A document's style transaction as a job its render state runs: the host hands it the transaction's root and the
+//! A document's style update as a job its render state runs: the host hands it the transaction's root and the
//! document's computation inputs, and the job answers with the reactions the host applies, which the host keeps until
//! it ends the transaction.
use super::StyleEngine;
use super::bridge::{
FfiCustomFunctionEntry, FfiDocumentStyleComputationInputs, FfiHostHandle, FfiStyleSheetResourceContextEntry,
- FfiStyleTransactionOutput, FfiStyleTransactionView, take_style_transaction,
+ FfiStyleUpdateOutput, run_style_update,
};
-use super::engine_calls::with_engine;
-use super::identities::StyleNodeIdAllocator;
use super::tree::StyleNodeID;
use crate::css::custom_properties::{CustomPropertyRegistry, retain_custom_property_registry};
use crate::css::parser::query_parser::FfiMediaFeatureValue;
@@ -22,23 +20,19 @@ use crate::css::rule::CompiledFunction;
use crate::css::style_compute::FfiLengthResolutionContext;
use crate::painting::ffi::FfiFlightBlocker;
use crate::painting::recording_slot::FlightLicense;
-use crate::render_state::{BegunRead, DocumentHost, TaskBoundary, fly};
+use crate::render_state::{BegunRead, DocumentHost, FrameJob, TaskBoundary, fly};
use std::sync::Arc;
-/// Takes the pending style transaction under `root`, with the document computation inputs the host sealed for it.
+/// Takes the pending style update under `root`, with the document computation inputs the host sealed for it.
pub(crate) struct StyleJob {
root: StyleNodeID,
computation_inputs: Arc<SealedStyleInputs>,
/// Whether the transaction flies beside the host, which leaves its atom sweep to a later transaction: the host may
/// name an atom meanwhile that the sweep would reclaim before the host hears of it.
flies: bool,
- /// Where a style update applies the transaction's reactions as the job answers them, they close over the elements
- /// they inherit through, but for those that inherit from the elements here, which arrived, moved or retired
- /// beside the transaction the host drains: those are the next transaction's.
- closes_beside: Option<super::HashSet<StyleNodeID>>,
}
-/// A style transaction's document computation inputs, sealed on the host's thread: the job owns a copy of every buffer
+/// A style update's document computation inputs, sealed on the host's thread: the job owns a copy of every buffer
/// the host lent with them, and a reference to each custom function and to the custom-property registry they name, so
/// it reads nothing the host goes on writing.
pub(crate) struct SealedStyleInputs {
@@ -200,41 +194,39 @@ unsafe fn lent_bytes<'a>(bytes: FfiHostHandle, length: usize) -> &'a [u8] {
/// What a style job answers: the reactions of the transaction, owned, which the host keeps until it ends the
/// transaction.
pub(crate) struct StyleJobAnswer {
- output: FfiStyleTransactionOutput,
+ output: FfiStyleUpdateOutput,
records: NamedRecords,
- /// The synthetic pseudo-elements each element whose row the host composes has rules for, as a C++ record's
- /// pseudo-style mask, and those among them that no settle generates or changes, by element, which the host reads as
- /// it settles the element's pseudo-elements over the composition.
- composed_pseudo_styles: Box<[(u32, ComposedPseudoStyles)]>,
/// The transition steps the transaction decided beside the rows that owe them, by element, which the host's steps
/// read rather than ask.
decided_transition_steps: Box<[crate::css::transition::DecidedTransitionStep]>,
+ /// What the main thread does to take the transaction's style installation, until it takes it.
+ installation_for_host: super::pipeline::install::StyleInstallation,
+ /// What the render side installed of the style rows in the boxes of their elements itself, which the host adopts
+ /// as it installs the rows, without publishing them again.
+ styled_rows: crate::layout::StyledRows,
+ /// The styles installed for every element and pseudo-element once the transaction installed its rows.
+ installed_styles: super::computed::InstalledStyles,
}
-/// What a style transaction answers of the pseudo-elements of an element whose row the host composes.
-#[derive(Clone, Copy)]
-pub(crate) struct ComposedPseudoStyles {
- /// The synthetic pseudo-elements with rules, as a C++ record's pseudo-style mask.
- pub(crate) mask: u64,
- /// The pseudo-elements in `mask` that a settle over any composition of the element leaves alone.
- pub(crate) inert: u64,
-}
+/// A record a transaction's rows name, with the record the host holds for it.
+type NamedRecord = (u64, std::sync::Arc<super::pipeline::Record>);
-/// The view of each record a transaction's rows name and the custom-property environment it was computed in, by record,
-/// which the host's drain reads without asking.
+/// The record the host holds for each record a transaction's rows name, by record, which the host's drain reads without
+/// asking. Holding the records keeps them live for the host until the next transaction.
struct NamedRecords {
- records: Box<[(u64, super::bridge::FfiStyleRecordView, Option<u64>)]>,
+ records: Box<[NamedRecord]>,
/// Where the last lookup found its record. The host installs a transaction's rows in tree order, the order in
/// which their new records were minted, so the next lookup mostly finds the record at or just past it.
cursor: std::cell::Cell<usize>,
}
-// SAFETY: A view points into a published record, which never changes while it is live, and the host reads one only for
-// a record it installs from the transaction, which keeps it live, or one a row replaces, which the engine reclaims no
-// sooner than its next transaction.
-unsafe impl Send for NamedRecords {}
-
impl StyleJobAnswer {
+ /// The styles installed for every element and pseudo-element once the transaction installed its rows: the records
+ /// the rows install, and those of every element the transaction left as it was.
+ pub(crate) fn installed_styles(&self) -> &super::computed::InstalledStyles {
+ &self.installed_styles
+ }
+
/// The rows the transaction answered.
pub(crate) fn rows(&self) -> &[super::bridge::FfiStyleDelta] {
self.output.answers()
@@ -245,23 +237,105 @@ impl StyleJobAnswer {
self.output.reclaimed_style_atoms()
}
- /// The view of `record`, one the rows name, and the custom-property environment it was computed in.
- pub(crate) fn record(&self, record: u64) -> Option<(super::bridge::FfiStyleRecordView, Option<u64>)> {
+ /// The record the host holds for `record`, one the rows name.
+ pub(crate) fn record(&self, record: u64) -> Option<*const std::ffi::c_void> {
let NamedRecords { records, cursor } = &self.records;
let near = cursor.get();
let index = (near..records.len().min(near + 4))
.find(|&index| records[index].0 == record)
- .or_else(|| records.binary_search_by_key(&record, |&(record, ..)| record).ok())?;
+ .or_else(|| records.binary_search_by_key(&record, |&(record, _)| record).ok())?;
cursor.set(index);
- let (_, view, environment) = records[index];
- Some((view, environment))
+ Some(std::sync::Arc::as_ptr(&records[index].1).cast())
+ }
+
+ /// Takes what the main thread does to take the transaction's style installation.
+ pub(crate) fn take_installation(&mut self) -> super::pipeline::install::StyleInstallation {
+ self.installation_for_host.take_for_the_host()
}
- /// What the transaction answered of the pseudo-elements of `node`, where the host composes its row.
- pub(crate) fn composed_pseudo_styles(&self, node: u32) -> Option<ComposedPseudoStyles> {
- let styles = &self.composed_pseudo_styles;
- let index = styles.binary_search_by_key(&node, |&(node, _)| node).ok()?;
- Some(styles[index].1)
+ /// Notes, for each element whose style record the transaction installed, whether its box is one only the host
+ /// styles in `arena`, the layout arena the host installs the records into.
+ pub(crate) fn note_host_styled_boxes(&mut self, arena: &crate::layout::LayoutNodeArena) {
+ for row in &mut self.installation_for_host.effects {
+ let slot = arena.bound_row(row.node());
+ if !slot.is_invalid() && arena.box_is_styled_by_host(slot) {
+ row.effects |= super::bridge::MainEffects::HOST_BOX_FACTS;
+ }
+ }
+ }
+
+ /// How the boxes of `node`, an element whose style record the transaction installed, take it: they are built
+ /// again from the root the move names, or the host installs it where they take the composition of its animations, or
+ /// appear or go.
+ pub(crate) fn element_install(&self, node: StyleNodeID) -> crate::layout::ElementInstall {
+ use super::bridge::MainEffects;
+ use crate::layout::ElementInstall;
+ let Some(row) = self.installation_for_host.effects_of(node) else {
+ return ElementInstall::Boxes;
+ };
+ if row
+ .effects
+ .intersects(MainEffects::ANIMATED | MainEffects::DISPLAY_NONE_FLIP)
+ {
+ ElementInstall::Host
+ } else if row.effects.intersects(MainEffects::REBUILD) {
+ ElementInstall::Rebuild(row.rebuild_root)
+ } else {
+ ElementInstall::Boxes
+ }
+ }
+
+ /// Notes `styled`, what the render side installed of the transaction's style rows.
+ pub(crate) fn note_styled(&mut self, styled: crate::layout::StyledRows) {
+ debug_assert!(
+ self.styled_rows.pinned_records.is_empty() && self.styled_rows.rebuilt.is_empty(),
+ "the render side installs a transaction once"
+ );
+ use super::bridge::MainEffects;
+ for row in &mut self.installation_for_host.effects {
+ let node = row.node();
+ // The render side marked the rebuilds of these elements, which leaves the host none to mark.
+ if styled.rebuilt.binary_search(&node).is_ok() {
+ row.effects = row.effects.without(MainEffects::REBUILD);
+ }
+ // The host installs the records in the boxes of the elements the render side left to it, and of those the
+ // main thread held no style for.
+ let installed = styled
+ .elements
+ .binary_search_by_key(&node, |element| element.node)
+ .is_ok();
+ if !installed || !row.moves_from_a_record() {
+ row.effects |= MainEffects::HOST_BOX_FACTS;
+ }
+ }
+ self.styled_rows = styled;
+ self.installation_for_host.keep_effects_with_host_work();
+ }
+
+ /// Whether the render side installed `style_record`, the style record of the element `node`, in its boxes, and
+ /// those of its pseudo-elements, with the relayout and repaint the move asks for.
+ pub(crate) fn render_state_installed(&self, node: StyleNodeID, style_record: u64) -> bool {
+ let elements = &self.styled_rows.elements;
+ elements
+ .binary_search_by_key(&node, |element| element.node)
+ .is_ok_and(|index| elements[index].style_record == style_record)
+ }
+
+ /// The record the render side installed in the box `slot`, if it styled it.
+ pub(crate) fn render_state_installed_box(&self, slot: crate::layout::node_data::NodeSlotId) -> Option<u64> {
+ let boxes = &self.styled_rows.boxes;
+ let index = boxes
+ .binary_search_by_key(&slot.slot_index(), |styled| styled.slot.slot_index())
+ .ok()?;
+ (boxes[index].slot == slot).then_some(boxes[index].style_record)
+ }
+
+ /// Takes the records the render side pinned for the host as it installed the transaction's rows, which the host
+ /// unpins as it ends the transaction.
+ pub(crate) fn take_pinned_records(&mut self) -> Vec<u64> {
+ let mut pinned = std::mem::take(&mut self.styled_rows.pinned_records);
+ pinned.append(&mut self.installation_for_host.pinned_records);
+ pinned
}
/// The transition step the transaction decided beside the row of `node`, if it decided one.
@@ -275,16 +349,14 @@ impl StyleJobAnswer {
impl StyleJob {
/// Runs the job on `engine`, the engine of the document it was sent for.
pub(crate) fn run(self, engine: &mut StyleEngine) -> StyleJobAnswer {
+ // What an installation the host never took, as one a flush threw away made, has the main thread do is not this
+ // transaction's.
+ for record in engine.take_installation().pinned_records {
+ engine.unpin_layout_style_record(record);
+ }
engine.defer_atom_sweep(self.flies);
// SAFETY: The sealed inputs name only what they own, and live until the transaction has taken them in.
- let output = unsafe {
- take_style_transaction(
- engine,
- self.root,
- self.computation_inputs.inputs,
- self.closes_beside.as_ref(),
- )
- };
+ let output = unsafe { run_style_update(engine, self.root, self.computation_inputs.inputs) };
engine.defer_atom_sweep(false);
// The host reads the record each row replaces as well, as it compares a box's old style with its new one. Only a
// live base record comes along: the host asks about a replaced overlay record itself.
@@ -303,33 +375,8 @@ impl StyleJob {
records.dedup();
let records = records
.into_iter()
- .filter_map(|record| {
- let view = super::bridge::style_record_view(engine, record);
- view.present.then(|| {
- let environment = engine
- .computed_group_sets
- .style_record_custom_property_environment(record);
- (record, view, environment)
- })
- })
- .collect();
- // The host settles the pseudo-elements of a row it composes only once it has composed the row, which asks
- // which of them have rules, and which of those the settle leaves alone: the transaction that matched the
- // element answers it beside the row.
- let mut composed_pseudo_styles: Vec<_> = output
- .answers()
- .iter()
- .filter(|row| row.composed_by_the_host)
- .filter_map(|row| {
- let node = StyleNodeID::from_raw(row.style_node)?;
- let styles = ComposedPseudoStyles {
- mask: engine.published_pseudo_style_mask(node),
- inert: engine.inert_pseudo_kinds(node),
- };
- Some((row.style_node, styles))
- })
+ .filter_map(|record| Some((record, engine.computed_group_sets.host_record(record)?.clone())))
.collect();
- composed_pseudo_styles.sort_unstable_by_key(|&(node, _)| node);
// The host's transition step for a row that owes one asks how the row's move starts the element's transitions,
// which the transaction answers beside the row where nothing but the engine's records decides it.
let mut decided_transition_steps: Vec<_> = output
@@ -338,14 +385,45 @@ impl StyleJob {
.filter_map(|row| crate::css::transition::DecidedTransitionStep::of_row(&mut *engine, row))
.collect();
decided_transition_steps.sort_unstable_by_key(crate::css::transition::DecidedTransitionStep::node);
- StyleJobAnswer {
+ let installation_for_host = engine.take_installation();
+ // The render side knows what it publishes: the host swaps the installation's records in without echoing them.
+ installation_for_host.note_held_by_the_host(engine);
+ let installed_styles = engine.computed_group_sets.publish_installed_styles();
+ let answer = StyleJobAnswer {
output,
records: NamedRecords {
records,
cursor: std::cell::Cell::new(0),
},
- composed_pseudo_styles: composed_pseudo_styles.into_boxed_slice(),
decided_transition_steps: decided_transition_steps.into_boxed_slice(),
+ installation_for_host,
+ styled_rows: Default::default(),
+ installed_styles,
+ };
+ if engine.process_style.verifies_reads {
+ verify_installed_styles(answer.installed_styles(), answer.rows());
+ }
+ answer
+ }
+}
+
+/// Checks that `styles` install what `rows` do.
+fn verify_installed_styles(styles: &super::computed::InstalledStyles, rows: &[super::bridge::FfiStyleDelta]) {
+ for row in rows {
+ let Some(node) = StyleNodeID::from_raw(row.style_node) else {
+ continue;
+ };
+ let installed = match row.pseudo_kind {
+ u8::MAX => styles.element(node),
+ kind => styles.pseudo_element(node, kind),
+ };
+ let installed = installed.map_or(0, |style| style.final_style_record().raw());
+ if installed != row.new_style_record {
+ eprintln!(
+ "the installed styles hold record {installed} for node {} (pseudo-element {}), the row installs {}",
+ row.style_node, row.pseudo_kind, row.new_style_record
+ );
+ std::process::abort();
}
}
}
@@ -358,28 +436,39 @@ impl StyleJob {
/// `host` must be a live document host, on its document's thread, and the buffers `computation_inputs` names must be
/// live for this call.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_take_style_transaction(
+pub unsafe extern "C" fn style_engine_run_style_update(
host: &DocumentHost,
read: &BegunRead,
root: u32,
computation_inputs: FfiDocumentStyleComputationInputs,
-) -> FfiStyleTransactionView {
+) {
let Some(root) = StyleNodeID::from_raw(root) else {
- return FfiStyleTransactionView::default();
+ return;
};
let job = StyleJob {
root,
// SAFETY: Guaranteed by the caller.
computation_inputs: Arc::new(unsafe { SealedStyleInputs::seal(computation_inputs) }),
flies: false,
- closes_beside: host.engine_memo().closes_taken_transaction_beside(),
};
host.keep_style_inputs(root, Arc::clone(&job.computation_inputs));
- let answer = host.run(read, true, move |state| job.run(state.engine_mut()));
- host.keep_style_transaction(answer).output.view()
+ // A style update takes the transactions its installations feed back one after another, and ends only the last.
+ // The host installed the one it took before this one, so it is done with the records the render side pinned for
+ // it to compare with, which go as the next one is taken.
+ let pinned = host.take_style_update_pinned_records();
+ let answer = host.run(read, true, move |state| {
+ let engine = state.engine_mut();
+ for record in pinned {
+ engine.unpin_layout_style_record(record);
+ }
+ let mut answer = job.run(engine);
+ state.install_styles(&mut answer);
+ answer
+ });
+ host.keep_style_update(answer);
}
-/// Lets the pending style transaction under `root` fly beside the host, with the document computation inputs the host
+/// Lets the pending style update under `root` fly beside the host, with the document computation inputs the host
/// gathered, where `blocker` is none and no transaction the host let fly before waits to be drained. The host's next
/// style update drains its reactions first. Answers whether the transaction flies.
///
@@ -388,14 +477,12 @@ pub unsafe extern "C" fn style_engine_take_style_transaction(
/// `host` must be a live document host, on its document's thread, and the buffers `computation_inputs` names must be
/// live for this call.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn style_engine_let_style_transaction_fly(
+pub unsafe extern "C" fn style_engine_let_style_update_fly(
host: &DocumentHost,
root: u32,
computation_inputs: FfiDocumentStyleComputationInputs,
blocker: FfiFlightBlocker,
) -> bool {
- // The round the host sealed for the frame flies with it, or not at all.
- let round = host.take_sealed_round();
let (Some(root), Some(license)) = (StyleNodeID::from_raw(root), FlightLicense::for_blocker(blocker)) else {
return false;
};
@@ -407,79 +494,57 @@ pub unsafe extern "C" fn style_engine_let_style_transaction_fly(
// SAFETY: Guaranteed by the caller.
computation_inputs: Arc::new(unsafe { SealedStyleInputs::seal(computation_inputs) }),
flies: true,
- closes_beside: None,
};
host.keep_style_inputs(root, Arc::clone(&job.computation_inputs));
- fly(host, Some(job), round, &license);
+ fly(host, FrameJob::Style(job), &license);
true
}
-/// Takes in the style transaction of `host`'s document that the host let fly, waiting for it to land, for the host to
+/// Takes in the style update of `host`'s document that the host let fly, waiting for it to land, for the host to
/// drain its reactions against the inputs it was sealed with. What the host wrote beside the transaction reaches the
/// render state only once style_engine_end_flown_style_drain() ends the drain: it is the next transaction's.
#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_take_flown_style_transaction(
- host: &DocumentHost,
- read: &BegunRead,
-) -> FfiStyleTransactionView {
+pub extern "C" fn style_engine_drain_flown_style_update(host: &DocumentHost, read: &BegunRead) {
// The read takes the frame in where it still flies.
let answer = host.begin_style_drain(read);
- host.keep_style_transaction(answer).output.view()
+ host.keep_style_update(answer);
}
-/// Ends the drain of the style transaction of `host`'s document that flew, behind which the writes the host made beside
+/// Ends the drain of the style update of `host`'s document that flew, behind which the writes the host made beside
/// it reach the render state.
#[unsafe(no_mangle)]
pub extern "C" fn style_engine_end_flown_style_drain(host: &DocumentHost) {
- host.engine_memo().beside_flown_transaction.borrow_mut().clear();
host.end_style_drain();
}
-/// Notes that the element `node` names arrived, moved or retired beside the style transaction of `host`'s document that
-/// flew, which knows nothing of that, until the drain of its reactions ends.
+/// Whether the render state installed the record `style_record` of the element `style_node` names in its box ahead of
+/// the host, and marked the relayout the move asks for: the host's install of the row marks none then.
#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_note_style_node_beside_flown_transaction(host: &DocumentHost, node: u32) {
- if let Some(node) = StyleNodeID::from_raw(node) {
- host.engine_memo().beside_flown_transaction.borrow_mut().insert(node);
- }
+pub extern "C" fn style_engine_render_state_installed(host: &DocumentHost, style_node: u32, style_record: u64) -> bool {
+ StyleNodeID::from_raw(style_node).is_some_and(|style_node| host.render_state_installed(style_node, style_record))
}
-/// Whether the frame whose style transaction `host`'s document drains applied the element `style_node` names its record
-/// `style_record` ahead of the host, and marked the relayout the move asks for: the host's install of the row marks none
-/// then.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_frame_marked_relayout(host: &DocumentHost, style_node: u32, style_record: u64) -> bool {
- StyleNodeID::from_raw(style_node).is_some_and(|style_node| host.frame_marked_relayout(style_node, style_record))
-}
-
-/// Whether the style transaction of `host`'s document the host let fly still flies; one that has landed is taken in.
+/// Whether the style update of `host`'s document the host let fly still flies; one that has landed is taken in.
/// The event loop asks between two tasks, so this never waits.
#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_style_transaction_flies(host: &DocumentHost) -> bool {
+pub extern "C" fn style_engine_style_update_flies(host: &DocumentHost) -> bool {
let boundary = TaskBoundary::at_event_loop_entry(&TAKES_FINISHED_STYLE_IN);
host.frame_still_flies(&boundary)
}
-/// The entry the event loop calls between two tasks to take a document's style transaction in where it has landed.
+/// The entry the event loop calls between two tasks to take a document's style update in where it has landed.
pub(crate) struct TakesFinishedStyleIn {
_private: (),
}
const TAKES_FINISHED_STYLE_IN: TakesFinishedStyleIn = TakesFinishedStyleIn { _private: () };
-/// Ends the transaction the host took last, and has `allocator`, its document's allocator, mint the identities its end
-/// released again first.
+/// Ends the transaction the host took last. The engine releases the identities its end released once it applies the
+/// write, which the host takes back to mint again as it has that job back.
#[unsafe(no_mangle)]
-pub extern "C" fn style_engine_end_style_transaction(
- host: &DocumentHost,
- read: &crate::render_state::BegunRead,
- allocator: &mut StyleNodeIdAllocator,
-) {
- host.end_style_transaction();
- let released = with_engine(read, host, |engine| engine.discard_style_transaction_outputs());
- let memo = host.engine_memo();
- memo.held.borrow_mut().forget(&released);
- memo.described.borrow_mut().forget(&released);
- memo.baselines.borrow_mut().forget(&released);
- allocator.release(&released);
+pub extern "C" fn style_engine_end_style_update(host: &DocumentHost) {
+ let pinned = host.end_style_update();
+ host.queue_change(crate::render_state::ArenaChange::Engine(
+ super::engine_calls::EngineWrite::EndStyleUpdate { pinned: pinned.into() },
+ ));
}
diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rs
index 1a4d6dfd68d..4a415025c48 100644
--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs
+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs
@@ -6757,7 +6757,7 @@ fn in_display_none_subtree_for_animations(
{
return false;
}
- if longhands.effective_display(None).is_none() {
+ if longhands.effective_display(None).is_none() && !longhands.display_none_is_animated() {
return true;
}
// The element's own display is answered above, so an element's walk starts at its parent; a
diff --git a/Libraries/LibWeb/Rust/src/layout/box_removal.rs b/Libraries/LibWeb/Rust/src/layout/box_removal.rs
index 6c52c6b7496..d347e6c689b 100644
--- a/Libraries/LibWeb/Rust/src/layout/box_removal.rs
+++ b/Libraries/LibWeb/Rust/src/layout/box_removal.rs
@@ -72,7 +72,7 @@ impl LayoutNodeArena {
let mut sibling = sibling;
while let Some(current) = sibling {
if current.text_index().is_some() {
- return engine.tree().text_is_ascii_whitespace(current);
+ return engine.text_is_ascii_whitespace(current);
}
let Some(facts) = engine.element_published_box_facts(current) else {
return true;
@@ -88,7 +88,7 @@ impl LayoutNodeArena {
if !lays_out_elsewhere {
return false;
}
- sibling = engine.tree().next_sibling_in_dom_order(current);
+ sibling = engine.next_sibling_in_dom_order(current);
}
false
})
diff --git a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
index 60f68182a86..4687a8fbaf4 100644
--- a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
+++ b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
@@ -494,6 +494,22 @@ impl PlacedBoxes {
_ => formatting_context::containing_block_laid_out_in(callbacks, node, run_root),
}
}
+
+ /// Whether the placements of the boxes from the coordinate space box `space` up lead to `run_root`.
+ fn chain_of_space_reaches(
+ &self,
+ mut space: crate::layout::node_data::NodeSlotId,
+ run_root: crate::layout::node_data::NodeSlotId,
+ callbacks: &LayoutPass<'_>,
+ ) -> bool {
+ while space != run_root {
+ if !self.is_placed(space) {
+ return false;
+ }
+ space = self.placement_containing_block(callbacks, space, run_root);
+ }
+ true
+ }
}
/// The fragment the box of `candidate` committed, where `candidate` builds identically to it. A fragment that continues
@@ -1341,17 +1357,25 @@ impl RunFragmentBuilder {
}
/// Takes the absolutely positioned boxes whose containing block is the run's root and whose positions the run
- /// knows, in tree order. Those inside a child the run left unplaced stay for the run's parent.
+ /// knows, in tree order. Those inside a child the run left unplaced stay for the run's parent, as do those whose
+ /// positions stand in a space beyond the root, which only the placement of the root relates to the root: a table
+ /// places its cells in the space of its wrapper.
pub(crate) fn take_abspos_contained_by_root(
&self,
callbacks: &LayoutPass<'_>,
) -> Vec<abspos_inputs::PendingAbsposChild> {
let root = self.root_node;
- let mut taken: Vec<abspos_inputs::PendingAbsposChild> = self
- .inner
- .borrow_mut()
- .pending_abspos_at_root
- .extract_if(.., |entry| entry.containing_block() == root)
+ let mut inner = self.inner.borrow_mut();
+ let RunFragmentBuilderInner {
+ pending_abspos_at_root,
+ placed_boxes,
+ ..
+ } = &mut *inner;
+ let mut taken: Vec<abspos_inputs::PendingAbsposChild> = pending_abspos_at_root
+ .extract_if(.., |entry| {
+ entry.containing_block() == root
+ && placed_boxes.chain_of_space_reaches(entry.coordinate_space_box, root, callbacks)
+ })
.collect();
sort_in_tree_order(&mut taken, callbacks);
taken
diff --git a/Libraries/LibWeb/Rust/src/layout/tree_builder.rs b/Libraries/LibWeb/Rust/src/layout/tree_builder.rs
index 963e87f5de9..5310e8386be 100644
--- a/Libraries/LibWeb/Rust/src/layout/tree_builder.rs
+++ b/Libraries/LibWeb/Rust/src/layout/tree_builder.rs
@@ -27,6 +27,12 @@ use crate::layout::tree_update_marks::layout_tree_update_reuse_reason;
use crate::layout::{ComputedValuesView, FfiDisplay};
use crate::painting::paint_read::PaintRead;
+mod whitespace_text_boxes;
+
+use whitespace_text_boxes::{
+ predicted_whitespace_text_needs_box, starts_with_whitespace_text, whitespace_text_needs_box,
+};
+
type LayoutNode = NodeSlotId;
pub(crate) struct TreeBuilderState {
@@ -45,6 +51,9 @@ pub(crate) struct TreeBuilderState {
/// The elements a finished build asks the document to rebuild. `None` asks for the whole tree:
/// the container the box escaped into stands for no element.
layout_tree_rebuild_requests: Vec<Option<StyleNodeID>>,
+ /// The elements whose kept child lists hold a white space text whose box the build could not add or take away in
+ /// place, for the document to have their child lists built again. `None` names the document.
+ whitespace_text_box_rebuild_requests: Vec<Option<StyleNodeID>>,
/// Whether the build reached an element no style update settled, which it built no box for.
reached_unstyled_element: bool,
/// What the build found out that the document has to be told, in the order it found it out.
@@ -73,6 +82,7 @@ impl Default for TreeBuilderState {
layout_tree_update_escaped_rebuild_roots: false,
new_subtree_root: NodeSlotId::INVALID,
layout_tree_rebuild_requests: Vec::new(),
+ whitespace_text_box_rebuild_requests: Vec::new(),
reached_unstyled_element: false,
reports: Vec::new(),
pinned_style_records: Vec::new(),
@@ -501,13 +511,6 @@ pub(crate) fn principal_box_placement_decision(
}
}
-/// Which way a sibling walk runs.
-#[derive(Clone, Copy, PartialEq, Eq)]
-enum SiblingDirection {
- Previous,
- Next,
-}
-
/// Whether the box an element already has can take the children that were just inserted under it,
/// rather than being rebuilt around them.
///
@@ -522,9 +525,6 @@ struct ChildListInsertionReuse<'a, 'host> {
/// Whether a `::first-letter` owner styles the first letter of this subtree, whose source
/// range only a full build can find again.
has_first_letter_owner: bool,
- /// The last layout child, when it is an anonymous inline run that an inserted text node would
- /// have to join.
- trailing_inline_wrapper: LayoutNode,
}
/// Which narrower rebuilds the build settled on for one node.
@@ -643,7 +643,9 @@ fn may_update_pseudo_elements_in_place(
child = layout.next_sibling(child);
}
- if first_letter_owner_covers_subtree(layout, engine, element, layout_node) {
+ if first_letter_owner_covers_subtree(layout, engine, element, layout_node)
+ || starts_with_whitespace_text(engine, element)
+ {
return false;
}
@@ -728,24 +730,12 @@ fn may_reuse_layout_node_for_child_list_insertion(
return false;
}
- let last_layout_child = layout.last_child(layout_node);
- let trailing_inline_wrapper = if !last_layout_child.is_invalid()
- && node_facts::has_flag(layout.data(last_layout_child), NodeFlag::Anonymous)
- && node_facts::has_flag(layout.data(last_layout_child), NodeFlag::ChildrenAreInline)
- && !node_is_generated_for_pseudo_element(layout.data(last_layout_child))
- {
- last_layout_child
- } else {
- NodeSlotId::INVALID
- };
-
let mut test = ChildListInsertionReuse {
layout,
engine,
element,
layout_node,
has_first_letter_owner: false,
- trailing_inline_wrapper,
};
test.has_first_letter_owner = first_letter_owner_covers_subtree(layout, engine, element, layout_node);
test.run()
@@ -797,7 +787,6 @@ fn may_rebuild_child_list(
element,
layout_node,
has_first_letter_owner: false,
- trailing_inline_wrapper: NodeSlotId::INVALID,
};
test.child_list_can_be_rebuilt()
}
@@ -819,132 +808,46 @@ impl ChildListInsertionReuse<'_, '_> {
self.arena().needs_layout_tree_update(node)
}
- fn is_out_of_flow(&self, node: LayoutNode) -> bool {
- let data = self.layout.data(node);
- node_kind_is_node_with_style(data.kind.get()) && node_is_out_of_flow(self.layout, node)
- }
-
- fn parent_collapses_whitespace(&self) -> bool {
- self.layout
- .style(self.layout_node)
- .is_some_and(|style| style.white_space_collapse() == white_space_collapse::COLLAPSE)
- }
-
- /// Whether a text node holding only collapsing whitespace can be spliced in where it sits,
- /// which needs the boxes on both sides of it to be children of this box.
- fn collapsing_whitespace_can_be_inserted(&self, text: StyleNodeID) -> bool {
- let mut will_join_trailing_inline_wrapper = false;
- if !self.can_place_next_to_sibling(
- self.engine.previous_sibling_in_dom_order(text),
- SiblingDirection::Previous,
- &mut will_join_trailing_inline_wrapper,
- ) || !self.can_place_next_to_sibling(
- self.engine.next_sibling_in_dom_order(text),
- SiblingDirection::Next,
- &mut will_join_trailing_inline_wrapper,
- ) {
- return false;
- }
-
- // Incremental inline insertion always reuses a trailing anonymous inline wrapper. If the
- // whitespace belongs to a different run, only a full rebuild can place it correctly.
- self.trailing_inline_wrapper.is_invalid() || will_join_trailing_inline_wrapper
+ /// Whether the white space text `text` has a box once the inserted children are built, or `None` where an inserted
+ /// child's box is not certain before it is built.
+ fn whitespace_text_needs_box_after_insertion(&self, text: StyleNodeID) -> Option<bool> {
+ predicted_whitespace_text_needs_box(self.layout, self.engine, self.layout_node, text)
}
- fn can_place_next_to_layout_node(
- &self,
- sibling_layout_node: LayoutNode,
- direction: SiblingDirection,
- pseudo_element: Option<u8>,
- will_join_trailing_inline_wrapper: &mut bool,
- ) -> bool {
- if sibling_layout_node.is_invalid() {
- return true;
- }
- if self.is_out_of_flow(sibling_layout_node) && (pseudo_element.is_some() || direction == SiblingDirection::Next)
- {
- return false;
- }
-
- let mut sibling_layout_node = sibling_layout_node;
- loop {
- let parent = self.layout.parent(sibling_layout_node);
- if parent.is_invalid() || parent == self.layout_node {
- break;
- }
- sibling_layout_node = parent;
- }
- if self.layout.parent(sibling_layout_node) != self.layout_node {
- return false;
- }
- let children_are_inline = node_facts::has_flag(self.layout.data(self.layout_node), NodeFlag::ChildrenAreInline);
- if let Some(generated_for) = pseudo_element {
- // ::after cannot anchor a newly appended anonymous wrapper. In normal flow,
- // inline ::before content also has to remain in its existing inline run, while
- // blockified flex/grid pseudo-elements remain separate items.
- if direction == SiblingDirection::Next {
- return children_are_inline;
+ /// Whether every white space text child that is not being inserted keeps having a box, or keeps having none, once
+ /// the inserted children are built. A text that has to gain or lose its box changes the anonymous wrappers around
+ /// it, which only a build of the child list places right.
+ fn whitespace_text_boxes_stay(&self) -> bool {
+ self.dom_children().all(|child| {
+ if child.text_index().is_none() || !self.engine.text_is_ascii_whitespace(child) {
+ return true;
}
-
- let pseudo_display = self
- .engine
- .pseudo_published_box_facts(self.element, pseudo_kind_of(generated_for))
- .map(|facts| facts.display);
- let parent_display = self.layout.display(self.layout_node);
- let pseudo_belongs_to_inline_run = pseudo_display
- .is_some_and(|display| display.is_inline_outside() || display.is_contents())
- && !parent_display.is_flex_inside()
- && !parent_display.is_grid_inside();
- return children_are_inline || !pseudo_belongs_to_inline_run;
- }
- if node_facts::has_flag(self.layout.data(sibling_layout_node), NodeFlag::Anonymous) {
- if sibling_layout_node != self.trailing_inline_wrapper {
- return false;
+ let has_box = !self.box_of(child).is_invalid();
+ if !has_box && self.needs_layout_tree_update(child) {
+ return true;
}
- *will_join_trailing_inline_wrapper = true;
- }
- true
+ self.whitespace_text_needs_box_after_insertion(child) == Some(has_box)
+ })
}
- fn can_place_next_to_sibling(
- &self,
- sibling: Option<StyleNodeID>,
- direction: SiblingDirection,
- will_join_trailing_inline_wrapper: &mut bool,
- ) -> bool {
- let mut sibling = sibling;
- while let Some(current) = sibling {
- if self
- .published_display(current)
- .is_some_and(|display| display.is_contents())
- {
- return false;
- }
- let sibling_layout_node = self.box_of(current);
- if !sibling_layout_node.is_invalid() {
- return self.can_place_next_to_layout_node(
- sibling_layout_node,
- direction,
- None,
- will_join_trailing_inline_wrapper,
- );
+ /// Whether the box has an anonymous child other than one of its generated boxes, as table fixup makes around
+ /// table-internal children.
+ fn has_anonymous_child_box(&self) -> bool {
+ let mut child = self.layout.first_child(self.layout_node);
+ while !child.is_invalid() {
+ let data = self.layout.data(child);
+ if node_facts::has_flag(data, NodeFlag::Anonymous) && !node_is_generated_for_pseudo_element(data) {
+ return true;
}
- sibling = match direction {
- SiblingDirection::Next => self.engine.next_sibling_in_dom_order(current),
- SiblingDirection::Previous => self.engine.previous_sibling_in_dom_order(current),
- };
+ child = self.layout.next_sibling(child);
}
+ false
+ }
- let generated_for = match direction {
- SiblingDirection::Previous => GENERATED_FOR_BEFORE,
- SiblingDirection::Next => GENERATED_FOR_AFTER,
- };
- self.can_place_next_to_layout_node(
- self.arena().bound_pseudo_element_row(self.element, generated_for),
- direction,
- Some(generated_for),
- will_join_trailing_inline_wrapper,
- )
+ /// Whether the inserted text `text` renders nothing: white space that gets no box.
+ fn inserted_text_gets_no_box(&self, text: StyleNodeID) -> bool {
+ self.engine.text_is_ascii_whitespace(text)
+ && self.whitespace_text_needs_box_after_insertion(text) == Some(false)
}
fn dom_children(&self) -> impl Iterator<Item = StyleNodeID> + '_ {
@@ -957,17 +860,10 @@ impl ChildListInsertionReuse<'_, '_> {
}
/// Whether every child that has no box yet can be spliced in without the parent's own box
- /// being rebuilt: a collapsing whitespace text node, or an element that renders nothing.
+ /// being rebuilt: white space that gets no box, or an element with display: none.
fn pending_children_can_preserve_parent(&self) -> bool {
- let collapses_whitespace = self.parent_collapses_whitespace();
- let mut has_pending_collapsing_whitespace = false;
- let mut inserted_whitespace_run_must_stay_last = false;
for child in self.dom_children() {
if !self.box_of(child).is_invalid() {
- if inserted_whitespace_run_must_stay_last {
- return false;
- }
- has_pending_collapsing_whitespace = false;
if self.needs_layout_tree_update(child) || self.arena().child_needs_layout_tree_update(Some(child)) {
return false;
}
@@ -976,17 +872,10 @@ impl ChildListInsertionReuse<'_, '_> {
if !self.needs_layout_tree_update(child) {
continue;
}
- if child.text_index().is_some()
- && self.engine.text_is_ascii_whitespace(child)
- && collapses_whitespace
- && !self.has_first_letter_owner
- && self.collapsing_whitespace_can_be_inserted(child)
- {
- inserted_whitespace_run_must_stay_last |= has_pending_collapsing_whitespace;
- has_pending_collapsing_whitespace = true;
- continue;
- }
if child.text_index().is_some() {
+ if self.inserted_text_gets_no_box(child) {
+ continue;
+ }
return false;
}
if !self.published_display(child).is_some_and(|display| display.is_none()) {
@@ -996,36 +885,6 @@ impl ChildListInsertionReuse<'_, '_> {
true
}
- /// Whether a row inserted between two existing rows would make the table fixup wrap whitespace
- /// that sits at the edge of a row group today.
- fn has_table_row_sibling(&self, sibling: Option<StyleNodeID>, direction: SiblingDirection) -> bool {
- let mut sibling = sibling;
- while let Some(current) = sibling {
- let sibling_layout_node = self.box_of(current);
- if !sibling_layout_node.is_invalid() {
- return self.layout.parent(sibling_layout_node) == self.layout_node
- && node_kind_is_node_with_style(self.layout.data(sibling_layout_node).kind.get())
- && self.layout.display(sibling_layout_node).is_table_row();
- }
-
- if !current.text_index().is_some() {
- let Some(sibling_display) = self.published_display(current) else {
- return false;
- };
- if !sibling_display.is_none() {
- return self.needs_layout_tree_update(current) && sibling_display.is_table_row();
- }
- } else if !self.engine.text_is_ascii_whitespace(current) {
- return false;
- }
- sibling = match direction {
- SiblingDirection::Next => self.engine.next_sibling_in_dom_order(current),
- SiblingDirection::Previous => self.engine.previous_sibling_in_dom_order(current),
- };
- }
- false
- }
-
/// Whether a child before `inserted_child` resets a counter that counts down from its last item. The start value
/// of such a counter counts every increment in its scope, which includes the inserted child.
fn earlier_child_counts_a_counter_down(&self, inserted_child: StyleNodeID) -> bool {
@@ -1173,10 +1032,7 @@ impl ChildListInsertionReuse<'_, '_> {
continue;
}
if !self.needs_layout_tree_update(child) {
- // A full build may give such a text node a box again.
- if !is_element {
- return false;
- }
+ // A text without a box is built again, which gives it one where it renders.
continue;
}
if !is_element || self.published_display(child).is_none_or(|display| display.is_none()) {
@@ -1203,6 +1059,9 @@ impl ChildListInsertionReuse<'_, '_> {
}
fn run(&self) -> bool {
+ if !self.whitespace_text_boxes_stay() {
+ return false;
+ }
if self.pending_children_can_preserve_parent() {
// An empty set means every insertion was canceled before layout. Moves are marked dirty
// at their destination, so they still enter one of the rejection paths above.
@@ -1220,6 +1079,11 @@ impl ChildListInsertionReuse<'_, '_> {
let parent_lays_out_inline_children =
parent_lays_out_flow && (parent_children_are_inline || !parent_has_children);
let parent_lays_out_block_children = parent_lays_out_flow && !parent_children_are_inline;
+ // An inline box, and a block container of nothing but inline-level boxes, lay out their inline content as their
+ // own children, so inserted text lands among them where it sits in the DOM.
+ let parent_holds_its_inline_content = (parent_lays_out_inline_children
+ || (parent_display.is_inline_outside() && parent_display.is_flow_inside()))
+ && !self.has_anonymous_child_box();
let parent_lays_out_table_rows = parent_display.is_table_row_group()
|| parent_display.is_table_header_group()
|| parent_display.is_table_footer_group();
@@ -1234,28 +1098,6 @@ impl ChildListInsertionReuse<'_, '_> {
return false;
}
- if parent_lays_out_table_rows {
- // NB: Table fixup discards whitespace at the edge of a row group. Inserting a row outside
- // that whitespace makes it interior, so only a rebuild can create its anonymous table-row box.
- for child in self.dom_children() {
- if !child.text_index().is_some()
- || !self.box_of(child).is_invalid()
- || self.needs_layout_tree_update(child)
- || !self.engine.text_is_ascii_whitespace(child)
- {
- continue;
- }
- if self.has_table_row_sibling(
- self.engine.previous_sibling_in_dom_order(child),
- SiblingDirection::Previous,
- ) && self.has_table_row_sibling(self.engine.next_sibling_in_dom_order(child), SiblingDirection::Next)
- {
- return false;
- }
- }
- }
-
- let collapses_whitespace = self.parent_collapses_whitespace();
let mut will_insert_inline_child = false;
let mut will_insert_block_child = false;
let mut all_inserted_block_children_are_in_flow = true;
@@ -1267,11 +1109,6 @@ impl ChildListInsertionReuse<'_, '_> {
// A fieldset keeps its content in a structural anonymous content box that appended children must also enter.
let mut all_indirect_existing_children_are_in_text_run_wrappers =
self.layout.data(self.layout_node).kind.get() != NodeKind::FieldSetBox;
- let mut has_pending_collapsing_whitespace = false;
- // In a full build, an out-of-flow block or more whitespace after inserted whitespace joins the anonymous wrapper
- // that whitespace starts. The incremental insertion finds that wrapper only while it stays the parent's last
- // child.
- let mut inserted_whitespace_run_must_stay_last = false;
// Counters are resolved from the boxes before a box, so an inserted subtree that touches one changes only what
// comes after it.
let mut first_inserted_child_touching_counters = None;
@@ -1279,10 +1116,9 @@ impl ChildListInsertionReuse<'_, '_> {
for child in self.dom_children() {
let child_layout_node = self.box_of(child);
if !child_layout_node.is_invalid() {
- if inserted_whitespace_run_must_stay_last || first_inserted_child_touching_counters.is_some() {
+ if first_inserted_child_touching_counters.is_some() {
return false;
}
- has_pending_collapsing_whitespace = false;
has_existing_child_after_insertion |= has_inserted_child;
if self.layout.parent(child_layout_node) != self.layout_node {
let wrapper = self.layout.parent(child_layout_node);
@@ -1304,23 +1140,27 @@ impl ChildListInsertionReuse<'_, '_> {
if child.text_index().is_some() {
if !self.needs_layout_tree_update(child) {
- has_unboxed_existing_text = true;
+ // White space without a box keeps having none, as whitespace_text_boxes_stay() found.
+ has_unboxed_existing_text |= !self.engine.text_is_ascii_whitespace(child);
continue;
}
- if !self.engine.text_is_ascii_whitespace(child) || !collapses_whitespace {
- // Text that renders is inline-level content, which is appended as an inline element is.
- if !parent_lays_out_block_children || will_insert_block_child {
+ if self.inserted_text_gets_no_box(child) {
+ continue;
+ }
+ if parent_holds_its_inline_content && self.engine.text_is_ascii_whitespace(child) {
+ if will_insert_block_child {
return false;
}
will_insert_inline_child = true;
has_inserted_child = true;
continue;
}
- if self.has_first_letter_owner || !self.collapsing_whitespace_can_be_inserted(child) {
+ // Text that renders is inline-level content, which is appended as an inline element is.
+ if !parent_lays_out_block_children || will_insert_block_child {
return false;
}
- inserted_whitespace_run_must_stay_last |= has_pending_collapsing_whitespace;
- has_pending_collapsing_whitespace = true;
+ will_insert_inline_child = true;
+ has_inserted_child = true;
continue;
}
@@ -1362,10 +1202,6 @@ impl ChildListInsertionReuse<'_, '_> {
&& child_facts.position != positioning::FIXED
&& child_facts.float_ == float::NONE;
if parent_lays_out_flex_or_grid_children {
- if has_pending_collapsing_whitespace && !child_is_in_flow {
- return false;
- }
- has_pending_collapsing_whitespace = false;
has_inserted_child = true;
continue;
}
@@ -1373,10 +1209,6 @@ impl ChildListInsertionReuse<'_, '_> {
continue;
}
if parent_lays_out_block_children && child_display.is_block_outside() {
- if has_pending_collapsing_whitespace && !child_is_in_flow {
- inserted_whitespace_run_must_stay_last = true;
- }
- has_pending_collapsing_whitespace = false;
has_inserted_child = true;
will_insert_block_child = true;
if !child_is_in_flow {
@@ -1415,9 +1247,6 @@ impl ChildListInsertionReuse<'_, '_> {
&& !will_insert_block_child
&& (child_facts.position == positioning::ABSOLUTE || child_facts.position == positioning::FIXED)
{
- if has_pending_collapsing_whitespace {
- return false;
- }
will_insert_inline_child = true;
has_inserted_child = true;
continue;
@@ -1456,8 +1285,7 @@ impl ChildListInsertionReuse<'_, '_> {
&& all_indirect_existing_children_are_in_text_run_wrappers);
let can_append_after_indirect_existing_children =
appends_independent_children && !has_indirect_existing_child_after_insertion;
- (!has_indirect_existing_child || can_append_after_indirect_existing_children)
- && !has_pending_collapsing_whitespace
+ !has_indirect_existing_child || can_append_after_indirect_existing_children
}
}
@@ -1508,6 +1336,29 @@ pub(crate) fn principal_node_entry_decision(
}
}
+/// Whether an empty text produces a line box fragment: a child of an editing host, or text in a text control, which
+/// the caret anchors in and the control takes its baseline from.
+fn text_produces_line_box_fragment_when_empty(
+ engine: &RetainedState,
+ text: StyleNodeID,
+ is_in_user_agent_shadow_tree: bool,
+) -> bool {
+ use crate::css::style::bridge::element_construction_fact::{IS_EDITING_HOST, IS_HTML_INPUT_ELEMENT};
+ let parent = engine.text_parent(text);
+ let parent_is_editing_host = parent
+ .filter(|parent| parent.element_index().is_some())
+ .is_some_and(|parent| engine.element_construction_facts(parent) & IS_EDITING_HOST != 0);
+ // NB: Tree relations are keyed by element identity, so the walk to the host starts at the text's parent.
+ let is_in_text_control = is_in_user_agent_shadow_tree
+ && parent
+ .and_then(|parent| engine.shadow_host_of(parent))
+ .is_some_and(|host| {
+ engine.element_construction_facts(host) & IS_HTML_INPUT_ELEMENT != 0
+ || engine.element_box_kind(host) == ElementBoxKind::TextArea
+ });
+ parent_is_editing_host || is_in_text_control
+}
+
impl TreeBuilderHost<'_> {
/// The first node in the DOM child sequence the style mirror holds for `parent`.
fn first_dom_child(&self, parent: StyleNodeID) -> Option<StyleNodeID> {
@@ -1697,16 +1548,31 @@ impl TreeBuildJob {
}
}
- for &element in &state.layout_tree_rebuild_requests {
+ let rebuild_requests = state
+ .layout_tree_rebuild_requests
+ .iter()
+ .map(|&element| {
+ (
+ element,
+ crate::layout::commit::FfiCommitMessageKind::LayoutTreeRebuildRequested,
+ )
+ })
+ .chain(state.whitespace_text_box_rebuild_requests.iter().map(|&element| {
+ (
+ element,
+ crate::layout::commit::FfiCommitMessageKind::WhitespaceTextBoxesStale,
+ )
+ }))
+ .collect::<Vec<_>>();
+ for (element, kind) in rebuild_requests {
// A request that names no element asks for the whole tree, which the arena answers itself.
let Some(element) = element else {
host.arena_mut().set_needs_full_layout_tree_update(true);
continue;
};
- state.reports.push(crate::layout::commit::FfiCommitMessage::new(
- element.raw(),
- crate::layout::commit::FfiCommitMessageKind::LayoutTreeRebuildRequested,
- ));
+ state
+ .reports
+ .push(crate::layout::commit::FfiCommitMessage::new(element.raw(), kind));
}
let built_scroll_containers = host.arena_mut().take_built_scroll_containers();
@@ -1741,7 +1607,9 @@ impl TreeBuildJob {
viewport,
rebuilt_subtree_root_count,
layout_tree_update_escaped_rebuild_roots: state.layout_tree_update_escaped_rebuild_roots,
- needs_another_build_pass: !state.layout_tree_rebuild_requests.is_empty() || state.reached_unstyled_element,
+ needs_another_build_pass: !state.layout_tree_rebuild_requests.is_empty()
+ || !state.whitespace_text_box_rebuild_requests.is_empty()
+ || state.reached_unstyled_element,
};
TreeBuildAnswer {
outcome,
@@ -1760,8 +1628,13 @@ fn update_layout_tree_for_dom_children(
must_create_subtree: bool,
insertion_mode: FfiInsertionMode,
) {
+ let keeps_layout_parent = !must_create_subtree && !context.document_needs_full_layout_tree_update;
let mut node = host.first_dom_child(parent);
while let Some(current) = node {
+ if keeps_layout_parent && settle_whitespace_text_in_kept_child_list(host, state, current, insertion_mode) {
+ node = host.next_dom_sibling(current);
+ continue;
+ }
if insertion_mode == FfiInsertionMode::InDomOrder && host.arena().bound_row(current).is_invalid() {
update_layout_tree_for_spliced_child(host, state, current, context, must_create_subtree, insertion_mode);
} else if !keeps_its_box_as_it_is(host, current, context, must_create_subtree) {
@@ -1771,6 +1644,47 @@ fn update_layout_tree_for_dom_children(
}
}
+/// A walk that keeps the box of a white space text's layout parent never gives the text a box or takes its box away
+/// where it sits: the anonymous wrappers around the text, and the boxes after it, would have to change with it, which
+/// only a build of the parent's child list gets right. Asks for that build when the text's box has to change, and
+/// answers whether the walk is done with the text.
+fn settle_whitespace_text_in_kept_child_list(
+ host: &mut TreeBuilderHost<'_>,
+ state: &mut TreeBuilderState,
+ node: StyleNodeID,
+ insertion_mode: FfiInsertionMode,
+) -> bool {
+ if node.text_index().is_none() || !host.arena().text_is_ascii_whitespace(Some(node)) {
+ return false;
+ }
+ let layout_parent = state.current_parent();
+ let has_box = !host.arena().bound_row(node).is_invalid();
+ let needs_box = whitespace_text_needs_box(host, layout_parent, node);
+ let is_marked = host.arena().needs_layout_tree_update(node);
+ if needs_box == has_box {
+ // A text that renders nothing and holds no mark is done; any other takes the usual path.
+ return !has_box && !is_marked;
+ }
+ // A child list insertion places an inserted text where it renders, as it places any inserted text.
+ if needs_box && is_marked && insertion_mode == FfiInsertionMode::InDomOrder {
+ return false;
+ }
+ let mut container = layout_parent;
+ while node_facts::has_flag(host.data(container), NodeFlag::Anonymous) {
+ container = host.parent(container);
+ }
+ let element = host
+ .arena()
+ .commit_message_style_node(container)
+ .and_then(StyleNodeID::from_raw)
+ .filter(|style_node| style_node.element_index().is_some());
+ if !state.whitespace_text_box_rebuild_requests.contains(&element) {
+ state.whitespace_text_box_rebuild_requests.push(element);
+ }
+ host.arena_mut().clear_layout_tree_update_marks(Some(node));
+ true
+}
+
fn update_layout_tree_for_spliced_child(
host: &mut TreeBuilderHost<'_>,
state: &mut TreeBuilderState,
@@ -1851,8 +1765,13 @@ fn update_layout_tree_for_assigned_slottables(
) {
// The style mirror holds the assigned nodes in flat-tree order, and the list does not change while the build
// walks it.
+ let keeps_layout_parent = !must_create_subtree && !context.document_needs_full_layout_tree_update;
for index in 0..host.arena().assigned_node_count(Some(slot)) {
let node = host.arena().assigned_node_at(slot, index);
+ if keeps_layout_parent && settle_whitespace_text_in_kept_child_list(host, state, node, FfiInsertionMode::Append)
+ {
+ continue;
+ }
update_layout_tree(
host,
state,
@@ -2693,7 +2612,14 @@ fn rebuild_child_list_from_dom_children(
kept_box = host.parent(kept_box);
}
if kept_box.is_invalid() {
- update_layout_tree_for_spliced_child(host, state, child, context, false, FfiInsertionMode::Append);
+ // A text without a box is built again, which gives it one where it renders.
+ let is_text = child.text_index().is_some();
+ update_layout_tree_for_spliced_child(host, state, child, context, is_text, FfiInsertionMode::Append);
+ } else if host.arena().text_is_ascii_whitespace(Some(child))
+ && !whitespace_text_needs_box(host, state.current_parent(), child)
+ {
+ // The kept box goes once nothing holds it.
+ clear_stale_subtree(host, child, StaleSubtreeClearScope::Inclusive);
} else if host.arena().needs_layout_tree_update(child)
&& (host.arena().layout_tree_update_reuse_reasons(child) == 0
|| host.data(kept_box).kind.get() == NodeKind::TableWrapper)
@@ -2936,11 +2862,17 @@ fn construct_principal_layout_node(
layout_node = created;
created_box = Some(host.created(created));
} else if update.kind.is_text() {
+ let text_is_ascii_whitespace = host.arena().text_is_ascii_whitespace(update.style_node);
+ if text_is_ascii_whitespace
+ && !whitespace_text_needs_box(host, update.state.current_parent(), update.identity)
+ {
+ return PrincipalBoxConstruction::none();
+ }
let facts = host.arena().text_style_parent_facts(update.style_node);
let needs_style_wrapper = display_contents_text_needs_style_wrapper(
facts.has_style_parent,
facts.parent_display_is_contents,
- host.arena().text_is_ascii_whitespace(update.style_node),
+ text_is_ascii_whitespace,
facts.parent_collapses_whitespace,
);
let text_layout_node = host.create_text_box(update.identity);
@@ -4188,24 +4120,15 @@ impl<'a> TreeBuilderHost<'a> {
/// restamps it when editability changes. Under an element with a highlight pseudo-element style
/// and no box of its own, the row takes that style's paint facts itself.
fn stamp_text_row_facts(&mut self, slot: NodeSlotId, text: StyleNodeID) {
- use crate::css::style::bridge::element_construction_fact::{IS_EDITING_HOST, IS_HTML_INPUT_ELEMENT};
let is_in_user_agent_shadow_tree =
self.arena().node_flags(slot) & NodeFlag::IsInUserAgentShadowTree as u32 != 0;
let (produces_line_box_fragment_when_empty, parent_element) = self.arena().with_style_store(|engine| {
- let parent = engine.text_parent(text);
- let parent_element = parent.filter(|parent| parent.element_index().is_some());
- let parent_is_editing_host =
- parent_element.is_some_and(|parent| engine.element_construction_facts(parent) & IS_EDITING_HOST != 0);
- // NB: Tree relations are keyed by element identity, so the walk to the host starts at the
- // text's parent.
- let is_in_text_control = is_in_user_agent_shadow_tree
- && parent
- .and_then(|parent| engine.shadow_host_of(parent))
- .is_some_and(|host| {
- engine.element_construction_facts(host) & IS_HTML_INPUT_ELEMENT != 0
- || engine.element_box_kind(host) == ElementBoxKind::TextArea
- });
- (parent_is_editing_host || is_in_text_control, parent_element)
+ (
+ text_produces_line_box_fragment_when_empty(engine, text, is_in_user_agent_shadow_tree),
+ engine
+ .text_parent(text)
+ .filter(|parent| parent.element_index().is_some()),
+ )
});
self.arena_mut().set_node_flag(
slot,
@@ -4822,6 +4745,29 @@ fn insert_child_in_dom_order(
host.attach_child(parent, child, NodeSlotId::INVALID);
}
+/// Whether `node` is an absolutely positioned box that would be inline-level in flow, laid out among the inline content
+/// of `parent`: its static position is where an inline box would sit in a line, after the floats and with the line's
+/// alignment, which only an inline formatting context gives it.
+/// https://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width
+/// A flex, grid or MathML container positions its out-of-flow children itself, table fixup sees them as inline content
+/// already, SVG lays out its children without lines, and the viewport holds the top layer's members as boxes of their
+/// own.
+fn is_inline_level_absolutely_positioned_box_in_flow_layout(
+ host: &TreeBuilderHost<'_>,
+ parent: LayoutNode,
+ node: LayoutNode,
+) -> bool {
+ let parent_kind = host.data(parent).kind.get();
+ node_kind_is_node_with_style(host.data(node).kind.get())
+ && host.style(node).is_some_and(|style| {
+ style.is_absolutely_positioned() && style.display_before_box_type_transformation().is_inline_outside()
+ })
+ && !lays_out_each_child_as_its_own_box(host, parent)
+ && !is_tabular_container(host, parent)
+ && !node_facts::kind_is_svg_box(parent_kind)
+ && !matches!(parent_kind, NodeKind::SVGSVGBox | NodeKind::Viewport)
+}
+
fn insert_node_into_inline_or_block_ancestor(
host: &mut TreeBuilderHost<'_>,
state: &mut TreeBuilderState,
@@ -4833,6 +4779,8 @@ fn insert_node_into_inline_or_block_ancestor(
) {
assert!(!nearest_insertion_ancestor.is_invalid());
let node_slot = node.slot();
+ let is_inline_outside = is_inline_outside
+ || is_inline_level_absolutely_positioned_box_in_flow_layout(host, nearest_insertion_ancestor, node_slot);
let insertion_point = if is_inline_outside {
insertion_parent_for_inline_node(host, nearest_insertion_ancestor)
diff --git a/Libraries/LibWeb/Rust/src/layout/tree_builder/whitespace_text_boxes.rs b/Libraries/LibWeb/Rust/src/layout/tree_builder/whitespace_text_boxes.rs
index 182f1617eea..02e99f3ba84 100644
--- a/Libraries/LibWeb/Rust/src/layout/tree_builder/whitespace_text_boxes.rs
+++ b/Libraries/LibWeb/Rust/src/layout/tree_builder/whitespace_text_boxes.rs
@@ -150,7 +150,7 @@ impl PrecedingBoxes for PredictedBoxes<'_, '_> {
return step;
}
// Of the text that is white space alone, only empty text may or may not get a box once it is inserted.
- if engine.tree().text_is_ascii_whitespace(node) && engine.text_collapses_white_space(node) == Some(true) {
+ if engine.text_is_ascii_whitespace(node) && engine.text_collapses_white_space(node) == Some(true) {
return Step::Unknown;
}
return Step::Box(text_box(engine, node));
@@ -205,8 +205,8 @@ fn is_display_contents(engine: &RetainedState, element: StyleNodeID) -> bool {
/// nothing after the same box that comes before them both. So the walk back stops at it without asking about its box,
/// which also keeps a walk over a long run of white space and hidden elements short.
fn collapsing_whitespace_text_step(engine: &RetainedState, text: StyleNodeID) -> Option<Step> {
- let is_collapsing_whitespace = engine.tree().text_is_ascii_whitespace(text)
- && engine.tree().text_data(text).is_some_and(|data| !data.is_empty())
+ let is_collapsing_whitespace = engine.text_is_ascii_whitespace(text)
+ && engine.text_data(text).is_some_and(|data| !data.is_empty())
&& engine.text_collapses_white_space(text) == Some(true);
is_collapsing_whitespace.then_some(Step::Box(PrecedingBox::Text {
ends_in_collapsible_white_space: true,
@@ -214,7 +214,7 @@ fn collapsing_whitespace_text_step(engine: &RetainedState, text: StyleNodeID) ->
}
fn text_box(engine: &RetainedState, text: StyleNodeID) -> PrecedingBox {
- let last_code_unit = engine.tree().text_data(text).and_then(|data| match data.as_units() {
+ let last_code_unit = engine.text_data(text).and_then(|data| match data.as_units() {
ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units) => {
units.last().map(|&unit| unit.into())
}
@@ -229,7 +229,7 @@ fn text_box(engine: &RetainedState, text: StyleNodeID) -> PrecedingBox {
/// The node before `node` among the children of its parent in the flat tree: the slot it is assigned to, or its
/// parent.
fn previous_flat_tree_sibling(engine: &RetainedState, node: StyleNodeID) -> Option<StyleNodeID> {
- let tree = engine.tree();
+ let tree = engine;
if let Some(slot) = tree.assigned_slot_of(node) {
let assigned = tree.assigned_nodes_of(slot);
let index = assigned.iter().position(|&assigned_node| assigned_node == node)?;
@@ -240,7 +240,7 @@ fn previous_flat_tree_sibling(engine: &RetainedState, node: StyleNodeID) -> Opti
/// The children of `element` in the flat tree, text included.
fn flat_tree_children(engine: &RetainedState, element: StyleNodeID) -> Vec<StyleNodeID> {
- let tree = engine.tree();
+ let tree = engine;
if let Some(shadow_root) = tree.shadow_root_of(element) {
return tree.dom_children(shadow_root).collect();
}
@@ -298,7 +298,7 @@ fn preceding_box(boxes: &impl PrecedingBoxes, text: StyleNodeID) -> Option<Prece
sibling = previous_flat_tree_sibling(engine, current);
}
// The slot the node is assigned to, its parent, or the host of the shadow root it is a child of.
- let Some(parent) = engine.tree().inheritance_parent(node) else {
+ let Some(parent) = engine.inheritance_parent(node) else {
return Some(PrecedingBox::Nothing);
};
if let Some(found) = pseudo_element_box(boxes, parent, GENERATED_FOR_BEFORE)? {
@@ -333,11 +333,7 @@ fn decision_of_layout_parent_or_text(
return Some(false);
}
if engine.text_collapses_white_space(text) != Some(true)
- || text_produces_line_box_fragment_when_empty(
- engine,
- text,
- engine.tree().text_is_in_user_agent_shadow_tree(text),
- )
+ || text_produces_line_box_fragment_when_empty(engine, text, engine.text_is_in_user_agent_shadow_tree(text))
{
return Some(true);
}
@@ -426,7 +422,7 @@ pub(super) fn starts_with_whitespace_text(engine: &RetainedState, element: Style
fn first_content_is_whitespace_text(engine: &RetainedState, element: StyleNodeID) -> Option<bool> {
for child in flat_tree_children(engine, element) {
if child.text_index().is_some() {
- return Some(engine.tree().text_is_ascii_whitespace(child));
+ return Some(engine.text_is_ascii_whitespace(child));
}
let Some(facts) = engine.element_published_box_facts(child) else {
return Some(true);
diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rs
index 0f2a1e9f7c1..8f2e62fde20 100644
--- a/Libraries/LibWeb/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Rust/src/lib.rs
@@ -19,6 +19,7 @@ mod encoding_detection;
pub(crate) mod fork;
#[cfg(test)]
mod gfx_test_stubs;
+pub(crate) mod heap_size;
pub(crate) use libcompositing_rust::fast_hash;
pub(crate) mod css;
diff --git a/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp b/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp
index d53aca403da..af0b4530f39 100644
--- a/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp
+++ b/Libraries/LibWeb/SVG/SVGDecodedImageData.cpp
@@ -292,7 +292,7 @@ Optional<Compositing::DisplayListResource> SVGDecodedImageData::record_display_l
m_natural_size.clear();
m_document->set_svg_image_color_scheme(color_scheme);
m_document->style_scope().invalidate_style_cache();
- m_document->record_style_environment_change();
+ m_document->record_style_environment_change(DOM::StyleEnvironmentChange::ColorScheme | DOM::StyleEnvironmentChange::MediaFeatures);
}
navigable.set_viewport_size(css_size);
diff --git a/Libraries/LibWeb/SVG/SVGGeometryElement.cpp b/Libraries/LibWeb/SVG/SVGGeometryElement.cpp
index 1e5144ec93a..e4896ac66b3 100644
--- a/Libraries/LibWeb/SVG/SVGGeometryElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGGeometryElement.cpp
@@ -5,7 +5,6 @@
*/
#include <AK/Math.h>
-#include <AK/ScopeGuard.h>
#include <LibGC/Heap.h>
#include <LibWeb/Bindings/DOMPointReadOnly.h>
#include <LibWeb/CSS/CSSStyleProperties.h>
@@ -42,9 +41,8 @@ CSS::ElementBoxKind SVGGeometryElement::box_kind() const
}
// The style of an element outside the document, where no rule reaches it: the style engine cascades its own
-// presentation attributes and inline style over the initial values. The record comes back pinned for the caller, or
-// zero where the engine leaves the computation to C++.
-static CSS::StyleRecordID declared_only_style_record(Layout::BegunRead const& read, CSS::StyleComputer& style_computer, DOM::Document const& document, SVGGeometryElement& element)
+// presentation attributes and inline style over the initial values, or none where the engine computes none.
+static CSS::InstalledStyle declared_only_style(Layout::BegunRead const& read, CSS::StyleComputer& style_computer, DOM::Document const& document, SVGGeometryElement& element)
{
auto hints = CSS::StyleComputer::collect_presentational_hint_properties({ element });
Vector<CSS::Parser::ValueParserFFI::FfiDeclaredProperty> declarations;
@@ -57,14 +55,14 @@ static CSS::StyleRecordID declared_only_style_record(Layout::BegunRead const& re
.name = {},
});
}
- return CSS::StyleRecordID { CSS::StyleEngineFFI::style_engine_declared_only_record(
+ return CSS::InstalledStyle::adopt(CSS::StyleEngineFFI::style_engine_declared_only_record(
style_computer.style_engine().host(),
&read, document.style_node_id().value(),
CSS::element_box_type_adjustment_facts(element),
CSS::StyleEngineFFI::FfiElementDeclarationKind::SvgPresentationAttribute,
declarations.data(),
declarations.size(),
- element.inline_style_declarations()) };
+ element.inline_style_declarations()));
}
// The geometry of the element in user units, which the geometry queries such as getTotalLength() measure. It is empty
@@ -89,22 +87,21 @@ bool SVGGeometryElement::with_computed_values(Function<void(CSSPixelSize viewpor
// NB: An element with no style is either in a subtree that is not rendered, which the style engine answers
// without installing anything, or outside the document, where no rule reaches it. The engine of the window's
// document computes the latter, as an element's own document may never have been styled, like the one
- // holding a template's contents.
- auto const has_no_style_node = style_node_id() == CSS::StyleNodeID {};
- auto& style_document = has_no_style_node ? HTML::relevant_window(*this).associated_document() : document();
+ // holding a template's contents, whose elements have no style even where they are connected.
+ auto const computes_in_own_document = style_node_id() != CSS::StyleNodeID {} && !document().created_for_appropriate_template_contents();
+ auto& style_document = computes_in_own_document ? document() : HTML::relevant_window(*this).associated_document();
+ // NB: The engine of the window's document owns that document from its first style update, which may not have run.
+ if (!computes_in_own_document)
+ style_document.update_style();
auto& style_computer = style_document.style_computer();
// The style comes from the engine of the document that computes it, as that document's read.
Layout::ForcedReadScope style_read { style_document };
- auto record = has_no_style_node
- ? declared_only_style_record(style_read, style_computer, style_document, *this)
- : CSS::StyleRecordID { style_computer.style_engine().answer_record_demand(style_read, style_node_id(), CSS::StyleEngine::RecordDemand::ElementRead).record.style_record };
- ScopeGuard unpin_record = [&] {
- if (has_no_style_node && !!record)
- style_computer.unpin_style_record(record);
- };
- auto view = style_computer.computed_style_record_view(style_read, record);
- if (!view)
+ auto style = computes_in_own_document
+ ? CSS::InstalledStyle { style_computer.style_engine().answer_record_demand(style_read, style_node_id(), CSS::StyleEngine::RecordDemand::ElementRead).record.host_record }
+ : declared_only_style(style_read, style_computer, style_document, *this);
+ if (!style)
return false;
+ auto view = style_computer.computed_style_record_view(style);
callback({ viewport_size.width(), viewport_size.height() }, *view);
return true;
}
@@ -114,15 +111,16 @@ bool SVGGeometryElement::with_computed_values(Function<void(CSSPixelSize viewpor
template<typename Measure>
static auto measure_geometry(SVGGeometryElement const& element, CSSPixelSize viewport_size, CSS::ComputedValues const& computed_values, Measure measure)
{
+ // NB: The groups are laid out as a style record's are, so the shape reads them as the element's style.
Array<void const*, to_underlying(CSS::StyleGroupIndex::Count)> payloads;
for (size_t index = 0; index < payloads.size(); ++index)
payloads[index] = computed_values.style_group_payload(static_cast<CSS::StyleGroupIndex>(index));
+ CSS::StyleRecordGroupsOverPayloads groups { payloads, computed_values.inherited_set_values(), computed_values.reset_bits() };
auto points = Layout::svg_shape_points(element);
static_assert(sizeof(Gfx::FloatPoint) == sizeof(Layout::RustFFI::FfiFloatPoint));
Layout::RustFFI::FfiSvgGeometryElementShape shape {
.geometry = Layout::svg_geometry_facts(element),
- .payloads = payloads.data(),
- .payload_count = payloads.size(),
+ .style = &groups,
.points = reinterpret_cast<Layout::RustFFI::FfiFloatPoint const*>(points.data()),
.point_count = points.size(),
.viewport_size = viewport_size,
diff --git a/Libraries/LibWeb/SVG/SVGStopElement.cpp b/Libraries/LibWeb/SVG/SVGStopElement.cpp
index 6f55ee592b7..e9e01aaf57e 100644
--- a/Libraries/LibWeb/SVG/SVGStopElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGStopElement.cpp
@@ -22,7 +22,7 @@ SVGStopElement::SVGStopElement(DOM::Document& document, DOM::QualifiedName quali
Gfx::Color SVGStopElement::stop_color()
{
if (auto const* values = style_group<CSS::ComputedValues::SVGResetValues>())
- return Gfx::Color::from_bgra(values->stop_color);
+ return CSS::resolve_style_color(values->stop_color, style_group<CSS::ComputedValues::InheritedTextValues>()->color_value());
return CSS::InitialValues::stop_color();
}
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index 745a6bc54bd..1f1b532885b 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -1186,6 +1186,7 @@ void ConnectionFromClient::debug_request(Web::PageId page_id, ByteString request
if (request == "clear-cache") {
Web::Fetch::Fetching::clear_http_memory_cache();
+ Web::CSS::StyleScope::release_kept_data();
return;
}
diff --git a/Services/WebContent/WebDriverConnection.cpp b/Services/WebContent/WebDriverConnection.cpp
index bce90e2447f..c0c7fb9dc33 100644
--- a/Services/WebContent/WebDriverConnection.cpp
+++ b/Services/WebContent/WebDriverConnection.cpp
@@ -1285,7 +1285,7 @@ Web::WebDriver::Response WebDriverConnection::get_element_css_value(String eleme
if (auto property = Web::CSS::PropertyNameAndID::from_name(Utf16FlyString::from_utf8(name)); property.has_value()) {
if (property->is_custom_property()) {
if (auto data = element->custom_property_data({}); data) {
- if (auto const* style_property = data->get(property->name()))
+ if (auto style_property = data->get(property->name()); style_property.has_value())
computed_value = style_property->value->to_string(Web::CSS::SerializationMode::Normal);
}
} else if (auto computed_values = element->computed_style()) {
diff --git a/Tests/LibWeb/Crash/DOM/text-arriving-in-child-of-shadow-host-outside-flat-tree.html b/Tests/LibWeb/Crash/DOM/text-arriving-in-child-of-shadow-host-outside-flat-tree.html
new file mode 100644
index 00000000000..a3c0a762c13
--- /dev/null
+++ b/Tests/LibWeb/Crash/DOM/text-arriving-in-child-of-shadow-host-outside-flat-tree.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<input type="checkbox">
+<script>
+ const input = document.querySelector("input");
+ document.documentElement.offsetWidth;
+ const child = document.createElement("div");
+ input.append(child);
+ document.documentElement.offsetWidth;
+ child.append(document.createTextNode("x"));
+ document.documentElement.offsetWidth;
+</script>
diff --git a/Tests/LibWeb/TestStyleEngineBridge.cpp b/Tests/LibWeb/TestStyleEngineBridge.cpp
index 10c4b74c578..5b61a7ba845 100644
--- a/Tests/LibWeb/TestStyleEngineBridge.cpp
+++ b/Tests/LibWeb/TestStyleEngineBridge.cpp
@@ -38,7 +38,7 @@ TEST_CASE(unowned_atoms_are_released_in_one_transaction_batch)
}
EXPECT_EQ(Utf16FlyString::number_of_utf16_fly_strings(), initial_fly_string_count + 256);
auto initial_generation = engine.atom_generation();
- (void)engine.take_style_transaction(read, root);
+ (void)engine.run_style_update(read, root);
EXPECT_EQ(engine.atom_generation(), initial_generation + 1);
EXPECT_EQ(Utf16FlyString::number_of_utf16_fly_strings(), initial_fly_string_count);
}
@@ -90,7 +90,7 @@ TEST_CASE(reclaimed_language_atoms_republish_their_text)
EXPECT_EQ(counter_value(engine, "languageTextsPublished"sv), 1ull);
engine.flush();
- (void)engine.take_style_transaction(read, root);
+ (void)engine.run_style_update(read, root);
engine.intern_language_atom(language.view());
EXPECT_EQ(counter_value(engine, "languageTextsPublished"sv), 2ull);
@@ -114,7 +114,7 @@ TEST_CASE(inline_custom_declaration_names_survive_without_computed_environments)
engine.intern_atom(Utf16FlyString::from_utf8_without_validation(churn));
}
auto generation = engine.atom_generation();
- (void)engine.take_style_transaction(read, root);
+ (void)engine.run_style_update(read, root);
EXPECT(engine.atom_generation() > generation);
engine.intern_atom(Utf16FlyString::from_utf8_without_validation("--replacement-property"sv));
EXPECT_EQ(engine.intern_atom(name), atom);
diff --git a/Tests/LibWeb/Text/expected/DOM/complex-selector-queries-match-with-pending-style-input.txt b/Tests/LibWeb/Text/expected/DOM/complex-selector-queries-match-with-pending-style-input.txt
deleted file mode 100644
index 6bb2c7c4dd4..00000000000
--- a/Tests/LibWeb/Text/expected/DOM/complex-selector-queries-match-with-pending-style-input.txt
+++ /dev/null
@@ -1,34 +0,0 @@
-li .toggle: [7 14] [] same
-ul > li: [6 10 13 17 19] [] same
-li:nth-child(2n+1) > span: [7 14 15] [] same
-li:nth-last-child(2) em: [18] [] same
-li:first-child *: [7 8 9] [] same
-li:last-child p: [21 22] [] same
-li:only-child: [] [] same
-div > p:only-child: [] [] same
-span:first-of-type: [7 11 14 25] [37 39 40] same
-span:last-of-type: [7 11 15 25] [37 39 40] same
-em:only-of-type: [16 18] [] same
-em:nth-of-type(2): [9] [] same
-em:nth-last-of-type(1): [9 16 18] [] same
-li + li: [10 13 17 19] [] same
-li ~ li.b: [10 13 19] [] same
-div .a .b: [] [] same
-#root li.a > span: [7 14 15] [] same
-.x > .y + .z: [24] [] same
-.y ~ .z > .toggle: [25] [] same
-[data-k] b: [12] [] same
-[data-k=v] ~ *: [13 17 19] [] same
-section b[data-k]: [28] [] same
-LI .TOGGLE: [] [] same
-svg circle: [31 32] [] same
-g > CIRCLE: [] [] same
-html:first-child body: [3] [] same
-li:first-child, em + em: [6 9] [] same
-ul li:nth-child(odd) em:last-child: [9 16] [] same
-li:nth-child(-n+2) span: [7 11] [] same
-#host span: [] [] same
-div > span:first-child: [25] [37] same
-.a span: [7 14 15] [37 39] same
-p > span:only-child: [] [39] same
-queries that settled pending input: 0
diff --git a/Tests/LibWeb/Text/expected/Editing/insertHTML-redundant-style-with-substitution-function.txt b/Tests/LibWeb/Text/expected/Editing/insertHTML-redundant-style-with-substitution-function.txt
new file mode 100644
index 00000000000..e8522e6bbde
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Editing/insertHTML-redundant-style-with-substitution-function.txt
@@ -0,0 +1,8 @@
+a<span style="--own: 7px; margin: var(--own)">x</span>b
+a<span style="margin: var(--three); color: red">x</span>b
+a<span class="matched">x</span>b
+axb
+a<span style="margin-inline: var(--three)">x</span>b
+a<span style="border: var(--three) solid">x</span>b
+a<span style="color: red;">x</span>b
+a<span style="margin: var(--three); margin-left: 1px">x</span>b
diff --git a/Tests/LibWeb/Text/expected/Internals/internals-object-results-receiver-realm.txt b/Tests/LibWeb/Text/expected/Internals/internals-object-results-receiver-realm.txt
index 524e5a65e12..5ebe60becb3 100644
--- a/Tests/LibWeb/Text/expected/Internals/internals-object-results-receiver-realm.txt
+++ b/Tests/LibWeb/Text/expected/Internals/internals-object-results-receiver-realm.txt
@@ -1,5 +1,5 @@
style counters has null prototype: true
-style counters has reaction batches: true
+style counters has animated overlay builds: true
compositor scroll state has null prototype: true
compositor scroll state scrollNodes uses iframe Array: false
compositor scroll state scrollNodes uses top Array: true
diff --git a/Tests/LibWeb/Text/expected/Layout/table-box-containing-block-of-abspos-in-cell.txt b/Tests/LibWeb/Text/expected/Layout/table-box-containing-block-of-abspos-in-cell.txt
new file mode 100644
index 00000000000..af0dfbbe726
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Layout/table-box-containing-block-of-abspos-in-cell.txt
@@ -0,0 +1,3 @@
+cell: 30,50
+inset: 24,44
+static: 30,50
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-geometry-in-template-contents.txt b/Tests/LibWeb/Text/expected/SVG/svg-geometry-in-template-contents.txt
new file mode 100644
index 00000000000..b6a896efd54
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-geometry-in-template-contents.txt
@@ -0,0 +1,4 @@
+in a template's fragment: 10 4 true
+connected in the contents' document: 10 4 true
+the document element of the contents' document: 10 4 true
+in a window whose document has no document element: 0
diff --git a/Tests/LibWeb/Text/expected/SVG/svg-geometry-registered-random-custom-property.txt b/Tests/LibWeb/Text/expected/SVG/svg-geometry-registered-random-custom-property.txt
new file mode 100644
index 00000000000..b4e55c8a8f7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SVG/svg-geometry-registered-random-custom-property.txt
@@ -0,0 +1,2 @@
+outside the document: 10
+in a template's fragment: 10
diff --git a/Tests/LibWeb/Text/expected/ShadowDOM/specified-inherited-style-invalidates-shadow-tree.txt b/Tests/LibWeb/Text/expected/ShadowDOM/specified-inherited-style-invalidates-shadow-tree.txt
index 5c6c4353f78..79473b988bc 100644
--- a/Tests/LibWeb/Text/expected/ShadowDOM/specified-inherited-style-invalidates-shadow-tree.txt
+++ b/Tests/LibWeb/Text/expected/ShadowDOM/specified-inherited-style-invalidates-shadow-tree.txt
@@ -8,7 +8,7 @@ relative initial child font-size: 20px
relative changed child font-size: 40px
explicit inherit initial child margin-left: 11px
explicit inherit changed child margin-left: 27px
-PASS: explicit inherit only marks direct shadow-root children | elementStyleRecomputations=0, elementStyleNoopRecomputations=0
+PASS: explicit inherit only marks direct shadow-root children
descendant explicit inherit initial grandchild margin-left: 0px
descendant explicit inherit changed grandchild margin-left: 0px
-PASS: descendant explicit inherit does not mark all ancestors | elementStyleRecomputations=0, elementStyleNoopRecomputations=0
+PASS: descendant explicit inherit does not mark all ancestors
diff --git a/Tests/LibWeb/Text/expected/canvas/canvas-font-reads-settled-style-without-rematching.txt b/Tests/LibWeb/Text/expected/canvas/canvas-font-reads-settled-style-without-rematching.txt
index bb7ded1ad28..2bd055d8f05 100644
--- a/Tests/LibWeb/Text/expected/canvas/canvas-font-reads-settled-style-without-rematching.txt
+++ b/Tests/LibWeb/Text/expected/canvas/canvas-font-reads-settled-style-without-rematching.txt
@@ -1,6 +1,6 @@
fonts: 20px serif, 22px serif, 24px serif, 26px serif, 28px serif, 30px serif, 32px serif, 34px serif, 36px serif, 38px serif
-cold matching rows: 0
-full drives: 0
+passes == 0: true
+styled == 0: true
restyled: 50px serif
hidden: 60px serif
still hidden: 70px serif
diff --git a/Tests/LibWeb/Text/expected/complex-selector-queries-do-not-settle-style-input.txt b/Tests/LibWeb/Text/expected/complex-selector-queries-do-not-settle-style-input.txt
deleted file mode 100644
index a32d83ae013..00000000000
--- a/Tests/LibWeb/Text/expected/complex-selector-queries-do-not-settle-style-input.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-found: 0,1,2,3,4,5,6,7,8,9
-style inputs submitted by queries: 0
-last label color: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/animated-non-inherited-property-descendant-invalidation.txt b/Tests/LibWeb/Text/expected/css/animated-non-inherited-property-descendant-invalidation.txt
index d88254473c8..a8a2dd3d0cf 100644
--- a/Tests/LibWeb/Text/expected/css/animated-non-inherited-property-descendant-invalidation.txt
+++ b/Tests/LibWeb/Text/expected/css/animated-non-inherited-property-descendant-invalidation.txt
@@ -1,3 +1,3 @@
-plain descendants recomputed: false
-text-decoration-line inheritor recomputed: false
-transform inheritor recomputed: true
+plain descendants styled <= 0: true
+text-decoration-line inheritor styled: 1
+transform inheritor restyled: true
diff --git a/Tests/LibWeb/Text/expected/css/animation-events-of-many-siblings-in-tree-order.txt b/Tests/LibWeb/Text/expected/css/animation-events-of-many-siblings-in-tree-order.txt
new file mode 100644
index 00000000000..de330e921ae
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/animation-events-of-many-siblings-in-tree-order.txt
@@ -0,0 +1,4 @@
+events in tree order: true
+after moving the last element first: true
+walks of the tree are bounded: true
+walks of the tree after an attribute change: 0
diff --git a/Tests/LibWeb/Text/expected/css/attr-name-read-after-attributes-exist.txt b/Tests/LibWeb/Text/expected/css/attr-name-read-after-attributes-exist.txt
index b07726cb550..41834837c21 100644
--- a/Tests/LibWeb/Text/expected/css/attr-name-read-after-attributes-exist.txt
+++ b/Tests/LibWeb/Text/expected/css/attr-name-read-after-attributes-exist.txt
@@ -1,4 +1,3 @@
before: rgb(1, 2, 3) rgb(1, 2, 3)
-engine computed the readers: true
sheet: rgb(0, 128, 0) rgb(128, 0, 128)
changed: rgb(255, 0, 0) rgb(128, 0, 128)
diff --git a/Tests/LibWeb/Text/expected/css/child-change-no-op-invalidation-counters.txt b/Tests/LibWeb/Text/expected/css/child-change-no-op-invalidation-counters.txt
index 911654bb145..483db7e63f3 100644
--- a/Tests/LibWeb/Text/expected/css/child-change-no-op-invalidation-counters.txt
+++ b/Tests/LibWeb/Text/expected/css/child-change-no-op-invalidation-counters.txt
@@ -1,3 +1,3 @@
-appending a child to a parent without observable child-state pseudos: 0 recomputations
-removing the only child from a parent without observable child-state pseudos: 0 recomputations
-appending a fragment to a parent without observable child-state pseudos: 0 recomputations
+appending a child to a parent without observable child-state pseudos: styled <= 1: true
+removing the only child from a parent without observable child-state pseudos: styled <= 0: true
+appending a fragment to a parent without observable child-state pseudos: styled <= 2: true
diff --git a/Tests/LibWeb/Text/expected/css/computed-values-group-sharing.txt b/Tests/LibWeb/Text/expected/css/computed-values-group-sharing.txt
index 4e4874ff120..fd4b2f38ba1 100644
--- a/Tests/LibWeb/Text/expected/css/computed-values-group-sharing.txt
+++ b/Tests/LibWeb/Text/expected/css/computed-values-group-sharing.txt
@@ -6,18 +6,17 @@ unstyled child anchor at default: true
unstyled child content at default: true
unstyled child transform at default: true
unstyled child effects at default: true
-unstyled child inheritedTable at default: true
-unstyled child inheritedList at default: true
+unstyled child inheritedListTable at default: true
unstyled child inheritedSVG at default: true
color-styled child inheritedText at default: false
color-styled child inheritedText shared with parent: false
color-styled child grid still at default: true
grid-styled child grid at default: false
-unstyled-again child inheritedList shared with parent: true
+unstyled-again child inheritedListTable shared with parent: true
unstyled-again child inheritedText shared with parent: true
unstyled-again child font shared with parent: true
-unstyled-again child inheritedBox shared with parent: true
unstyled-again child inheritedUI shared with parent: true
-writing-mode parent: child inheritedBox at default: false
-writing-mode parent: child inheritedBox shared with parent: true
-visibility-overriding child inheritedBox shared with parent: false
+writing-mode parent: child writing-mode: vertical-rl
+writing-mode parent: child visibility: hidden
+visibility-overriding child visibility: visible
+visibility-overriding child writing-mode: vertical-rl
diff --git a/Tests/LibWeb/Text/expected/css/custom-property-animation-setting-display.txt b/Tests/LibWeb/Text/expected/css/custom-property-animation-setting-display.txt
index 06451906a4e..75416c5f875 100644
--- a/Tests/LibWeb/Text/expected/css/custom-property-animation-setting-display.txt
+++ b/Tests/LibWeb/Text/expected/css/custom-property-animation-setting-display.txt
@@ -1,5 +1,6 @@
rgb(0, 0, 0)
rgb(0, 0, 0)
+none, 1 animation
rgb(0, 0, 0)
rgb(0, 0, 0)
rgb(0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/focus-state-in-blur-handler.txt b/Tests/LibWeb/Text/expected/css/focus-state-in-blur-handler.txt
new file mode 100644
index 00000000000..d58f470edcf
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/focus-state-in-blur-handler.txt
@@ -0,0 +1,10 @@
+focused: first rgb(0, 128, 0), wrapper rgb(0, 128, 0), second rgb(255, 0, 0)
+in blur: active BODY, first false, wrapper false
+in blur: first rgb(255, 0, 0), wrapper rgb(255, 0, 0), second rgb(255, 0, 0)
+moved: first rgb(255, 0, 0), wrapper rgb(255, 0, 0), second rgb(0, 128, 0)
+blurred: first rgb(255, 0, 0), wrapper rgb(255, 0, 0), second rgb(255, 0, 0)
+keeper in blur: false, target none
+keeper: active target, target block
+in blur: active BODY, first false, wrapper false
+in blur: first rgb(255, 0, 0), wrapper rgb(255, 0, 0), second rgb(255, 0, 0)
+moved back: active first, first rgb(0, 128, 0), wrapper rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/font-face-weight-specific-invalidation.txt b/Tests/LibWeb/Text/expected/css/font-face-weight-specific-invalidation.txt
index 443424d25ae..f4cec3a38c5 100644
--- a/Tests/LibWeb/Text/expected/css/font-face-weight-specific-invalidation.txt
+++ b/Tests/LibWeb/Text/expected/css/font-face-weight-specific-invalidation.txt
@@ -1,4 +1,3 @@
affected weight recomputed: true
unaffected weights skipped: true
-affected weight computed by the style engine: true
regular face loaded: loaded
diff --git a/Tests/LibWeb/Text/expected/css/inherited-custom-property-change-reuses-shared-styles.txt b/Tests/LibWeb/Text/expected/css/inherited-custom-property-change-reuses-shared-styles.txt
index 099f84fe666..c8d71c5a842 100644
--- a/Tests/LibWeb/Text/expected/css/inherited-custom-property-change-reuses-shared-styles.txt
+++ b/Tests/LibWeb/Text/expected/css/inherited-custom-property-change-reuses-shared-styles.txt
@@ -1,3 +1,5 @@
margin after change: 2px
every child keeps its own margin: true
-children keep their styles: true
+every child inherits the new theme: true
+styled at most 1: true
+children compute no record of their own past the first: true
diff --git a/Tests/LibWeb/Text/expected/css/insert-rule-keyframes-shadow-host-invalidation-counters.txt b/Tests/LibWeb/Text/expected/css/insert-rule-keyframes-shadow-host-invalidation-counters.txt
index 8f6e23def41..539a5a4d3bb 100644
--- a/Tests/LibWeb/Text/expected/css/insert-rule-keyframes-shadow-host-invalidation-counters.txt
+++ b/Tests/LibWeb/Text/expected/css/insert-rule-keyframes-shadow-host-invalidation-counters.txt
@@ -1 +1 @@
-PASS: bare :host keyframes insertRule only recomputes the host
+bare :host keyframes insertRule only restyles the host, styled <= 2: true
diff --git a/Tests/LibWeb/Text/expected/css/invisible-animation-style-throttling.txt b/Tests/LibWeb/Text/expected/css/invisible-animation-style-throttling.txt
index 2fb84a18acb..18cde6cbcb6 100644
--- a/Tests/LibWeb/Text/expected/css/invisible-animation-style-throttling.txt
+++ b/Tests/LibWeb/Text/expected/css/invisible-animation-style-throttling.txt
@@ -2,7 +2,7 @@ hidden animation overlay builds: 0
hidden animation frame pump requests: 0
animation event listener uses iteration wake-ups: true
animation event listener skips past events: 0
-removing animation event listener stops frame pump: 0
+removing animation event listener stops frame pump: 1
computed style samples hidden animation: true
offscreen clipped animation overlay builds: 0
offscreen clipped animation frame pump requests: 0
diff --git a/Tests/LibWeb/Text/expected/css/shadow-media-query-invalidation-stays-scoped.txt b/Tests/LibWeb/Text/expected/css/shadow-media-query-invalidation-stays-scoped.txt
index 9901c26fb24..1b6944ccd79 100644
--- a/Tests/LibWeb/Text/expected/css/shadow-media-query-invalidation-stays-scoped.txt
+++ b/Tests/LibWeb/Text/expected/css/shadow-media-query-invalidation-stays-scoped.txt
@@ -1,2 +1,2 @@
Target color: rgb(0, 128, 0)
-PASS: shadow media query update stayed scoped (0 recomputations)
+shadow media query update stays scoped, styled <= 15: true
diff --git a/Tests/LibWeb/Text/expected/css/shadow-root-host-light-dom-trailing-universal-invalidation.txt b/Tests/LibWeb/Text/expected/css/shadow-root-host-light-dom-trailing-universal-invalidation.txt
index 7d81355bf68..7dce8ada97b 100644
--- a/Tests/LibWeb/Text/expected/css/shadow-root-host-light-dom-trailing-universal-invalidation.txt
+++ b/Tests/LibWeb/Text/expected/css/shadow-root-host-light-dom-trailing-universal-invalidation.txt
@@ -1,6 +1,6 @@
-PASS: host child combinator add keeps work scoped
-PASS: host descendant combinator add keeps work scoped
-PASS: broad host-side stylesheet add avoids document-wide work
-PASS: broad host-side sibling escape avoids root-side work
-PASS: broad functional host-side selector avoids document-wide work
-PASS: broad functional host-side sibling escape avoids root-side work
+host child combinator add keeps work scoped: color unchanged true, styled < 10: true
+host descendant combinator add keeps work scoped: color unchanged true, styled < 10: true
+broad host-side stylesheet add avoids document-wide work: color unchanged true, styled < 10: true
+broad host-side sibling escape avoids root-side work: color unchanged true, styled < 10: true
+broad functional host-side selector avoids document-wide work: color unchanged true, styled < 10: true
+broad functional host-side sibling escape avoids root-side work: color unchanged true, styled < 10: true
diff --git a/Tests/LibWeb/Text/expected/css/shadow-root-keyframes-shadow-local-invalidation-counters.txt b/Tests/LibWeb/Text/expected/css/shadow-root-keyframes-shadow-local-invalidation-counters.txt
index 581eed58ce3..0b6988b2246 100644
--- a/Tests/LibWeb/Text/expected/css/shadow-root-keyframes-shadow-local-invalidation-counters.txt
+++ b/Tests/LibWeb/Text/expected/css/shadow-root-keyframes-shadow-local-invalidation-counters.txt
@@ -1 +1 @@
-PASS: shadow-local keyframes insert ignores matching light-DOM bystanders (at most 4 recomputations)
+shadow-local keyframes insert ignores matching light-DOM bystanders, styled <= 4: true
diff --git a/Tests/LibWeb/Text/expected/css/shadow-root-layer-order-shadow-local-invalidation.txt b/Tests/LibWeb/Text/expected/css/shadow-root-layer-order-shadow-local-invalidation.txt
index 0c939cec536..f9ec7a0c37a 100644
--- a/Tests/LibWeb/Text/expected/css/shadow-root-layer-order-shadow-local-invalidation.txt
+++ b/Tests/LibWeb/Text/expected/css/shadow-root-layer-order-shadow-local-invalidation.txt
@@ -1,2 +1,2 @@
-PASS: shadow-local layer-order add stays inside the shadow root (at most 4 recomputations)
-PASS: shadow-local layer-order remove stays inside the shadow root (at most 4 recomputations)
+shadow-local layer-order add stays inside the shadow root, styled <= 4: true
+shadow-local layer-order remove stays inside the shadow root, styled <= 4: true
diff --git a/Tests/LibWeb/Text/expected/css/shadow-root-replacesync-shadow-local-invalidation-counters.txt b/Tests/LibWeb/Text/expected/css/shadow-root-replacesync-shadow-local-invalidation-counters.txt
index 80fe452545b..c5daccabbbd 100644
--- a/Tests/LibWeb/Text/expected/css/shadow-root-replacesync-shadow-local-invalidation-counters.txt
+++ b/Tests/LibWeb/Text/expected/css/shadow-root-replacesync-shadow-local-invalidation-counters.txt
@@ -1,3 +1,3 @@
-PASS: shadow-local replaceSync ignores matching light-DOM bystanders (at most 2 recomputations)
-PASS: shadow-local replaceSync stays bounded on subsequent updates (at most 2 recomputations)
-PASS: shadow-local replaceSync clearing the sheet stays bounded (at most 2 recomputations)
+shadow-local replaceSync ignores matching light-DOM bystanders, styled <= 2: true
+shadow-local replaceSync stays bounded on subsequent updates, styled <= 2: true
+shadow-local replaceSync clearing the sheet stays bounded, styled <= 2: true
diff --git a/Tests/LibWeb/Text/expected/css/shadow-root-replacesync-slot-only-invalidation-counters.txt b/Tests/LibWeb/Text/expected/css/shadow-root-replacesync-slot-only-invalidation-counters.txt
index 609603d18a4..e3ad88b3ebb 100644
--- a/Tests/LibWeb/Text/expected/css/shadow-root-replacesync-slot-only-invalidation-counters.txt
+++ b/Tests/LibWeb/Text/expected/css/shadow-root-replacesync-slot-only-invalidation-counters.txt
@@ -1,2 +1,2 @@
-PASS: slot-only replaceSync stays scoped to the current host subtree
-PASS: slot-only replaceSync removal stays scoped to the current host subtree
+slot-only replaceSync stays scoped to the current host subtree, styled <= 4: true
+slot-only replaceSync removal stays scoped to the current host subtree, styled <= 4: true
diff --git a/Tests/LibWeb/Text/expected/css/shadow-root-slot-style-add-remove-invalidation-counters.txt b/Tests/LibWeb/Text/expected/css/shadow-root-slot-style-add-remove-invalidation-counters.txt
index 75067472aa9..8d5e999c71d 100644
--- a/Tests/LibWeb/Text/expected/css/shadow-root-slot-style-add-remove-invalidation-counters.txt
+++ b/Tests/LibWeb/Text/expected/css/shadow-root-slot-style-add-remove-invalidation-counters.txt
@@ -1,2 +1,2 @@
-PASS: slotted stylesheet add ignores matching bystanders outside the current host
-PASS: slotted stylesheet remove ignores matching bystanders outside the current host
+slotted stylesheet add ignores matching bystanders outside the current host, styled <= 4: true
+slotted stylesheet remove ignores matching bystanders outside the current host, styled <= 4: true
diff --git a/Tests/LibWeb/Text/expected/css/shadow-root-stylesheet-add-remove-shadow-local-invalidation-counters.txt b/Tests/LibWeb/Text/expected/css/shadow-root-stylesheet-add-remove-shadow-local-invalidation-counters.txt
index fcf2a43bf14..18f114cb226 100644
--- a/Tests/LibWeb/Text/expected/css/shadow-root-stylesheet-add-remove-shadow-local-invalidation-counters.txt
+++ b/Tests/LibWeb/Text/expected/css/shadow-root-stylesheet-add-remove-shadow-local-invalidation-counters.txt
@@ -1,2 +1,2 @@
-PASS: shadow-local stylesheet add ignores matching light-DOM bystanders (at most 4 recomputations)
-PASS: shadow-local stylesheet remove ignores matching light-DOM bystanders (at most 4 recomputations)
+shadow-local stylesheet add ignores matching light-DOM bystanders, styled <= 4: true
+shadow-local stylesheet remove ignores matching light-DOM bystanders, styled <= 4: true
diff --git a/Tests/LibWeb/Text/expected/css/shared-style-sheet-copy-on-write.txt b/Tests/LibWeb/Text/expected/css/shared-style-sheet-copy-on-write.txt
index e19e759d54e..528cad5ab8f 100644
--- a/Tests/LibWeb/Text/expected/css/shared-style-sheet-copy-on-write.txt
+++ b/Tests/LibWeb/Text/expected/css/shared-style-sheet-copy-on-write.txt
@@ -1,7 +1,4 @@
-first edit compiles private contents: 3
first edit: rgb(255, 0, 0), rgb(0, 128, 0)
-later insertion compiles one rule: 1
later insertion: rgb(0, 128, 0), rgb(0, 128, 0)
-later declaration edit compiles no rules: 0
later declaration edit: rgb(0, 0, 255), rgb(0, 128, 0)
second sheet outlives first: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-attribute-no-op-invalidation-counters.txt b/Tests/LibWeb/Text/expected/css/style-attribute-no-op-invalidation-counters.txt
index 0b470866fbd..7bf922da36b 100644
--- a/Tests/LibWeb/Text/expected/css/style-attribute-no-op-invalidation-counters.txt
+++ b/Tests/LibWeb/Text/expected/css/style-attribute-no-op-invalidation-counters.txt
@@ -1,4 +1,4 @@
-setting identical style text: 0 recomputations, 0 engine records
-setting changed style text: 0 recomputations, 1 engine records
-setting identical custom property: 0 recomputations, 0 engine records
-setting changed custom property: 0 recomputations, 2 engine records
+setting identical style text, styled <= 0: true
+setting changed style text, styled <= 1: true
+setting identical custom property, styled <= 0: true
+setting changed custom property, styled <= 2: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animated-element-pseudo-elements.txt b/Tests/LibWeb/Text/expected/css/style-engine/animated-element-pseudo-elements.txt
index db298fb88a0..9a967cf32e3 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/animated-element-pseudo-elements.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/animated-element-pseudo-elements.txt
@@ -1,3 +1,2 @@
-C++ recomputations: 0
height: 7px
::before color: rgb(100, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animated-row-moves-declarations.txt b/Tests/LibWeb/Text/expected/css/style-engine/animated-row-moves-declarations.txt
index 9c0a85ef361..72b63497205 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/animated-row-moves-declarations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/animated-row-moves-declarations.txt
@@ -1,6 +1,4 @@
before: 20px 5px 20px, child 20px rgb(0, 0, 255)
-beside the animation: C++ recomputations 0
beside the animation: 20px 7px 20px, child 20px rgb(0, 128, 0)
-retimed: C++ recomputations 0
retimed: 15px 7px 15px, child 15px rgb(0, 128, 0)
duration: 2000000
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animated-style-group-overlay.txt b/Tests/LibWeb/Text/expected/css/style-engine/animated-style-group-overlay.txt
index 745e74dd72d..b75b09b7853 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/animated-style-group-overlay.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/animated-style-group-overlay.txt
@@ -3,6 +3,3 @@ background: rgb(0, 0, 255)
opacity: 0.5
color: rgb(100, 0, 0)
border color: rgb(100, 0, 0)
-reconstruction fallbacks: none
-overlay builds: some
-full builds: none
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animated-style-overlay-lifetime.txt b/Tests/LibWeb/Text/expected/css/style-engine/animated-style-overlay-lifetime.txt
deleted file mode 100644
index 8000b98e63d..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/animated-style-overlay-lifetime.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-permanent style records added: 0
-permanent metadata added: 0
-overlay slots added: 1
-overlay records updated: 9
-live overlay records: 1
-overlay slots released: 1
-live overlays after removal: 0
-animated pseudo-element style survives removal
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animated-style-overlay-with-box-updates-in-place.txt b/Tests/LibWeb/Text/expected/css/style-engine/animated-style-overlay-with-box-updates-in-place.txt
deleted file mode 100644
index 73b1c943db5..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/animated-style-overlay-with-box-updates-in-place.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-overlay slots added: 1
-overlay records updated: 9
-live overlay records: 1
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animation-first-record-inherited-keyframes.txt b/Tests/LibWeb/Text/expected/css/style-engine/animation-first-record-inherited-keyframes.txt
index 183a65b1c62..5e575ce6170 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/animation-first-record-inherited-keyframes.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/animation-first-record-inherited-keyframes.txt
@@ -1,4 +1,4 @@
-inherited keyframes: C++ recomputations 0, animations tint, target rgb(100, 50, 0), child rgb(100, 50, 0)
-sibling-index() keyframes: C++ recomputations 0, animations grow-by-index, width 30px
-url() keyframes: C++ recomputations 0, animations picture, background-image true
-keyframe custom property: C++ recomputations 0, animations vary, child width 17px
+inherited keyframes: animations tint, target rgb(100, 50, 0), child rgb(100, 50, 0)
+sibling-index() keyframes: animations grow-by-index, width 30px
+url() keyframes: animations picture, background-image true
+keyframe custom property: animations vary, child width 17px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animation-list-from-settled-record.txt b/Tests/LibWeb/Text/expected/css/style-engine/animation-list-from-settled-record.txt
index 3961de7d9b3..0263c631a5c 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/animation-list-from-settled-record.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/animation-list-from-settled-record.txt
@@ -1,5 +1,4 @@
before: 100px
-C++ recomputations: 0
after: 20px 0.25
names: grow,fade
durations: 1000000,1000000
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animation-name-of-sheet-adopted-by-several-scopes.txt b/Tests/LibWeb/Text/expected/css/style-engine/animation-name-of-sheet-adopted-by-several-scopes.txt
index 80d573a0270..9044374dd78 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/animation-name-of-sheet-adopted-by-several-scopes.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/animation-name-of-sheet-adopted-by-several-scopes.txt
@@ -1,3 +1,2 @@
-C++ recomputations: 0
normal: 10px
important: 20px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animation-name-rolled-back-plans-in-engine.txt b/Tests/LibWeb/Text/expected/css/style-engine/animation-name-rolled-back-plans-in-engine.txt
index fee0e3a30e3..754e69c5b70 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/animation-name-rolled-back-plans-in-engine.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/animation-name-rolled-back-plans-in-engine.txt
@@ -1,2 +1,2 @@
-step 1: animations 0, C++ recomputations 0
-step 2: animations 1, C++ recomputations 0
+step 1: animations 0
+step 2: animations 1
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animation-name-shadow-scopes.txt b/Tests/LibWeb/Text/expected/css/style-engine/animation-name-shadow-scopes.txt
index 8d3facb6911..dc92a013259 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/animation-name-shadow-scopes.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/animation-name-shadow-scopes.txt
@@ -1,4 +1,4 @@
-document element: C++ recomputations 0, width 100px, animations 1
-shadow tree element: C++ recomputations 0, width 7px, animations 1
-:host rule: C++ recomputations 0, width 9px, animations 1
-adopted sheet element: C++ recomputations 0, width 13px, animations 1
+document element: width 100px, animations 1
+shadow tree element: width 7px, animations 1
+:host rule: width 9px, animations 1
+adopted sheet element: width 13px, animations 1
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animation-starts-when-hidden-subtree-is-revealed.txt b/Tests/LibWeb/Text/expected/css/style-engine/animation-starts-when-hidden-subtree-is-revealed.txt
index e474933ef89..6a8f00ea904 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/animation-starts-when-hidden-subtree-is-revealed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/animation-starts-when-hidden-subtree-is-revealed.txt
@@ -1,6 +1,5 @@
first, under display:none from the start: 0 animation(s)
second, shown: 1 animation(s), grow
second, hidden: 0 animation(s)
-C++ recomputations: 0
first, revealed: 1 animation(s), grow
second, revealed: 1 animation(s), grow
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/animation-underlying-style-delta.txt b/Tests/LibWeb/Text/expected/css/style-engine/animation-underlying-style-delta.txt
index cb5acc723bf..93ae0d6d6d5 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/animation-underlying-style-delta.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/animation-underlying-style-delta.txt
@@ -1,4 +1,3 @@
-base change takes partial drive: true
animation object survives: true
sampled color: rgb(50, 50, 50)
sampled opacity: 0.5
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/arrival-routing-beyond-the-subtree.txt b/Tests/LibWeb/Text/expected/css/style-engine/arrival-routing-beyond-the-subtree.txt
index 11b85168c59..06ade03571c 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/arrival-routing-beyond-the-subtree.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/arrival-routing-beyond-the-subtree.txt
@@ -1,4 +1,4 @@
-an arrival moves which sibling is the second `.a`: [one, two, zero]
-an arrival is the left side of a sibling selector: [after, later, trigger]
+an arrival moves which sibling is the second `.a`: [zero, one, two]
+an arrival is the left side of a sibling selector: [trigger, after, later]
an arrival witnesses a relational query above it: [outer, witness]
a host arrives with its shadow tree already built: [host, style, inner]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-pseudo-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-pseudo-engine-computed.txt
deleted file mode 100644
index de8c75a7258..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-pseudo-engine-computed.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-computation stays in the engine: true
-colors: rgb(0, 128, 0) rgb(128, 0, 128)
-attribute change stays in the engine: true
-colors: rgb(255, 0, 0) rgb(128, 0, 128)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/backdrop-read-outside-top-layer.txt b/Tests/LibWeb/Text/expected/css/style-engine/backdrop-read-outside-top-layer.txt
index 673650cc430..05d4a076b36 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/backdrop-read-outside-top-layer.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/backdrop-read-outside-top-layer.txt
@@ -1,3 +1,3 @@
-never shown: --own backdrop, color rgb(0, 128, 0), demands left to the host 0
-modal: --own backdrop, color rgb(0, 128, 0), demands left to the host 0
-closed: --own backdrop, color rgb(0, 128, 0), demands left to the host 0
+never shown: --own backdrop, color rgb(0, 128, 0)
+modal: --own backdrop, color rgb(0, 128, 0)
+closed: --own backdrop, color rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/backing-element-selection-records.txt b/Tests/LibWeb/Text/expected/css/style-engine/backing-element-selection-records.txt
index e0a5e3855f8..e6d5e8b75fd 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/backing-element-selection-records.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/backing-element-selection-records.txt
@@ -1,2 +1 @@
selection: rgb(255, 0, 0)
-engine pseudo records: 4
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/boxless-pseudo-element-read-custom-properties.txt b/Tests/LibWeb/Text/expected/css/style-engine/boxless-pseudo-element-read-custom-properties.txt
index 0bdf0927c1e..21976e804d3 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/boxless-pseudo-element-read-custom-properties.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/boxless-pseudo-element-read-custom-properties.txt
@@ -1,3 +1,2 @@
::before: --own pseudo, --inherited element, color rgb(0, 128, 0)
::after: --own element after, --inherited element, color rgb(0, 0, 0)
-demands left to the host: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cascade-topology-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/cascade-topology-mutations.txt
index de29db6563e..d9d39f10972 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/cascade-topology-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/cascade-topology-mutations.txt
@@ -1,5 +1,5 @@
-move a sheet after the one it overlaps: [first, item]
-move it back in front: [first, item]
+move a sheet after the one it overlaps: [item]
+move it back in front: [item]
adopt two overlapping sheets: [item]
swap their order: [item]
unadopt both: [item]
@@ -9,13 +9,13 @@ make a layered declaration important: [item]
make it normal again: [item]
insert an empty layer block: []
delete the empty layer: []
-insert nested layers with overlapping rules: [item]
-delete the nested layer: [item]
-insert a layered rule behind a matching condition: [item]
+insert nested layers with overlapping rules: []
+delete the nested layer: []
+insert a layered rule behind a matching condition: []
delete the gated layer: []
move a sheet out of the document: [item]
-put it back at the front: [second, item]
+put it back at the front: []
move a shadow sheet past the one it overlaps: [inner, inner-first]
declare layers inside the shadow root: []
-put the shadow layers in the other order: [inner]
-append a sheet that is already last: [first, item]
+put the shadow layers in the other order: []
+append a sheet that is already last: []
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/child-combinator-rule-bounded-to-its-shadow-tree.txt b/Tests/LibWeb/Text/expected/css/style-engine/child-combinator-rule-bounded-to-its-shadow-tree.txt
index 7d761addf1a..f35fcf714b1 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/child-combinator-rule-bounded-to-its-shadow-tree.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/child-combinator-rule-bounded-to-its-shadow-tree.txt
@@ -1,5 +1,5 @@
li > div > :focus: 0
-li > div > *: 0
+li > div > *: 1
li :focus: 0
before focus: rgb(0, 0, 0)
after focus: rgb(1, 2, 3)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/children-reactions-in-parent-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/children-reactions-in-parent-batch.txt
deleted file mode 100644
index 566900eefc3..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/children-reactions-in-parent-batch.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-children inside the batch: transactions 1, engine records 3, C++ recomputations 0
- first: color rgb(0, 128, 0), width 20px
- second: color rgb(0, 128, 0), width 20px
-children inside and outside the batch: transactions 2, engine records 3, C++ recomputations 0
- first: color rgb(0, 0, 0), width 784px
- second: color rgb(0, 0, 0), width 20px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cold-record-retries-after-materialized-parent.txt b/Tests/LibWeb/Text/expected/css/style-engine/cold-record-retries-after-materialized-parent.txt
deleted file mode 100644
index d5b908059c0..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/cold-record-retries-after-materialized-parent.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-engine records: 3
-C++ recomputations: 0
-color: rgb(255, 0, 0)
-font size: 20px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-closure-after-style-sharing.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-closure-after-style-sharing.txt
index d5da7ea7251..4dd49c73aaa 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/computed-closure-after-style-sharing.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/computed-closure-after-style-sharing.txt
@@ -1,4 +1,4 @@
shared initial style: true
-longhand evaluations: 0
+styled only the changed element: true
first background: rgba(0, 0, 0, 0)
second background: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-color-scheme-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-color-scheme-closure.txt
index 37cd65c07ad..312269f618a 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/computed-color-scheme-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/computed-color-scheme-closure.txt
@@ -1,3 +1,2 @@
-color scheme longhand evaluations: 0
background: rgb(0, 0, 0)
inherited background: rgb(0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-current-color-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-current-color-closure.txt
index 357fc67a416..0cab431570c 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/computed-current-color-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/computed-current-color-closure.txt
@@ -1,3 +1,2 @@
-currentColor longhand evaluations: 0
color: rgb(0, 0, 255)
border color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-font-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-font-closure.txt
index a59b54a0961..348b3a76af1 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/computed-font-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/computed-font-closure.txt
@@ -1,3 +1,2 @@
-font change longhand evaluations: 0
font size: 20px
font-relative margin: 40px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-group-identities.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-group-identities.txt
deleted file mode 100644
index 20898f88954..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/computed-group-identities.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-computed group handles cover the elements: true
-computed group sets are shared: 147
-computed groups are shared: 3441
-inherited group handles cover the elements: true
-inherited group sets are shared: 149
-custom property handles cover the elements: true
-custom property environments are shared: 148
-computed fixed metadata handles cover the elements: true
-computed fixed metadata tuples are shared: true
-base style record handles cover the elements: true
-base style records are shared: 147
-pseudo assignments are published sparsely: true
-custom property environments survive transaction boundaries: true
-pseudo assignments are removed sparsely: true
-ordinary item: rgb(20, 24, 28)
-distinct non-inherited item: rgb(60, 64, 68)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-logical-mapping-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-logical-mapping-closure.txt
index 76134101d06..7ce24fe253c 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/computed-logical-mapping-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/computed-logical-mapping-closure.txt
@@ -1,5 +1,4 @@
left margin: 20px
right margin: 10px
top margin: 10px
-margin family longhand evaluations: 10
changed logical margin: 30px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-output-key-stops.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-output-key-stops.txt
index 08516dc3ddb..f1d152c7cf4 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/computed-output-key-stops.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/computed-output-key-stops.txt
@@ -1,5 +1 @@
-specified winner changed: true
-equal computed group canonicalized: true
-computed output stopped propagation: true
-computed group handle stayed equal: true
computed margin: 96px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-record-reclamation.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-record-reclamation.txt
deleted file mode 100644
index 9a3e97b1353..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/computed-record-reclamation.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-first sweep found unreachable groups: true
-second sweep found unreachable groups: true
-reclaimed group slots stay bounded: true
-current style survives reclamation: true
-stale input record survives reclamation: true
-style derived after reclamation: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-style-record-view-pins.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-style-record-view-pins.txt
deleted file mode 100644
index aa9f4fd32a9..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/computed-style-record-view-pins.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-initial layout record view pins unchanged: true
-style update record view pins unchanged: true
-computed style record view pins increased: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/computed-winner-group-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/computed-winner-group-closure.txt
index e0fb13ba26c..968d8780ac8 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/computed-winner-group-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/computed-winner-group-closure.txt
@@ -1,8 +1,5 @@
-winner closure longhand evaluations: 0
changed value: 0.5
unchanged value: rgb(0, 128, 0)
-independent leaf evaluations: 0
independent leaf opacity: 0.75
independent leaf background: rgb(0, 0, 255)
-mixed leaf and logical evaluations: 0
logical value: 20px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/connected-selector-query-leaves-pending-input.txt b/Tests/LibWeb/Text/expected/css/style-engine/connected-selector-query-leaves-pending-input.txt
index 9f8c4856409..2d3db69b813 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/connected-selector-query-leaves-pending-input.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/connected-selector-query-leaves-pending-input.txt
@@ -1,8 +1,8 @@
querySelector observes mutation: true
-querySelector leaves style input pending: true
-querySelectorAll leaves style input pending: true
-matches leaves style input pending: true
-closest leaves style input pending: true
+querySelector observes another mutation: true
+querySelectorAll observes mutation: true
+matches observes mutation: true
+closest observes mutation: true
connected query preserves pending style update: true
detached querySelector initial: true
detached querySelector sees attribute mutation: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/connected-subtree-common-class-fanout.txt b/Tests/LibWeb/Text/expected/css/style-engine/connected-subtree-common-class-fanout.txt
deleted file mode 100644
index b13aae72e04..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/connected-subtree-common-class-fanout.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-no-op reactions suppressed: true
-none animation names remain shareable: true
-inserted elements were styled: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/container-computed-in-same-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/container-computed-in-same-batch.txt
index 76a01c834b9..362a8c8201a 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/container-computed-in-same-batch.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/container-computed-in-same-batch.txt
@@ -1 +1 @@
-C++ recomputations 0, gated 10px, function 20px
+gated 10px, function 20px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/container-length-record-admission.txt b/Tests/LibWeb/Text/expected/css/style-engine/container-length-record-admission.txt
index 80884d9b5b6..7f05b5447d7 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/container-length-record-admission.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/container-length-record-admission.txt
@@ -1,4 +1,4 @@
initial: 1px, 1px
-direct: value refusals 0, C++ recomputations 0, widths 40px, 60px
-mixed: value refusals 0, C++ recomputations 0, widths 2px, 6px
+direct: widths 40px, 60px
+mixed: widths 2px, 6px
resized: 2.5px, 6px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/content-and-anchor-name-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/content-and-anchor-name-engine-computed.txt
deleted file mode 100644
index 4eff9cc7b71..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/content-and-anchor-name-engine-computed.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-image content, first record: property refusals 0, value refusals 0, C++ recomputations 0, value an image
-counter(x, decimal), first record: property refusals 0, value refusals 0, C++ recomputations 0, value counter(x)
-named @counter-style, first record: property refusals 0, value refusals 0, C++ recomputations 0, value counter(x, thumbs)
-content flip, first record: property refusals 0, value refusals 0, C++ recomputations 0, value none
-list-style-type, first record: property refusals 0, value refusals 0, C++ recomputations 0, value thumbs
-anchor-name, first record: property refusals 0, value refusals 0, C++ recomputations 0, value --anchor
-anchor-name on ::before, first record: property refusals 0, value refusals 0, C++ recomputations 0, value --anchor
-image content, warm record: property refusals 0, value refusals 0, C++ recomputations 0, value an image
-counter(x, decimal), warm record: property refusals 0, value refusals 0, C++ recomputations 0, value counter(x)
-named @counter-style, warm record: property refusals 0, value refusals 0, C++ recomputations 0, value counter(x, thumbs)
-content flip, warm record: property refusals 0, value refusals 0, C++ recomputations 0, value none
-list-style-type, warm record: property refusals 0, value refusals 0, C++ recomputations 0, value thumbs
-anchor-name, warm record: property refusals 0, value refusals 0, C++ recomputations 0, value --anchor
-anchor-name on ::before, warm record: property refusals 0, value refusals 0, C++ recomputations 0, value --anchor
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/converging-style-input-shares-style.txt b/Tests/LibWeb/Text/expected/css/style-engine/converging-style-input-shares-style.txt
index 3f6c0a52fbd..377565ca4ff 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/converging-style-input-shares-style.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/converging-style-input-shares-style.txt
@@ -1,3 +1,2 @@
shared converging style: true
-shared style transition damage: true
colors became green: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-change-does-not-restyle-children.txt b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-change-does-not-restyle-children.txt
index 1e6e2f5d783..3f179cd35a4 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-change-does-not-restyle-children.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-change-does-not-restyle-children.txt
@@ -1,6 +1,5 @@
elements: 25
-records computed: 23
-C++ recomputations: 0
-transactions: 1
+styled: 10, full passes: 0
+rebuilding the boxes restyles nothing again: true
marker rebuilt: true
generated content rebuilt: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-change-spares-unrelated-records.txt b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-change-spares-unrelated-records.txt
index 6494df81bd1..fd6311240ab 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-change-spares-unrelated-records.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-change-spares-unrelated-records.txt
@@ -1,4 +1,3 @@
-an engine-computed record was published: true
plain received a new style record: true
plain color: rgb(0, 128, 0)
item color: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-observer-identity.txt b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-observer-identity.txt
deleted file mode 100644
index 84f69308bcd..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-observer-identity.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-environment unchanged: true
-computed content stayed equal: true
-observer metadata changed: true
-style record changed: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-records-shared-per-scope.txt b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-records-shared-per-scope.txt
index 6625af3a93e..dc2bb22bc8d 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-records-shared-per-scope.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-records-shared-per-scope.txt
@@ -1,4 +1,3 @@
-consumer records shared: 8
first scope's consumers share a record: true
second scope's consumers share a record: true
scopes' consumers hold different records: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-root-preparation.txt b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-root-preparation.txt
index 6c62f6f3fec..ff15e21ac15 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-root-preparation.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-root-preparation.txt
@@ -1,2 +1 @@
-root font prepared: true
plain width: 40px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-shared-record-mutation.txt b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-shared-record-mutation.txt
index c5d786c8271..43c46755393 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/counter-style-shared-record-mutation.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/counter-style-shared-record-mutation.txt
@@ -1,7 +1,3 @@
-initial consumers answered by engine: true
-initial C++ recomputations: 0
all shared consumers update: true
-counter-style consumers answered by engine: true
all shared consumers restore: true
-records were shared: true
counter content consumer updates: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cssom-program-input-precision.txt b/Tests/LibWeb/Text/expected/css/style-engine/cssom-program-input-precision.txt
index dc8d3d66c16..f51bdd1fd0d 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/cssom-program-input-precision.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/cssom-program-input-precision.txt
@@ -1,45 +1,30 @@
-repeat layers environment changed: false
-repeat layers topology changed: false
+repeat layers styled <= 0: true
repeat layers colors: rgb(0, 0, 255), rgb(0, 0, 255)
-remove repeated layers environment changed: false
-remove repeated layers topology changed: false
+remove repeated layers styled <= 0: true
remove repeated layers colors: rgb(0, 0, 255), rgb(0, 0, 255)
-reorder layers environment changed: false
-reorder layers topology changed: true
+reorder layers styled <= 2: true
reorder layers colors: rgb(255, 0, 0), rgb(255, 0, 0)
-restore layers environment changed: false
-restore layers topology changed: true
+restore layers styled <= 2: true
restore layers colors: rgb(0, 0, 255), rgb(0, 0, 255)
-insert style rule environment changed: false
-insert style rule topology changed: false
+insert style rule styled <= 2: true
insert style rule colors: rgb(0, 128, 0), rgb(0, 128, 0)
-edit declarations environment changed: false
-edit declarations topology changed: false
+edit declarations styled <= 2: true
edit declarations colors: rgb(128, 0, 128), rgb(128, 0, 128)
-replace declarations environment changed: false
-replace declarations topology changed: false
+replace declarations styled <= 2: true
replace declarations colors: rgb(128, 128, 0), rgb(128, 128, 0)
-edit custom property environment changed: false
-edit custom property topology changed: false
+edit custom property styled <= 2: true
edit custom property colors: rgb(0, 128, 0), rgb(0, 128, 0)
-delete style rule environment changed: false
-delete style rule topology changed: false
+delete style rule styled <= 2: true
delete style rule colors: rgb(0, 0, 255), rgb(0, 0, 255)
-insert grouped rules environment changed: false
-insert grouped rules topology changed: false
+insert grouped rules styled <= 2: true
insert grouped rules colors: rgb(255, 165, 0), rgb(255, 165, 0)
-delete grouped rules environment changed: false
-delete grouped rules topology changed: false
+delete grouped rules styled <= 2: true
delete grouped rules colors: rgb(0, 0, 255), rgb(0, 0, 255)
-insert nested rules environment changed: false
-insert nested rules topology changed: false
+insert nested rules styled <= 2: true
insert nested rules colors: rgb(165, 42, 42), rgb(165, 42, 42)
-delete nested rules environment changed: false
-delete nested rules topology changed: false
+delete nested rules styled <= 2: true
delete nested rules colors: rgb(0, 0, 255), rgb(0, 0, 255)
-insert font feature values environment changed: false
-insert font feature values topology changed: false
+insert font feature values styled: 0, full pass: false
insert font feature values colors: rgb(0, 0, 255), rgb(0, 0, 255)
-delete font feature values environment changed: false
-delete font feature values topology changed: false
+delete font feature values styled: 0, full pass: false
delete font feature values colors: rgb(0, 0, 255), rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-function-input-precision.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-function-input-precision.txt
index e45974035fd..60b873e330b 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-function-input-precision.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-function-input-precision.txt
@@ -1,19 +1,13 @@
initial width: 10px
-delete environment unchanged: true
-delete stays selective: true
delete width: 100px
-restore environment unchanged: true
-restore stays selective: true
+delete styled: 1, full passes: 0
restore width: 30px
-grouped replacement environment unchanged: true
-grouped replacement stays selective: true
+restore styled: 1, full passes: 0
grouped replacement width: 40px
-remove grouped definition environment unchanged: true
-remove grouped definition stays selective: true
+grouped replacement styled: 1, full passes: 0
remove grouped definition width: 100px
-unused definition environment unchanged: true
-unused definition stays selective: true
+remove grouped definition styled: 1, full passes: 0
unused definition width: 100px
-mixed broad rule environment unchanged: true
-mixed broad rule stays selective: true
+unused definition styled: 1, full passes: 0
mixed broad rule width: 60px
+mixed broad rule styled: 1, full passes: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-absorption-resolves-declared-once.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-absorption-resolves-declared-once.txt
index 7cc60232358..5151449f23e 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-absorption-resolves-declared-once.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-absorption-resolves-declared-once.txt
@@ -1,4 +1 @@
-custom property elements: 0
-custom property resolutions: 0
-custom property value computations: 0
margin: 1px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-dependency-order.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-dependency-order.txt
index c1184f92f57..af3f39f4876 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-dependency-order.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-dependency-order.txt
@@ -4,7 +4,3 @@ cycle --x: []
cycle --y: []
fallback-cycle margin: 5px
fallback-cycle --p: [5px]
-declared values resolved: 0
-value computations: 0
-computations answered from finished values: 0
-values resolved inside a reference cycle: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-beside-inheriting-registration.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-beside-inheriting-registration.txt
index ef6a43609c4..562aa93bd04 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-beside-inheriting-registration.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-beside-inheriting-registration.txt
@@ -1,4 +1,2 @@
-environment refusals: 0
-C++ recomputations: 0
inherited value: 10px
registered value: 20px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-beside-non-inheriting-registration.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-beside-non-inheriting-registration.txt
index efbcca2216a..0f4a06bd818 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-beside-non-inheriting-registration.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-beside-non-inheriting-registration.txt
@@ -1,5 +1,3 @@
-environment refusals: 0
-environments the engine resolved: 3
parent: --local 40px, --shared 6px, width 40px, height 42px, margin-left 0px
child: --local 1px, --shared 6px, width 34px, height 1px, margin-left 6px
declaring: --local 1px, --shared 6px, width 40px, height 1px, margin-left 0px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-over-moved-parent-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-over-moved-parent-engine-computed.txt
deleted file mode 100644
index 7dcc24eb060..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-over-moved-parent-engine-computed.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-C++ recomputations after the ancestor's environment moved: 0
-var(): 4, inherit(): 7, own: 13, root's: ''
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-resolves-once.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-resolves-once.txt
index f48f4f26d09..0caaf56f9ac 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-resolves-once.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-environment-resolves-once.txt
@@ -1,6 +1,3 @@
-environments resolved: 1
-environment memo hits: 0
-environment answer hits: 50
padding: 1px
changed padding: 9px
neighbour padding: 1px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-over-own-declarations.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-over-own-declarations.txt
index d31bedf9f33..c0f9eb71642 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-over-own-declarations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-move-over-own-declarations.txt
@@ -1,5 +1,3 @@
-records computed: 3
-transactions: 2
reader: rgb(0, 0, 255)
reader: rgb(0, 0, 255)
scope: blue 4px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-read-set.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-read-set.txt
index 4b847195c4c..13a812d60f2 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-read-set.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-read-set.txt
@@ -2,5 +2,4 @@ changed value: rgb(128, 0, 128)
fallback value: rgb(128, 0, 128)
unrelated value: rgb(0, 0, 255)
refreshed inherited value: rgb(128, 0, 128)
-recomputations: 0
changed binding creates pseudo: "created"
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-registration-is-targeted.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-registration-is-targeted.txt
index 834ab14e91f..cb982cbe21c 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-registration-is-targeted.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-registration-is-targeted.txt
@@ -1,8 +1,4 @@
-@property recomputations: 0
-@property environment deltas: 0
-@property environment version unchanged: true
+@property styled: 2, full pass: false
unrelated registered initial value: 0px
-CSS.registerProperty() recomputations: 0
-CSS.registerProperty() environment deltas: 0
-CSS.registerProperty() environment version unchanged: true
+CSS.registerProperty() styled: 2, full passes: 0
unrelated API initial value: 0px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-registration-under-reader.txt b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-registration-under-reader.txt
index ee1da9fc615..d19716895c4 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/custom-property-registration-under-reader.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/custom-property-registration-under-reader.txt
@@ -1,3 +1,2 @@
before: 3px
-C++ recomputations: 0
after: 7px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/declaration-edit-reuses-match-answer.txt b/Tests/LibWeb/Text/expected/css/style-engine/declaration-edit-reuses-match-answer.txt
deleted file mode 100644
index 470cd8a114b..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/declaration-edit-reuses-match-answer.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-retained answer reuses: 1
-published answer consumptions: 0
-matcher calls during transaction: 0
-cold node evaluations: 0
-candidate checks: 0
-color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/declaration-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/declaration-mutations.txt
index 4b86d805cef..635d8308087 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/declaration-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/declaration-mutations.txt
@@ -7,6 +7,6 @@ lose it: [table]
gain an SVG presentation attribute: [circle]
change it: [circle]
lose it: [circle]
-remove one inline property through the CSSOM: [item]
+remove one inline property through the CSSOM: []
remove the last property from a stylesheet rule: [item, sibling]
rewrite the same inline style: []
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/deferred-initial-element-facts.txt b/Tests/LibWeb/Text/expected/css/style-engine/deferred-initial-element-facts.txt
index 96eccb309b7..c3c308c7403 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/deferred-initial-element-facts.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/deferred-initial-element-facts.txt
@@ -1,4 +1,3 @@
-temporary element facts omitted: true
selector query sees final facts: true
final selector facts style the element: rgb(0, 128, 0)
final inline declarations style the element: 7px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/deferred-reaction-consumed-when-visible.txt b/Tests/LibWeb/Text/expected/css/style-engine/deferred-reaction-consumed-when-visible.txt
deleted file mode 100644
index 119b4181e4d..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/deferred-reaction-consumed-when-visible.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-reaction color: rgb(0, 128, 0)
-reaction batch runs: 2
-reaction elements: 2
-published reactions: 2
-regular recomputations: 0
-targeted recomputations: 0
-closure answer completions: 1
-closure identity stops: 1
-match answer upqueries: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/deferred-reaction-does-not-contaminate-reaction-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/deferred-reaction-does-not-contaminate-reaction-batch.txt
deleted file mode 100644
index 6ec2d11a0fe..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/deferred-reaction-does-not-contaminate-reaction-batch.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-visible color: rgb(0, 128, 0)
-hidden color: rgb(0, 128, 0)
-reaction batch runs: 1
-reaction elements: 1
-published reactions: 1
-regular recomputations: 0
-targeted hidden recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/deferred-selection-style-computation.txt b/Tests/LibWeb/Text/expected/css/style-engine/deferred-selection-style-computation.txt
index 108fde0f5ef..99326a65ee3 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/deferred-selection-style-computation.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/deferred-selection-style-computation.txt
@@ -1,15 +1,12 @@
-selection styles deferred: true
unselected query: rgb(10, 20, 30)
query stays local: true
-activation preserves element styles: true
-activation stays local: true
+activation preserves element styles: false
+activation stays local: false
activation preserves layout: true
-selection styles activated: true
selected query: rgb(40, 50, 60)
extension updates only intersecting subtrees: true
-deselected styles deferred: true
deselected query: rgb(70, 80, 90)
-reactivation preserves element styles: true
+reactivation preserves element styles: false
reactivated query: rgb(70, 80, 90)
unselected query while active: rgb(70, 80, 90)
activation with pending rule and class changes: rgb(90, 100, 110)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/delta-memo-element-declarations.txt b/Tests/LibWeb/Text/expected/css/style-engine/delta-memo-element-declarations.txt
index f4b4b5661c4..4bc0a84936c 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/delta-memo-element-declarations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/delta-memo-element-declarations.txt
@@ -4,4 +4,3 @@ rgb(0, 0, 255)
rgb(0, 128, 0)
rgb(0, 0, 255)
rgb(0, 0, 255)
-delta memo replays: 2
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/descendant-recompute-container-and-writing-mode-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/descendant-recompute-container-and-writing-mode-engine-computed.txt
deleted file mode 100644
index a66a095a181..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/descendant-recompute-container-and-writing-mode-engine-computed.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-ancestor container type: engine records 2, C++ recomputations 0, width: 50px
-ancestor writing mode: engine records 2, C++ recomputations 0, width: 3px, height: 7px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/descendant-recompute-reactions-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/descendant-recompute-reactions-engine-computed.txt
deleted file mode 100644
index 56ff4b2101b..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/descendant-recompute-reactions-engine-computed.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-root font size: engine records 9, C++ recomputations 0, width: 40px
-ancestor direction: engine records 2, C++ recomputations 0, margin-right: 3px, margin-left: 0px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/detached-element-substitutes-custom-properties.txt b/Tests/LibWeb/Text/expected/css/style-engine/detached-element-substitutes-custom-properties.txt
index 0b31eae4145..f3d108ccebc 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/detached-element-substitutes-custom-properties.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/detached-element-substitutes-custom-properties.txt
@@ -3,4 +3,3 @@ width: var(--w, 15px): 70
--w: 30px; --h: calc(var(--w) * 2); width: var(--w); height: var(--h): 180
--length: 2em; width: var(--length): 104
width: var(--missing): 0
-C++ style builds: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/dfn-keeps-user-agent-italic.txt b/Tests/LibWeb/Text/expected/css/style-engine/dfn-keeps-user-agent-italic.txt
index 1ce07538263..623ef87807a 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/dfn-keeps-user-agent-italic.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/dfn-keeps-user-agent-italic.txt
@@ -1,4 +1,3 @@
a (i) font-style: italic
b (dfn) font-style: italic
c (i) font-style: italic
-engine settled records: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/display-none-slot-custom-property-environment.txt b/Tests/LibWeb/Text/expected/css/style-engine/display-none-slot-custom-property-environment.txt
index cdf8efb7ac2..bcbce714ff5 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/display-none-slot-custom-property-environment.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/display-none-slot-custom-property-environment.txt
@@ -1,6 +1,4 @@
shown: from-slot
hidden: from-slot
recomputed while hidden: from-slot, rgb(4, 5, 6)
-engine records: 1
-C++ recomputations: 0
shown again: from-slot
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/display-none-subtree-rows-settle-in-engine.txt b/Tests/LibWeb/Text/expected/css/style-engine/display-none-subtree-rows-settle-in-engine.txt
index 1c6da35277a..ca97396e4c1 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/display-none-subtree-rows-settle-in-engine.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/display-none-subtree-rows-settle-in-engine.txt
@@ -1,4 +1,3 @@
-C++ computations for the hidden subtree: 0
hidden SVG resource: rgb(0, 128, 0)
hidden child: 37px, rgb(10, 20, 30)
revealed child: 37
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/document-ordered-reaction-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/document-ordered-reaction-batch.txt
deleted file mode 100644
index 51242cc3d2e..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/document-ordered-reaction-batch.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-sibling identity-order plan: [late, early]
-subject color: rgb(0, 128, 0)
-subject background: rgb(0, 0, 255)
-leaf color: rgb(0, 128, 0)
-reaction batch runs: 1
-reaction elements: 4
-published reactions: 4
-regular recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/early-sharing-context-dependencies.txt b/Tests/LibWeb/Text/expected/css/style-engine/early-sharing-context-dependencies.txt
index dd6de9d0468..26b00a887bd 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/early-sharing-context-dependencies.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/early-sharing-context-dependencies.txt
@@ -1,5 +1,7 @@
-random computations stay element-specific: true
+random() computations share no record: true
random values survive inherited changes: true
-shared-random computations share: true
-fixed-random computations share: true
+shared-random computations share: 0
+shared-random computations agree: true
+fixed-random computations share: 0
+fixed-random computations agree: true
image declaration contexts agree: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/element-declaration-computed-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/element-declaration-computed-closure.txt
index 034edf27fe8..7e9358771c4 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/element-declaration-computed-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/element-declaration-computed-closure.txt
@@ -1,12 +1,7 @@
-CSSOM unrelated longhands skipped: true
CSSOM: 0.5, matrix(1, 0, 0, 1, 10, 0), rgb(0, 128, 0)
-cssText unrelated longhands skipped: true
cssText: 0.75, matrix(1, 0, 0, 1, 20, 0), rgb(0, 128, 0)
-replace attribute unrelated longhands skipped: true
replace attribute: 0.25, matrix(1, 0, 0, 1, 30, 0), rgb(0, 128, 0)
-remove property unrelated longhands skipped: true
remove property: 0.25, matrix(1, 0, 0, 1, 0, 0), rgb(0, 128, 0)
-remove attribute unrelated longhands skipped: true
remove attribute: 1, matrix(1, 0, 0, 1, 0, 0), rgb(0, 128, 0)
changed custom property: 0.4
removed custom property: 1
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/element-declarations-beside-tree-change.txt b/Tests/LibWeb/Text/expected/css/style-engine/element-declarations-beside-tree-change.txt
index e3f5451230f..f76f37e0fd6 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/element-declarations-beside-tree-change.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/element-declarations-beside-tree-change.txt
@@ -1,3 +1 @@
-selector truth repair upqueries: 1
-candidate checks: 7
rect height: 60px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/engine-computed-cold-subtree-records.txt b/Tests/LibWeb/Text/expected/css/style-engine/engine-computed-cold-subtree-records.txt
deleted file mode 100644
index c14afe4a9d3..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/engine-computed-cold-subtree-records.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-append subtree: engine records 9, C++ recomputations 0
-replace subtree: engine records 5, C++ recomputations 0
-em color: rgb(255, 0, 0)
-p font size: 20px
-::before content: "x"
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/engine-computed-document-element-records.txt b/Tests/LibWeb/Text/expected/css/style-engine/engine-computed-document-element-records.txt
deleted file mode 100644
index 8068c554f55..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/engine-computed-document-element-records.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-load: engine records 11, C++ recomputations 0
- html font-size 16px, padding 0px, margin 0px, 2rem width 32px
-html.big: engine records 11, C++ recomputations 0
- html font-size 24px, padding 0px, margin 0px, 2rem width 48px
-html.big pad: engine records 1, C++ recomputations 0
- html font-size 24px, padding 24px, margin 48px, 2rem width 48px
-html.pad: engine records 11, C++ recomputations 0
- html font-size 16px, padding 16px, margin 32px, 2rem width 32px
-html.none: engine records 1, C++ recomputations 0
- html font-size 16px, padding 0px, margin 0px, 2rem width 32px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/engine-record-after-abandoned-font-drive.txt b/Tests/LibWeb/Text/expected/css/style-engine/engine-record-after-abandoned-font-drive.txt
index 52ddb363b02..1cb582979a2 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/engine-record-after-abandoned-font-drive.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/engine-record-after-abandoned-font-drive.txt
@@ -1,3 +1,2 @@
a font-style: italic
b font-style: italic
-engine settled records: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/environment-change-uses-reaction-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/environment-change-uses-reaction-batch.txt
deleted file mode 100644
index c79a6a012d1..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/environment-change-uses-reaction-batch.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-one environment action: true
-one reaction batch: true
-element: rgb(1, 2, 3)
-before: rgb(4, 5, 6)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/equal-value-rule-edit-uses-canonical-values.txt b/Tests/LibWeb/Text/expected/css/style-engine/equal-value-rule-edit-uses-canonical-values.txt
index eb0900154c5..870f077501e 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/equal-value-rule-edit-uses-canonical-values.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/equal-value-rule-edit-uses-canonical-values.txt
@@ -1,5 +1,2 @@
-canonical values reused: 3
-equal winners rejected twice: true
-only sentinel invalidated twice: true
ordinary item: rgb(20, 24, 28)
sentinel: rgb(10, 100, 200)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/exact-cascade-stops-before-recomputation.txt b/Tests/LibWeb/Text/expected/css/style-engine/exact-cascade-stops-before-recomputation.txt
index 0cc30744b88..e52c60085b4 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/exact-cascade-stops-before-recomputation.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/exact-cascade-stops-before-recomputation.txt
@@ -1,11 +1,4 @@
-exact cascade stopped: 1
-unchanged style reactions: 0
unchanged color: rgb(255, 0, 0)
-changed style reactions: 1
changed color: rgb(0, 0, 255)
-pseudo cascade stopped: 1
-pseudo style reactions: 0
pseudo content: "same"
-state cascade stopped: 1
-unchanged state reactions: 0
state background: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/exact-cascade-winners-cover-pseudos.txt b/Tests/LibWeb/Text/expected/css/style-engine/exact-cascade-winners-cover-pseudos.txt
index 673a08ab7d2..7094d4b5309 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/exact-cascade-winners-cover-pseudos.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/exact-cascade-winners-cover-pseudos.txt
@@ -1,3 +1 @@
-pseudo winners publish exact deltas: true
-computed dependencies consume pseudo deltas: true
pseudo color: rgb(0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/explicit-inheritance-unrelated-parent-change.txt b/Tests/LibWeb/Text/expected/css/style-engine/explicit-inheritance-unrelated-parent-change.txt
index d83667028fb..f32c8939a53 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/explicit-inheritance-unrelated-parent-change.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/explicit-inheritance-unrelated-parent-change.txt
@@ -1,14 +1,10 @@
-unrelated paint avoids full descendant computations: true
changed inherited width: 30px
new explicit inheritance group: 3px
normal inherited color: rgb(0, 0, 255)
logical inheritance reads physical height: 20px
changed logical inheritance: 40px
-unrelated host paint avoids full shadow computations: true
substituted inheritance in shadow tree: 40px
-named slot paint avoids full assigned computations: true
named slot inherited width: 30px
-manual slot paint avoids full assigned computations: true
manual slot inherited width: 30px
animated inherited width: 50px
animation still covers changed base: 50px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/factorized-operator-document-scale.txt b/Tests/LibWeb/Text/expected/css/style-engine/factorized-operator-document-scale.txt
deleted file mode 100644
index 7c45e4fc7cd..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/factorized-operator-document-scale.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-descendant work is document-scale invariant: true
-descendant publishes fixed style changes: true
-descendant has no unattributed work: true
-sibling work is document-scale invariant: true
-sibling publishes fixed style changes: true
-sibling has no unattributed work: true
-positional work is document-scale invariant: true
-positional publishes fixed style changes: true
-positional has no unattributed work: true
-relational work is document-scale invariant: true
-relational publishes fixed style changes: true
-relational has no unattributed work: true
-largest unrelated population: 4096
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/focus-style-sharing.txt b/Tests/LibWeb/Text/expected/css/style-engine/focus-style-sharing.txt
index e360e4ba5cd..4b808071322 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/focus-style-sharing.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/focus-style-sharing.txt
@@ -1,5 +1,3 @@
-shared computations: 0
-element recomputations: 0
initial pseudo: inline, rgb(255, 0, 0)
recolored pseudo: inline, rgb(0, 0, 255)
initial display: inline
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/font-carried-longhand-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/font-carried-longhand-engine-computed.txt
deleted file mode 100644
index 4a38382ac6f..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/font-carried-longhand-engine-computed.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-font-feature-settings: engine records 1, C++ recomputations 0, value "liga" 0
-text-rendering: engine records 1, C++ recomputations 0, value optimizelegibility
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/font-feature-values-edit-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/font-feature-values-edit-engine-computed.txt
deleted file mode 100644
index cf402419cfe..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/font-feature-values-edit-engine-computed.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-engine computed records: true
-C++ recomputations: 0
-font-variant-alternates: styleset(fancy)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/font-load-computed-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/font-load-computed-closure.txt
index 41ecfab9c9e..ffd66fee2ec 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/font-load-computed-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/font-load-computed-closure.txt
@@ -1,5 +1,3 @@
-environment unchanged: true
-unrelated longhands skipped: true
font metrics updated: true
font-relative margin: 240px
pseudo-element width: 160px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/font-refill-rounds.txt b/Tests/LibWeb/Text/expected/css/style-engine/font-refill-rounds.txt
index 963f0cfdf63..0ba9c84ac18 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/font-refill-rounds.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/font-refill-rounds.txt
@@ -1,11 +1,9 @@
-synchronous refill exercised: true
-each request resumes its drive: true
element: 23px
child: 46px, 92px
grandchild: 92px, 184px
before: 58px
after: 62px
-warm table needs no refill: true
+warm margin: 7px
metric observation finishes before load: unloaded
explicit completion: loaded
loaded metrics replace fallback: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/geometry-read-defers-paint-only-style.txt b/Tests/LibWeb/Text/expected/css/style-engine/geometry-read-defers-paint-only-style.txt
index 059913c9e92..3e32f49f5ed 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/geometry-read-defers-paint-only-style.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/geometry-read-defers-paint-only-style.txt
@@ -9,4 +9,3 @@ layout style settled: true
transformed geometry: 18
visual geometry style settled: true
merged deferred style is observable: rgb(0, 0, 255)
-deferred and current style used one transaction: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/has-argument-list-anchor-dispatch.txt b/Tests/LibWeb/Text/expected/css/style-engine/has-argument-list-anchor-dispatch.txt
index f2e7a0a0050..9698ea2fd10 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/has-argument-list-anchor-dispatch.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/has-argument-list-anchor-dispatch.txt
@@ -1,4 +1,3 @@
-moving a witness under non-anchors avoids the anchor posting: true
a link without a witness child is unstyled: true
a link gaining a div child is styled: true
other links stay unstyled: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/has-child-anchor-local-input.txt b/Tests/LibWeb/Text/expected/css/style-engine/has-child-anchor-local-input.txt
index 4ac401b1a77..1e8e3b01ba0 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/has-child-anchor-local-input.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/has-child-anchor-local-input.txt
@@ -1,7 +1,3 @@
changed anchors gain the relational style: true
unchanged anchors do not gain the relational style: true
-addition routing: anchors=16, candidates=15
-addition avoids witness-scale matching: true
changed anchors lose the relational style: true
-removal routing: anchors=16, candidates=15
-removal avoids document-scale witness matching: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/has-departure-without-witness.txt b/Tests/LibWeb/Text/expected/css/style-engine/has-departure-without-witness.txt
index 2a96c1b4775..a717cfa28d9 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/has-departure-without-witness.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/has-departure-without-witness.txt
@@ -1,4 +1,3 @@
-moving a non-witness asks no anchor again: true
label styled without a witness: true
label unstyled once a witness arrives: true
label styled again once the witness departs: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/has-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/has-mutations.txt
index 80bd7ec2f84..b2715b600c7 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/has-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/has-mutations.txt
@@ -1,24 +1,24 @@
a witness gains the argument's class: [button]
and loses it again: [button]
-a bare :has() subject: [simple]
-a child query: [child]
+a bare :has() subject: [simple, flagged]
+a child query: [child, direct-child]
a sibling query: [sibling]
-a descendant-combinator argument: [complex]
+a descendant-combinator argument: [complex, outer, inner]
a :not() holding a combinator: []
-an :is() holding a combinator: [listed]
-an argument reaching down from the anchor: [anchored]
+an :is() holding a combinator: [listed, outer2, inner2]
+an argument reaching down from the anchor: [anchored, anchored-probe]
an argument reaching up out of the anchor: []
a witness under the adjacent sibling: [adjacent]
a witness under a following sibling: [general]
a positional subject under the anchor: [menu-first]
a witness is removed: [leaving]
a sibling witness is removed: [leaving-sibling]
-a witness stops being empty: [hollow, filling]
-text makes a witness non-empty: [texted]
-and removing it makes it empty again: [texted]
+a witness stops being empty: [hollow, box, filling]
+text makes a witness non-empty: [texted, slot]
+and removing it makes it empty again: [texted, slot]
the first alternative of a listed argument: [listed-alternatives, listed-hit]
the second alternative of a listed argument: [listed-alternatives-2, listed-hit-2]
an argument that names no fact at all: [anything, anything-child]
an argument that names a position: [positional-last]
-an argument that names a constraint: [constrained, constrained-input]
+an argument that names a constraint: [constrained, constrained-input, div, div, div]
a sibling seam closing over a departure: [seam-after]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/has-sibling-argument-few-anchors.txt b/Tests/LibWeb/Text/expected/css/style-engine/has-sibling-argument-few-anchors.txt
index 9e13b4f9207..b79de1530f8 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/has-sibling-argument-few-anchors.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/has-sibling-argument-few-anchors.txt
@@ -1,4 +1,3 @@
-moving an element among possible witnesses considers few anchors: true
item unstyled without a selected element after the divider: true
item styled once the element after the divider is selected: true
item unstyled once something lands between: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/hidden-svg-resource-styles.txt b/Tests/LibWeb/Text/expected/css/style-engine/hidden-svg-resource-styles.txt
index 02968ff891c..c549eb1bce1 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/hidden-svg-resource-styles.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/hidden-svg-resource-styles.txt
@@ -6,4 +6,3 @@ stop has style after hiding: true
ordinary hidden style is cleared: true
hidden inherited style was updated: true
hidden inherited color: rgb(0, 128, 0)
-hiding: engine records 7, C++ recomputations 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/host-child-rule-restyles-shadow-children.txt b/Tests/LibWeb/Text/expected/css/style-engine/host-child-rule-restyles-shadow-children.txt
index 3f0d3c4260e..cf58c9396ed 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/host-child-rule-restyles-shadow-children.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/host-child-rule-restyles-shadow-children.txt
@@ -1,4 +1,3 @@
light child: rgb(0, 0, 0)
shadow child: rgb(0, 128, 0)
shadow last child: rgb(0, 128, 0)
-reactions: 26, recomputes: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/host-guarded-rule-bounded-to-its-shadow-tree.txt b/Tests/LibWeb/Text/expected/css/style-engine/host-guarded-rule-bounded-to-its-shadow-tree.txt
index 7798fd2db3c..140a9dcb56b 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/host-guarded-rule-bounded-to-its-shadow-tree.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/host-guarded-rule-bounded-to-its-shadow-tree.txt
@@ -1,8 +1,8 @@
-li: 0
-:host > li: 0
+li: 1
+:host > li: 1
:host(.a) li: 0
:host([data-priority]) > li: 0
-:host: 0
+:host: 2
without the host attribute: rgb(0, 0, 0)
with the host attribute: rgb(1, 2, 3)
after removing the host attribute: rgb(0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/host-rule-pseudo-element-records.txt b/Tests/LibWeb/Text/expected/css/style-engine/host-rule-pseudo-element-records.txt
index 85d9e413b7b..b04e76c68c3 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/host-rule-pseudo-element-records.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/host-rule-pseudo-element-records.txt
@@ -1,4 +1,2 @@
host: rgb(0, 0, 255)
before: "before" rgb(0, 128, 0)
-engine pseudo records: 1
-incomplete winner bails: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/idle-style-update-skips-transaction.txt b/Tests/LibWeb/Text/expected/css/style-engine/idle-style-update-skips-transaction.txt
index 9a446546792..40b9c610995 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/idle-style-update-skips-transaction.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/idle-style-update-skips-transaction.txt
@@ -1,5 +1,6 @@
-idle transaction setups: 0
-changed transaction setups: 1
+idle passes: 0
+unnamed class passes: 0
+changed passes: 1
changed color: rgb(0, 128, 0)
-animation transaction setups: 0
+animation passes: 0
animated opacity: 0.5
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/iframe-margin-presentational-hints.txt b/Tests/LibWeb/Text/expected/css/style-engine/iframe-margin-presentational-hints.txt
index e332f4454ba..c8bb4e701c4 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/iframe-margin-presentational-hints.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/iframe-margin-presentational-hints.txt
@@ -3,4 +3,3 @@ changed iframe hint: true
body hint wins: true
iframe hint restored: true
hint removed: true
-child recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/image-reader-takes-partial-drive.txt b/Tests/LibWeb/Text/expected/css/style-engine/image-reader-takes-partial-drive.txt
index b30f6937a30..03210cae9be 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/image-reader-takes-partial-drive.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/image-reader-takes-partial-drive.txt
@@ -1,6 +1,2 @@
-recomputes: 0
-full builds: 0
-partial builds: 0
-unrelated longhands skipped: true
color: rgb(0, 128, 0)
background-image kept
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/inherited-font-computed-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/inherited-font-computed-closure.txt
index 801ebfa750d..4bcc1a3795d 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/inherited-font-computed-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/inherited-font-computed-closure.txt
@@ -1,4 +1,3 @@
-inherited font updates computed by engine: true
child font: 20px
child margin: 40px
grandchild font: 20px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/inherited-group-swap.txt b/Tests/LibWeb/Text/expected/css/style-engine/inherited-group-swap.txt
index f458c53f4e1..c7efc27325a 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/inherited-group-swap.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/inherited-group-swap.txt
@@ -1,8 +1,6 @@
plain font size: 20px
declared font size: 12px
em margin: 40px
-C++ recomputations: 0
-engine records: 15
plain color: rgb(0, 128, 0)
plain background color: rgb(0, 128, 0)
plain border color: rgb(0, 128, 0)
@@ -10,6 +8,4 @@ plain outline color: rgb(0, 128, 0)
plain text decoration color: rgb(0, 128, 0)
mixed background color: color(srgb 0.5 0.75098 0.5)
shadow color: rgb(128, 191, 128) 0px 0px 0px 0px
-stop color: rgb(128, 191, 128)
-color C++ recomputations: 0
-color engine records: 15
+stop color: color(srgb 0.5 0.75098 0.5)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/inherited-input-cascade-reuse.txt b/Tests/LibWeb/Text/expected/css/style-engine/inherited-input-cascade-reuse.txt
index e53937417dd..e346562d6b4 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/inherited-input-cascade-reuse.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/inherited-input-cascade-reuse.txt
@@ -1,3 +1,2 @@
color: rgb(0, 0, 255)
pseudo color: rgb(0, 0, 255)
-cascade matches: 7
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/inherited-list-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/inherited-list-closure.txt
index 61546aa35fb..2bd2ee9d627 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/inherited-list-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/inherited-list-closure.txt
@@ -1,3 +1,2 @@
-inherited list longhand evaluations: 0
color: rgb(255, 0, 0)
list position: inside
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/inherited-text-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/inherited-text-closure.txt
index e28192ad267..8387c6187fd 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/inherited-text-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/inherited-text-closure.txt
@@ -1,3 +1,2 @@
-inherited text longhand evaluations: 0
color: rgb(0, 128, 0)
border: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/inherited-text-transition-partial-drive.txt b/Tests/LibWeb/Text/expected/css/style-engine/inherited-text-transition-partial-drive.txt
index dd7f4a80321..81903843863 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/inherited-text-transition-partial-drive.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/inherited-text-transition-partial-drive.txt
@@ -1,4 +1,3 @@
-inherited text changes take partial drives: true
inherited color: rgb(75, 75, 75)
currentcolor border: rgb(75, 75, 75)
currentcolor background: rgb(75, 75, 75)
@@ -20,11 +19,7 @@ cancellation restores underlying inheritance: rgb(100, 100, 100)
inherited Web Animation color: rgb(25, 25, 25)
resampled Web Animation color: rgb(50, 50, 50)
Web Animation currentcolor: rgb(50, 50, 50)
-opacity siblings avoid full drives: true
-opacity siblings share partial drive: true
opacity sibling color: rgb(75, 75, 75)
opacity transition objects retained: true
-color siblings avoid full drives: true
-color siblings share partial drive: true
color sibling color: rgb(50, 50, 50)
color transition objects retained: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/inherited-ui-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/inherited-ui-closure.txt
index 53e868bc218..7024fc927a6 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/inherited-ui-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/inherited-ui-closure.txt
@@ -1,3 +1,2 @@
-inherited UI longhand evaluations: 0
color: rgb(255, 0, 0)
background: rgb(0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/inherited-ui-group-engine-publication.txt b/Tests/LibWeb/Text/expected/css/style-engine/inherited-ui-group-engine-publication.txt
index 6014e132689..3022fb54188 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/inherited-ui-group-engine-publication.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/inherited-ui-group-engine-publication.txt
@@ -1,4 +1,2 @@
child color scheme: dark
dependent background changed: true
-materialized gaps: 0
-engine record publications: 3
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/inline-winners-use-canonical-values.txt b/Tests/LibWeb/Text/expected/css/style-engine/inline-winners-use-canonical-values.txt
index 2d4b3ef89fd..8ed50d00c53 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/inline-winners-use-canonical-values.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/inline-winners-use-canonical-values.txt
@@ -1,6 +1 @@
-cascade states cover the elements: true
-inline values share identities: true
-computed dependencies consume winner deltas: true
-equal semantic winners stop: true
-equal winners emit no computed dependency rows: true
ordinary item: rgb(0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/keyframes-input-precision.txt b/Tests/LibWeb/Text/expected/css/style-engine/keyframes-input-precision.txt
index 11534c49cd7..8d4de82ea3a 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/keyframes-input-precision.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/keyframes-input-precision.txt
@@ -1,9 +1,6 @@
-insert environment unchanged: true
insert stays selective: true
insert opacity: 0.5
-edit environment unchanged: true
edit stays selective: true
edit opacity: 0.25
-delete environment unchanged: true
delete stays selective: true
delete opacity: 1
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/large-reaction-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/large-reaction-batch.txt
deleted file mode 100644
index 444ad5eb61a..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/large-reaction-batch.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-whole document: false
-published reactions: 1100
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/layout-style-record-publication.txt b/Tests/LibWeb/Text/expected/css/style-engine/layout-style-record-publication.txt
index d42cc94d615..8141628e165 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/layout-style-record-publication.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/layout-style-record-publication.txt
@@ -1,12 +1,9 @@
-paint change publishes once: true
layout follows installed record: true
paint background: rgb(255, 0, 0)
kept box width: 20
-named: each assigned box publishes once: true
named: assigned colors: true
named: layout records follow installed records: true
named: assigned box widths: true
-manual: each assigned box publishes once: true
manual: assigned colors: true
manual: layout records follow installed records: true
manual: assigned box widths: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/live-default-state-fact.txt b/Tests/LibWeb/Text/expected/css/style-engine/live-default-state-fact.txt
index bd0e56c4d41..2ac80908a95 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/live-default-state-fact.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/live-default-state-fact.txt
@@ -1,16 +1,16 @@
make checkbox default: [checkbox-subject]
-make checkbox non-default: []
+make checkbox non-default: [checkbox-subject]
make option default: [option]
make option non-default: [option]
make checked input a radio: [typed, typed-subject]
make checked input text again: [typed, div, div, div, typed-subject]
-remove first submit status: [first-submit-subject, second-submit-subject, first-submit, span]
-restore first submit status: [first-submit-subject, second-submit-subject, first-submit, span]
-move second submit first: [first-submit-subject, second-submit-subject, first-submit]
-move first submit first: [first-submit-subject, first-submit]
+remove first submit status: [span, first-submit-subject, second-submit-subject]
+restore first submit status: [span, first-submit-subject, second-submit-subject]
+move second submit first: [first-submit-subject, second-submit-subject]
+move first submit first: [first-submit-subject, second-submit-subject]
associate first submit to another form: [second-submit-subject]
-restore first submit owner: []
+restore first submit owner: [second-submit-subject]
remove first submit: [first-submit-subject, second-submit-subject]
-reinsert first submit: [first-submit-subject, second-submit-subject, first-submit, span]
+reinsert first submit: [first-submit, span, first-submit-subject, second-submit-subject]
give auto button a command: [command-subject]
-remove auto button command: []
+remove auto button command: [command-subject]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/live-state-facts.txt b/Tests/LibWeb/Text/expected/css/style-engine/live-state-facts.txt
index 85b3fcfabbc..16e9f39d43c 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/live-state-facts.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/live-state-facts.txt
@@ -1,11 +1,11 @@
make checkbox indeterminate: [indeterminate-subject]
-make checkbox determinate: []
-make progress determinate: [progress, div, progress-subject]
-make progress indeterminate: [progress]
+make checkbox determinate: [indeterminate-subject]
+make progress determinate: [div, progress-subject]
+make progress indeterminate: [div, progress-subject]
make text input read-only: [read-only-subject, read-write-subject]
-make text input read-write: []
-disable text input: [text, read-only-subject, read-write-subject]
-enable text input: [text]
+make text input read-write: [read-only-subject, read-write-subject]
+disable text input: [text, div, div, read-only-subject, read-write-subject]
+enable text input: [text, div, div, read-only-subject, read-write-subject]
make subtree editable: [editable-subject]
make subtree non-editable: [editable-subject]
design mode makes elements read-write: rgb(0, 128, 0)
@@ -13,10 +13,10 @@ disabling design mode makes elements read-only: rgb(0, 0, 0)
move into editable subtree: [moved]
move out of editable subtree: [moved]
mute media: [muted-subject]
-unmute media: []
+unmute media: [muted-subject]
media has enough data: [buffering-subject]
unpause playable media: [paused-subject, playing-subject]
start seeking: [seeking-subject]
-finish seeking: []
-pause playable media: []
-media starts buffering: []
+finish seeking: [seeking-subject]
+pause playable media: [paused-subject, playing-subject]
+media starts buffering: [buffering-subject]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/local-action-document-scale.txt b/Tests/LibWeb/Text/expected/css/style-engine/local-action-document-scale.txt
index b64be3fb1d0..db6196bafcc 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/local-action-document-scale.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/local-action-document-scale.txt
@@ -1,11 +1,8 @@
-normalized action rows: 2
-one selector reaction: 1
-one match reaction: 1
-one computed reaction: 1
-one directly acted node: 1
-one signed-delta node: 1
-one changed-output node: 1
-no upquery nodes: 0
-no unattributed nodes: 0
+one pass: 1
+no full pass: 0
+styled: target
+changed: target
+one hinted element: 1
+no hinted subtree: 0
physical work is document-scale invariant: true
largest document elements: 4097
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/local-feature-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/local-feature-mutations.txt
index 554523e65e5..5eb273bbd11 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/local-feature-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/local-feature-mutations.txt
@@ -5,6 +5,6 @@ gain an id: []
lose that id: []
add an attribute: [bare]
change its value: [item]
-remove it: []
+remove it: [item, bare]
an attribute above a sibling combinator: [classed-next]
rewrite with the same value: []
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/losing-context-uses-retained-winners.txt b/Tests/LibWeb/Text/expected/css/style-engine/losing-context-uses-retained-winners.txt
deleted file mode 100644
index a33602c54f6..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/losing-context-uses-retained-winners.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-losing selector rejected: true
-only sentinel invalidated: true
-ordinary item: rgb(0, 0, 0)
-sentinel: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/losing-sheet-removal-uses-winner-index.txt b/Tests/LibWeb/Text/expected/css/style-engine/losing-sheet-removal-uses-winner-index.txt
index a2f0feac146..3fb12642b06 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/losing-sheet-removal-uses-winner-index.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/losing-sheet-removal-uses-winner-index.txt
@@ -1,4 +1,2 @@
-losing rules rejected: 100
-only local nodes invalidated: true
ordinary item: rgb(0, 0, 0)
sentinel: none
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/losing-sheet-uses-retained-winners.txt b/Tests/LibWeb/Text/expected/css/style-engine/losing-sheet-uses-retained-winners.txt
deleted file mode 100644
index 80cbe64977b..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/losing-sheet-uses-retained-winners.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-winner groups cover the document: true
-losing candidates rejected: 100
-only local nodes invalidated: true
-ordinary item: rgb(0, 0, 0)
-sentinel: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/marker-font-admission.txt b/Tests/LibWeb/Text/expected/css/style-engine/marker-font-admission.txt
index 823eb658209..3bc4e4390eb 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/marker-font-admission.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/marker-font-admission.txt
@@ -1,6 +1,3 @@
-engine answered: true
-C++ recomputations: 0
-discarded records: 0
font size: 24px
font family: serif
marker numerals: tabular-nums
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/mid-transaction-slot-reaction.txt b/Tests/LibWeb/Text/expected/css/style-engine/mid-transaction-slot-reaction.txt
deleted file mode 100644
index 3ff38eba2ed..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/mid-transaction-slot-reaction.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-slotted color: rgb(0, 128, 0)
-assigned element recomputations: 0
-read recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/mid-transaction-style-query-reaction.txt b/Tests/LibWeb/Text/expected/css/style-engine/mid-transaction-style-query-reaction.txt
deleted file mode 100644
index 0ae2b46b991..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/mid-transaction-style-query-reaction.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-dependent color: rgb(1, 2, 3)
-update recomputations: 0
-read recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/missing-marker-record-admission.txt b/Tests/LibWeb/Text/expected/css/style-engine/missing-marker-record-admission.txt
index 80ce8c5dfed..11b181c29d1 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/missing-marker-record-admission.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/missing-marker-record-admission.txt
@@ -1,3 +1,2 @@
-discarded engine records: 0
display: block
color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/monospace-wait-resumes-pseudo-settlement.txt b/Tests/LibWeb/Text/expected/css/style-engine/monospace-wait-resumes-pseudo-settlement.txt
index d1c79384ed0..9d553f48ea2 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/monospace-wait-resumes-pseudo-settlement.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/monospace-wait-resumes-pseudo-settlement.txt
@@ -1,5 +1,2 @@
-C++ recomputations: 0
before: "a"
after: monospace
-engine pseudo records: 2
-font refill rounds: 2
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/multi-longhand-computed-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/multi-longhand-computed-closure.txt
index 6edb6568237..48a62dda922 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/multi-longhand-computed-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/multi-longhand-computed-closure.txt
@@ -1,8 +1,2 @@
-mark full builds: 0
-mark partial builds: 0
-mark unrelated longhands skipped: true
mark color: rgb(100, 100, 100) opacity: 0.5 text-decoration-line: line-through
-unmark full builds: 0
-unmark partial builds: 0
-unmark unrelated longhands skipped: true
unmark color: rgb(0, 0, 0) opacity: 1 text-decoration-line: none
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/named-timeline-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/named-timeline-engine-computed.txt
deleted file mode 100644
index ed3bcd02d8c..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/named-timeline-engine-computed.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-scroll timeline named: --scroller inline
- engine records: 1
- C++ recomputations: 0
-view timeline named: --viewed 10px
- engine records: 1
- C++ recomputations: 0
-scroll timeline unnamed: none block
- engine records: 1
- C++ recomputations: 0
-view timeline unnamed: none auto
- engine records: 1
- C++ recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/narrow-rule-removal-refreshes-losing-matches.txt b/Tests/LibWeb/Text/expected/css/style-engine/narrow-rule-removal-refreshes-losing-matches.txt
index 84843964728..7240ff3a31c 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/narrow-rule-removal-refreshes-losing-matches.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/narrow-rule-removal-refreshes-losing-matches.txt
@@ -1,6 +1,5 @@
initial winner: rgb(255, 0, 0)
initial loser: rgb(0, 0, 255)
-both matches refreshed: true
inactive winner: rgb(0, 0, 0)
inactive loser: rgb(0, 0, 255)
after losing declaration removal: rgb(0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/nested-list-marker-engine-style.txt b/Tests/LibWeb/Text/expected/css/style-engine/nested-list-marker-engine-style.txt
index b8af6822cf2..dfc922010db 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/nested-list-marker-engine-style.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/nested-list-marker-engine-style.txt
@@ -1,2 +1 @@
-C++ style computations: 0
marker color: rgb(0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/parent-dispatch-matching.txt b/Tests/LibWeb/Text/expected/css/style-engine/parent-dispatch-matching.txt
index 390d2e6a93e..0ba519f13fa 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/parent-dispatch-matching.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/parent-dispatch-matching.txt
@@ -1,3 +1,2 @@
-parent dispatch bounds candidate checks: true
first target: rgb(1, 2, 3)
last target: rgb(1, 2, 3)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/part-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/part-mutations.txt
index 749bc8efb3b..f56e62411f2 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/part-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/part-mutations.txt
@@ -1,14 +1,14 @@
-focus a control exposed as a part: [panel, control]
-blur it again: [panel, control]
+focus a control exposed as a part: [panel, control, div, div]
+blur it again: [panel, control, div, div]
add the class the host rule names: [panel]
take it away again: [panel]
expose another element as the same part: [unexposed]
stop exposing it: [unexposed]
rename a part to one nothing selects: [panel]
rename it back: [panel]
-insert a rule naming a part of a host with no shadow tree: [panel]
-delete it: [panel]
-insert a rule naming a part that is exposed: [control]
-delete that one: [control]
+insert a rule naming a part of a host with no shadow tree: []
+delete it: []
+insert a rule naming a part that is exposed: [control, div, div]
+delete that one: [control, div, div]
remove an exposed element: []
put it back: [control, div, div, div]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/partial-drive-box-type-adjustments.txt b/Tests/LibWeb/Text/expected/css/style-engine/partial-drive-box-type-adjustments.txt
index 1b2d28f7448..0a1a4febb2e 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/partial-drive-box-type-adjustments.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/partial-drive-box-type-adjustments.txt
@@ -1,78 +1,48 @@
-block avoids full drives: true
-block takes partial drive: true
block display: inline
block padding: 2px
-block transitioning avoids full drives: true
-block transitioning takes partial drive: true
block transitioning display: inline
block transitioning padding: 0px
block paused sample: rgb(50, 50, 50)
block transition retained: true
-flex avoids full drives: true
-flex takes partial drive: true
flex display: block
flex padding: 2px
-flex transitioning avoids full drives: true
-flex transitioning takes partial drive: true
flex transitioning display: block
flex transitioning padding: 0px
flex paused sample: rgb(50, 50, 50)
flex transition retained: true
-grid avoids full drives: true
-grid takes partial drive: true
grid display: block
grid padding: 2px
-grid transitioning avoids full drives: true
-grid transitioning takes partial drive: true
grid transitioning display: block
grid transitioning padding: 0px
grid paused sample: rgb(50, 50, 50)
grid transition retained: true
-absolute avoids full drives: true
-absolute takes partial drive: true
absolute display: block
absolute padding: 2px
absolute position retained: absolute
absolute computed float: none
-fixed avoids full drives: true
-fixed takes partial drive: true
fixed display: block
fixed padding: 2px
fixed position retained: fixed
fixed computed float: none
-floating avoids full drives: true
-floating takes partial drive: true
floating display: block
floating padding: 2px
float retained: left
-named slot in block avoids full drives: true
-named slot in block takes partial drive: true
named slot in block display: inline
named slot in block padding: 2px
named moved slot blockifies: block
-named slot in flex avoids full drives: true
-named slot in flex takes partial drive: true
named slot in flex display: block
named slot in flex padding: 2px
named moved slot restores inline: inline
-named flex slot avoids full drives: true
-named flex slot takes partial drive: true
named flex slot display: block
named flex slot padding: 2px
named specified float retained in flex: left
named contents slot restores inline: inline
-manual slot in block avoids full drives: true
-manual slot in block takes partial drive: true
manual slot in block display: inline
manual slot in block padding: 2px
manual moved slot blockifies: block
-manual slot in flex avoids full drives: true
-manual slot in flex takes partial drive: true
manual slot in flex display: block
manual slot in flex padding: 2px
manual moved slot restores inline: inline
-manual flex slot avoids full drives: true
-manual flex slot takes partial drive: true
manual flex slot display: block
manual flex slot padding: 2px
manual specified float retained in flex: left
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/partial-drive-sharing-across-parents.txt b/Tests/LibWeb/Text/expected/css/style-engine/partial-drive-sharing-across-parents.txt
index d99d95b29e7..0455e7fee1f 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/partial-drive-sharing-across-parents.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/partial-drive-sharing-across-parents.txt
@@ -1,4 +1,3 @@
-shared across different parent padding: true
updated backgrounds: true
inherit padding: 1px, 2px, 3px, 4px
substitute padding: 1px, 2px, 3px, 4px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/paused-transition-restyle-preserves-descendant-records.txt b/Tests/LibWeb/Text/expected/css/style-engine/paused-transition-restyle-preserves-descendant-records.txt
index 8e75cc006c7..4410a76c9b1 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/paused-transition-restyle-preserves-descendant-records.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/paused-transition-restyle-preserves-descendant-records.txt
@@ -1,5 +1,4 @@
paused child color: rgb(50, 50, 50)
-padding only updates parent records: true
paused child color after padding: rgb(50, 50, 50)
retargeted child color: rgb(125, 125, 125)
cancelled child color: rgb(200, 200, 200)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/persistent-style-sharing-cssom-revision.txt b/Tests/LibWeb/Text/expected/css/style-engine/persistent-style-sharing-cssom-revision.txt
index cceeb82987b..19fba01aea6 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/persistent-style-sharing-cssom-revision.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/persistent-style-sharing-cssom-revision.txt
@@ -1,4 +1,4 @@
-shared across transactions: true
+shared or reused across transactions: 0
initial colors: rgb(255, 0, 0), rgb(255, 0, 0)
CSSOM mutation colors: rgb(0, 128, 0), rgb(0, 128, 0)
inline mutation colors: rgb(0, 0, 255), rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/phase-clocks-and-work-counters.txt b/Tests/LibWeb/Text/expected/css/style-engine/phase-clocks-and-work-counters.txt
deleted file mode 100644
index 2be2b696a85..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/phase-clocks-and-work-counters.txt
+++ /dev/null
@@ -1,22 +0,0 @@
-partial rust additive: true
-partial cpp additive: true
-changed margin: 30px
-reachedStyleNodes: true
-enginePartialDrivesStarted: true
-enginePartialLonghandEvaluations: true
-enginePhysicalLonghandEvaluations: true
-engineDriveCopiedTableSlots: false
-arrival rust additive: true
-arrival cpp additive: true
-new color: rgb(12, 34, 56)
-coldNodesEvaluated: true
-candidateChecks: true
-engineFullDrivesStarted: true
-styleRecordsInterned: true
-styleRecordsReused: true
-quiescent rust additive: true
-quiescent cpp additive: true
-canceled rust additive: true
-canceled cpp additive: true
-diagnostic rust additive: true
-diagnostic cpp additive: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/placeholder-restyle-during-transition.txt b/Tests/LibWeb/Text/expected/css/style-engine/placeholder-restyle-during-transition.txt
index eef0d98cbb6..2750b3f0c00 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/placeholder-restyle-during-transition.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/placeholder-restyle-during-transition.txt
@@ -1,5 +1,4 @@
initial: opacity 1, font-size 10px
fading: opacity is above 0.9? true
restyled: font-size 20px
-restyled: C++ recomputations 0
restyled: opacity is above 0.9? true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/placeholder-rule-flip-restyles-backing-element.txt b/Tests/LibWeb/Text/expected/css/style-engine/placeholder-rule-flip-restyles-backing-element.txt
index deeac8f2bad..c85d4963f7a 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/placeholder-rule-flip-restyles-backing-element.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/placeholder-rule-flip-restyles-backing-element.txt
@@ -1,2 +1,2 @@
-step 1: rgb(0, 128, 0), C++ recomputations 0
-step 2: rgb(255, 0, 0), C++ recomputations 0
+step 1: rgb(0, 128, 0)
+step 2: rgb(255, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/positional-move-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/positional-move-mutations.txt
index bbf28abec20..75061cfb513 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/positional-move-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/positional-move-mutations.txt
@@ -1,9 +1,9 @@
-first-child begins matching (subject): [moved]
-first-child stops matching (subject): [moved]
-last-child begins matching (subject): [moved]
-last-child stops matching (subject): [moved]
-nth-last-child(2) begins matching (subject): [moved]
-nth-last-child(2) stops matching (subject): [moved]
+first-child begins matching (subject): [moved, target]
+first-child stops matching (subject): [moved, target]
+last-child begins matching (subject): [moved, target]
+last-child stops matching (subject): [moved, target]
+nth-last-child(2) begins matching (subject): [moved, target]
+nth-last-child(2) stops matching (subject): [moved, target]
first-child begins matching (descendant): [target]
first-child stops matching (descendant): [target]
last-child begins matching (descendant): [target]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/positional-of-type-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/positional-of-type-mutations.txt
index 0b7888f5718..80fb3262976 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/positional-of-type-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/positional-of-type-mutations.txt
@@ -1,4 +1,4 @@
other type leaves (subject): []
-same type leaves (subject): [subject]
+same type leaves (subject): [subject, target]
other type leaves (descendant): []
same type leaves (descendant): [target]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/post-layout-size-query-reaction.txt b/Tests/LibWeb/Text/expected/css/style-engine/post-layout-size-query-reaction.txt
deleted file mode 100644
index d5de98e90a5..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/post-layout-size-query-reaction.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-dependent color: rgb(1, 2, 3)
-layout recomputations within budget: true
-size-query scan visits: 1
-read recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/prefix-relation-survives-tree-scope-moves.txt b/Tests/LibWeb/Text/expected/css/style-engine/prefix-relation-survives-tree-scope-moves.txt
deleted file mode 100644
index e4cd9ee4e21..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/prefix-relation-survives-tree-scope-moves.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-a guarded target moves into the shadow tree: settles exactly, relation maintained
-the document guard no longer reaches it: true
-a guard arrives around it inside the shadow tree: settles exactly, relation maintained
-it moves back under the document guard: settles exactly, relation maintained
-the document guard reaches it again: true
-the document guard leaves as the shadow guard does: settles exactly, relation maintained
-a guard arrives in the shadow tree sharing the document's selector: settles exactly, relation maintained
-the shadow tree's own guard rule reaches the node born there: true
-that guard leaves: settles exactly, relation maintained
-the other target moves into that shadow tree: settles exactly, relation maintained
-a guard arrives around it there: settles exactly, relation maintained
-the shadow tree's own guard rule reaches both: true
-it moves back as the document guard returns: settles exactly, relation maintained
-the document guard reaches both again: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/presentation-attribute-shorthand-substitution.txt b/Tests/LibWeb/Text/expected/css/style-engine/presentation-attribute-shorthand-substitution.txt
index e0a72d19636..6028a446fda 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/presentation-attribute-shorthand-substitution.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/presentation-attribute-shorthand-substitution.txt
@@ -1,2 +1 @@
-C++ recomputations: 0
font-variant-caps: all-small-caps
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/private-pseudo-read-leaves-no-cached-record.txt b/Tests/LibWeb/Text/expected/css/style-engine/private-pseudo-read-leaves-no-cached-record.txt
index d588feb0973..54b3341c16e 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/private-pseudo-read-leaves-no-cached-record.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/private-pseudo-read-leaves-no-cached-record.txt
@@ -1,4 +1,2 @@
first ::before color: rgb(0, 128, 0)
second ::before color: rgb(0, 128, 0)
-first read derived a record: true
-second read derived its own: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-attr-beside-unread-attributes.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-attr-beside-unread-attributes.txt
index 0d74202c473..2a5159aeb15 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-attr-beside-unread-attributes.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-attr-beside-unread-attributes.txt
@@ -1,3 +1 @@
-C++ recomputations: 0
before: "two"
-engine pseudo records: 1
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-css-animations-settled-by-engine.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-css-animations-settled-by-engine.txt
index b7c9b33c726..c583bc88174 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-css-animations-settled-by-engine.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-css-animations-settled-by-engine.txt
@@ -2,4 +2,3 @@ started: [fade ::before] opacity 0.25, width 9.703125px, color rgb(0, 0, 0)
restyled beneath it: [fade ::before] opacity 0.25, width 9.703125px, color rgb(0, 0, 255)
another added: [fade ::before, grow ::before] opacity 0.25, width 10px, color rgb(0, 0, 0)
removed: [] opacity 1, width 9.703125px, color rgb(0, 0, 0)
-C++ style builds: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-read-beyond-its-element.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-read-beyond-its-element.txt
index 4c042d6d53a..41623d186ec 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-read-beyond-its-element.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-read-beyond-its-element.txt
@@ -1,3 +1,3 @@
-document ::before: --own document, demands left to the host 0
-shadow ::before: --own shadow, demands left to the host 0
-host ::after: --own host, demands left to the host 0
+document ::before: --own document
+shadow ::before: --own shadow
+host ::after: --own host
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-reads-past-synthetic-kinds.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-reads-past-synthetic-kinds.txt
index 695c5b50272..11ea5fde519 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-reads-past-synthetic-kinds.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-reads-past-synthetic-kinds.txt
@@ -1,8 +1,8 @@
-item::placeholder: rgb(0, 128, 0), engine drove it: true, left to the host: 0
-item::file-selector-button: rgb(0, 0, 255), engine drove it: true, left to the host: 0
-item::view-transition-group(name): rgb(0, 128, 128), engine drove it: true, left to the host: 0
-item::view-transition-image-pair(name): rgb(128, 0, 128), engine drove it: true, left to the host: 0
-item::view-transition-old(name): rgb(128, 128, 0), engine drove it: true, left to the host: 0
-item::view-transition-new(name): rgb(0, 0, 128), engine drove it: true, left to the host: 0
-file::placeholder: rgb(0, 128, 0), engine drove it: true, left to the host: 0
+item::placeholder: rgb(0, 128, 0)
+item::file-selector-button: rgb(0, 0, 255)
+item::view-transition-group(name): rgb(0, 128, 128)
+item::view-transition-image-pair(name): rgb(128, 0, 128)
+item::view-transition-old(name): rgb(128, 128, 0)
+item::view-transition-new(name): rgb(0, 0, 128)
+file::placeholder: rgb(0, 128, 0)
item::-webkit-scrollbar length: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-transition-starts-in-a-later-pass.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-transition-starts-in-a-later-pass.txt
new file mode 100644
index 00000000000..7b00c231d57
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-element-transition-starts-in-a-later-pass.txt
@@ -0,0 +1,3 @@
+element: rgb(128, 0, 128)
+::before: rgb(128, 0, 128)
+transitions: element color, ::before color
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-keyed-cascade-state.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-keyed-cascade-state.txt
index d1dec7d58dd..a1287cf59fe 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-keyed-cascade-state.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-keyed-cascade-state.txt
@@ -1,6 +1,4 @@
pseudo content changed: "after"
pseudo color changed: rgb(0, 0, 255)
-element cascade stopped: true
-pseudo delta consumed: true
element background changed: rgb(0, 0, 255)
pseudo content preserved: "after"
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-only-flip-keeps-element-winners.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-only-flip-keeps-element-winners.txt
index bb053aa19e8..8f1f2220886 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-only-flip-keeps-element-winners.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-only-flip-keeps-element-winners.txt
@@ -1,3 +1,2 @@
-cascade matches: 210
::before color: rgb(0, 128, 0)
padding: 29px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-records-beside-container-unit-substitution.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-records-beside-container-unit-substitution.txt
index 7f21ec1cb08..695773bcb78 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-records-beside-container-unit-substitution.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-records-beside-container-unit-substitution.txt
@@ -1,4 +1,2 @@
-C++ recomputations: 0
before: "changed" rgb(0, 128, 0)
marker: rgb(255, 0, 0)
-engine pseudo records: 2
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-records-of-display-none-element.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-records-of-display-none-element.txt
index 85e7cf3e6fd..d90f2a58cf0 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-records-of-display-none-element.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-records-of-display-none-element.txt
@@ -1,4 +1 @@
-C++ recomputations: 0
before: "changed" rgb(0, 128, 0)
-engine pseudo records: 1
-parent bails: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-transition-records-beside-host-record.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-transition-records-beside-host-record.txt
index 6163c8bbe73..5e5f9c809d3 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-transition-records-beside-host-record.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-transition-records-beside-host-record.txt
@@ -1,5 +1,2 @@
-C++ recomputations: 0
transitions: color ::before
before: rgb(128, 0, 128)
-engine pseudo records: 1
-property bails: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-winner-stop-kinds.txt b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-winner-stop-kinds.txt
index 4d5fe2ea85d..91fbc6535dc 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/pseudo-winner-stop-kinds.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/pseudo-winner-stop-kinds.txt
@@ -1,4 +1,3 @@
initial marker: rgb(255, 0, 0)
initial backdrop: rgb(255, 0, 0)
-marker exact cascade stops: 0
updated backdrop: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/published-answer-identity-reuses-cascade-input.txt b/Tests/LibWeb/Text/expected/css/style-engine/published-answer-identity-reuses-cascade-input.txt
deleted file mode 100644
index 131fa5f512a..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/published-answer-identity-reuses-cascade-input.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-first color: rgb(255, 0, 0)
-second color: rgb(255, 0, 0)
-published answers: 2
-engine records: 2
-shared payloads: 1
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/published-style-delta-gap.txt b/Tests/LibWeb/Text/expected/css/style-engine/published-style-delta-gap.txt
deleted file mode 100644
index 2c5732891a3..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/published-style-delta-gap.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-materialized gaps: 0
-record deltas applied: 1
-color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/published-style-delta-inherited-gap.txt b/Tests/LibWeb/Text/expected/css/style-engine/published-style-delta-inherited-gap.txt
deleted file mode 100644
index c9a912be71e..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/published-style-delta-inherited-gap.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-child list position: inside
-materialized gaps: 0
-record deltas applied: 2
-longhand evaluations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/registered-custom-property-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/registered-custom-property-engine-computed.txt
deleted file mode 100644
index 6f035914482..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/registered-custom-property-engine-computed.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-parents switched on: C++ recomputations 0, small --len 20px children 20px 20px, large --len 40px children 40px 40px
-::before switched on: C++ recomputations 0, --len 60px, width 60px
-first records: C++ recomputations 0, --len 40px, child 40px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/registered-custom-property-external-inputs.txt b/Tests/LibWeb/Text/expected/css/style-engine/registered-custom-property-external-inputs.txt
index 3cf7a1ea2cc..ad573b9c5da 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/registered-custom-property-external-inputs.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/registered-custom-property-external-inputs.txt
@@ -1,5 +1,3 @@
-environment refusals: 0
-environments the engine resolved: 2
--drawn in range: true
--drawn shared between elements: true
opacity reads --drawn: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/removing-stylesheet-preserves-descendant-animation-overlay.txt b/Tests/LibWeb/Text/expected/css/style-engine/removing-stylesheet-preserves-descendant-animation-overlay.txt
index 20ad7d8e762..906472456aa 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/removing-stylesheet-preserves-descendant-animation-overlay.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/removing-stylesheet-preserves-descendant-animation-overlay.txt
@@ -1,3 +1,2 @@
font status before removal: loading
-live overlays before removal: 1
PASS (did not crash)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/removing-stylesheet-preserves-non-layout-descendant-record.txt b/Tests/LibWeb/Text/expected/css/style-engine/removing-stylesheet-preserves-non-layout-descendant-record.txt
index ffec42c91ac..ff01f94aaf2 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/removing-stylesheet-preserves-non-layout-descendant-record.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/removing-stylesheet-preserves-non-layout-descendant-record.txt
@@ -1,6 +1,4 @@
font status before removal: loading
-live overlays before removal: 1
-prepared style-record activity before removal: true
later link has style record before removal: true
later link has layout before removal: false
non-layout pseudo-element has computed style before removal: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/reuse-exact-planning-facts.txt b/Tests/LibWeb/Text/expected/css/style-engine/reuse-exact-planning-facts.txt
deleted file mode 100644
index ac3839116d7..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/reuse-exact-planning-facts.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-no duplicate fact batch: true
-no complete fact-store scan: true
-no complete fact-store clone: true
-first target: rgb(1, 2, 3)
-last target: rgb(1, 2, 3)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/reuse-originating-element-matches.txt b/Tests/LibWeb/Text/expected/css/style-engine/reuse-originating-element-matches.txt
index 21c68c6fd12..26caaffaef9 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/reuse-originating-element-matches.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/reuse-originating-element-matches.txt
@@ -1,6 +1,3 @@
-cold node evaluations: 0
-candidate checks: 0
-rule matches emitted: 0
element: rgb(16, 17, 18)
before: rgb(19, 20, 21)
after: rgb(22, 23, 24)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/root-font-inputs-through-fixed-ancestors.txt b/Tests/LibWeb/Text/expected/css/style-engine/root-font-inputs-through-fixed-ancestors.txt
index 9f55e46a7ad..1fd097b0f51 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/root-font-inputs-through-fixed-ancestors.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/root-font-inputs-through-fixed-ancestors.txt
@@ -10,6 +10,3 @@ viewport root pseudo: 80px/60px
equal constant: 80px/60px, pseudo 120px/90px
viewport after constant: 80px/60px, pseudo 120px/90px; new: 80px/60px, pseudo 120px/90px
transitioning root: 60px/60px, pseudo 90px/90px
-root font preparation exercised: true
-root font fallback exercised: false
-engine computation exercised: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/rootless-style-update-holds-install-feedback.txt b/Tests/LibWeb/Text/expected/css/style-engine/rootless-style-update-holds-install-feedback.txt
index 828d3149381..9420561ffb9 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/rootless-style-update-holds-install-feedback.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/rootless-style-update-holds-install-feedback.txt
@@ -1,2 +1 @@
-transaction setups without a root: 0
child color with the root back: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/rule-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/rule-mutations.txt
index 9e6258fa05d..b7c4df11d5c 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/rule-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/rule-mutations.txt
@@ -10,11 +10,11 @@ edit a rule's declarations: [item]
remove a property from a rule: [item]
rewrite a rule's whole declaration block: [item]
insert a rule at the front of the sheet: [other]
-insert the same rule at the back: [other]
+insert the same rule at the back: []
delete both copies: [other]
insert a rule with a selector list: [other, bare]
-widen its selector to everything: WHOLE DOCUMENT
-narrow it back to one class: WHOLE DOCUMENT
+widen its selector to everything: [html, head, body, guard, animated, declarer, activation-match, activation-miss, card, error, button, list, row-one, row-two, script, out]
+narrow it back to one class: [html, head, body, guard, bare, animated, declarer, activation-match, activation-miss, card, error, button, list, row-one, row-two, script, out]
delete the listed rule: [other]
insert a rule using :has(): [button]
delete the relational rule: [button]
@@ -24,8 +24,8 @@ insert one bounded from the end: [row-two]
delete it: [row-two]
insert a positional rule behind a combinator: [row-one]
delete that one: [row-one]
-insert a rule with a nested one inside: [card, button]
-delete the nesting rule: [card, button]
+insert a rule with a nested one inside: [card, error, button]
+delete the nesting rule: [card, error, button]
rewrite a rule's declaration with the same value: []
insert and delete a rule in one transaction: []
make a rule's declaration important: [item]
@@ -48,15 +48,15 @@ delete the layer block: [other]
insert a scoped rule: [other]
delete the scoped rule: [other]
insert a @font-face rule: []
-insert a @counter-style rule: WHOLE DOCUMENT
-delete both at-rules: WHOLE DOCUMENT
-insert the @keyframes the animation names: [animated]
-edit a keyframe's declarations: [animated]
+insert a @counter-style rule: [row-one, row-two]
+delete both at-rules: [row-one, row-two]
+insert the @keyframes the animation names: []
+edit a keyframe's declarations: []
insert @keyframes nothing names: []
delete the unused keyframes: []
-register a custom property nobody uses: [consumer]
-unregister it: [consumer]
-register one that is declared and referenced: [consumer, declarer]
-unregister that one: [consumer, declarer]
-register one with an initial value: [consumer]
-unregister the initialized one: [consumer]
+register a custom property nobody uses: []
+unregister it: []
+register one that is declared and referenced: [declarer]
+unregister that one: [declarer]
+register one with an initial value: []
+unregister the initialized one: []
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/sampled-custom-property-child.txt b/Tests/LibWeb/Text/expected/css/style-engine/sampled-custom-property-child.txt
index 700e0cc7a61..aa964444656 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/sampled-custom-property-child.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/sampled-custom-property-child.txt
@@ -1,3 +1,2 @@
color: rgb(0, 128, 0)
-C++ recomputations: 0
background-color: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/selection-observability-with-environment-change.txt b/Tests/LibWeb/Text/expected/css/style-engine/selection-observability-with-environment-change.txt
index 5016305c59f..86dbd53d02a 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/selection-observability-with-environment-change.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/selection-observability-with-environment-change.txt
@@ -1,4 +1,2 @@
-engine computed records: true
-C++ recomputations: 0
styled ::selection: rgb(1, 2, 3) on rgb(4, 5, 6)
inner ::selection inherits: rgb(1, 2, 3) on rgb(4, 5, 6)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-activation.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-activation.txt
deleted file mode 100644
index 63880d4440d..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-activation.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-active color: rgb(255, 0, 0)
-answer patches: 2
-answer reuses: 2
-cold node evaluations: 0
-invalidated nodes: 2
-inactive color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-sheet-activation.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-sheet-activation.txt
deleted file mode 100644
index 63880d4440d..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-sheet-activation.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-active color: rgb(255, 0, 0)
-answer patches: 2
-answer reuses: 2
-cold node evaluations: 0
-invalidated nodes: 2
-inactive color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-sheet-attachment.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-sheet-attachment.txt
deleted file mode 100644
index e0b9ee6e5a3..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-sheet-attachment.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-attached color: rgb(255, 0, 0)
-answer patches: 2
-answer reuses: 2
-cold node evaluations: 0
-invalidated nodes: 2
-detached color: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-stops-at-unchanged-signature.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-stops-at-unchanged-signature.txt
deleted file mode 100644
index 49b3034f8bc..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-stops-at-unchanged-signature.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-delta patches: 2
-patch upqueries: 0
-unchanged stops: 2
-invalidated nodes: 0
-color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-updates-signature.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-updates-signature.txt
deleted file mode 100644
index f7471e24561..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-updates-signature.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-active color: rgb(255, 0, 0)
-selector truth additions: 1
-selector truth removals: 1
-selector truth cancellations: 0
-selector truth refreshes: 0
-match answer changes: 2
-match answer upqueries: 0
-delta patches: 2
-patch upqueries: 0
-answer reuses: 2
-cold node evaluations: 0
-invalidated nodes: 2
-computed style changes: 2
-inactive color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/shadow-host-pseudo-element-beside-animated-record.txt b/Tests/LibWeb/Text/expected/css/style-engine/shadow-host-pseudo-element-beside-animated-record.txt
index 2c0431287f0..edc7ef0e6da 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/shadow-host-pseudo-element-beside-animated-record.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/shadow-host-pseudo-element-beside-animated-record.txt
@@ -1,2 +1 @@
-environment refusals: 0
::before color: rgb(100, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/shared-selector-program-routes-once.txt b/Tests/LibWeb/Text/expected/css/style-engine/shared-selector-program-routes-once.txt
deleted file mode 100644
index 4e10c3bb348..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/shared-selector-program-routes-once.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-rules compiled: 100
-selector candidates tested: 100
-only local nodes invalidated: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/sheet-attachment-plan.txt b/Tests/LibWeb/Text/expected/css/style-engine/sheet-attachment-plan.txt
index d86fdd30adf..706017dc972 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/sheet-attachment-plan.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/sheet-attachment-plan.txt
@@ -1,4 +1,4 @@
-sheet attaches: [style, inside]
+sheet attaches: [inside]
sheet disables: [inside]
sheet enables: [inside]
sheet detaches: [inside]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/sheet-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/sheet-mutations.txt
index b2ead690ee2..c6003230af0 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/sheet-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/sheet-mutations.txt
@@ -1,23 +1,23 @@
-attach a sheet naming .item: [style, item, slottee]
+attach a sheet naming .item: [item, slottee]
detach it: [item, slottee]
-attach a sheet naming nothing present: [style]
+attach a sheet naming nothing present: []
detach that one: []
-attach a sheet naming an id: [style, by-id]
+attach a sheet naming an id: [by-id]
detach the id sheet: [by-id]
-attach a sheet naming a tag: [style, by-tag]
+attach a sheet naming a tag: [by-tag]
detach the tag sheet: [by-tag]
-attach a sheet naming an attribute: [style, by-attr]
+attach a sheet naming an attribute: [by-attr]
detach the attribute sheet: [by-attr]
-attach a sheet naming everything: WHOLE DOCUMENT
-detach the universal sheet: WHOLE DOCUMENT
-attach a sheet whose only rule is a negation: WHOLE DOCUMENT
-detach the negation sheet: WHOLE DOCUMENT
-attach a sheet of several rules, some matching: [style, item, slottee, by-id]
+attach a sheet naming everything: [html, head, body, guard, item, bare, host, slottee, dispatch, by-id, by-tag, by-attr, script, out]
+detach the universal sheet: [html, head, body, guard, item, bare, host, slottee, dispatch, by-id, by-tag, by-attr, script, out]
+attach a sheet whose only rule is a negation: [html, head, body, guard, item, bare, host, slottee, dispatch, by-id, by-tag, by-attr, script, out]
+detach the negation sheet: [html, head, body, guard, item, bare, host, slottee, dispatch, by-id, by-tag, by-attr, script, out]
+attach a sheet of several rules, some matching: [item, slottee, by-id]
detach the several-rule sheet: [item, slottee, by-id]
-attach two sheets at once: [two-a, two-b, item, slottee, by-id]
+attach two sheets at once: [item, slottee, by-id]
detach both at once: [item, slottee, by-id]
attach and detach a sheet in one transaction: []
-attach a sheet behind a media query that does not match: [style]
+attach a sheet behind a media query that does not match: []
insert a rule into the group whose condition does not hold: []
turn the condition on: [item, slottee]
turn it off again: [item, slottee]
@@ -38,15 +38,15 @@ unadopt it: [item, slottee]
detach and reattach a subtree holding a sheet: [dispatch, by-id, by-tag, by-attr, style]
adopt a sheet into a shadow root: [inner]
unadopt it from the shadow root: [inner]
-adopt one sheet into two scopes: [item, inner, slottee]
+adopt one sheet into two scopes: [item, slottee, inner]
unadopt it from the document only: [item, slottee]
unadopt it from the shadow root too: [inner]
adopt the same sheet twice over: [item, slottee]
unadopt the doubled sheet: [item, slottee]
detach and reattach a host with an empty shadow tree: [div]
-edit its adopted sheet after the round trip: [div]
-adopt a sheet reaching out of its scope: [host, slottee]
-unadopt the reaching sheet: [host, slottee]
+edit its adopted sheet after the round trip: []
+adopt a sheet reaching out of its scope: [host, slot, inner]
+unadopt the reaching sheet: [host, slot, inner]
adopt a sheet into a shadow root nothing has entered yet: []
fill the shadow tree: [widget]
edit the adopted sheet now that the tree is populated: [widget]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/slot-assigned-nodes-published-once-per-arrival.txt b/Tests/LibWeb/Text/expected/css/style-engine/slot-assigned-nodes-published-once-per-arrival.txt
deleted file mode 100644
index 1d40582c852..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/slot-assigned-nodes-published-once-per-arrival.txt
+++ /dev/null
@@ -1 +0,0 @@
-slot lists published: 2
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/slot-assignment-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/slot-assignment-mutations.txt
index 6b21858ca36..902fabff0cf 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/slot-assignment-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/slot-assignment-mutations.txt
@@ -1,4 +1,4 @@
-assign a slottable to a named slot: [a]
+assign a slottable to a named slot: []
rewrite the attribute to the same slot: []
send it to a slot that does not exist: [a]
send it back to the default slot: [a]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/slot-inherited-group-updates.txt b/Tests/LibWeb/Text/expected/css/style-engine/slot-inherited-group-updates.txt
index 18fd315baa5..efb1a34d81e 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/slot-inherited-group-updates.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/slot-inherited-group-updates.txt
@@ -1,8 +1,3 @@
-named: inherited color avoids full drives: true
-named: shared inherited groups are computed at most twice: true
-named: siblings reuse inherited group results: true
-named: inherited updates reuse cascades: true
-named: cascade completion is bounded: true
named: assigned colors: true
named: descendant colors: true
named: currentColor borders: true
@@ -14,11 +9,6 @@ named: custom property is inherited: rgb(255, 0, 0)
named: inherited text alignment: right
named: changed custom property: rgb(0, 128, 0)
named: changed font updates em width: 60px
-manual: inherited color avoids full drives: true
-manual: shared inherited groups are computed at most twice: true
-manual: siblings reuse inherited group results: true
-manual: inherited updates reuse cascades: true
-manual: cascade completion is bounded: true
manual: assigned colors: true
manual: descendant colors: true
manual: currentColor borders: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/slot-partial-variable-environment-move.txt b/Tests/LibWeb/Text/expected/css/style-engine/slot-partial-variable-environment-move.txt
index b7cb896739e..4405a0eb008 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/slot-partial-variable-environment-move.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/slot-partial-variable-environment-move.txt
@@ -1,4 +1,3 @@
-changed variables use partial descendant drives: true
changed width: 20px
changed shorthand: 2px
changed inherited color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/slot-style-propagation.txt b/Tests/LibWeb/Text/expected/css/style-engine/slot-style-propagation.txt
index 7e792786a61..403885df11a 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/slot-style-propagation.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/slot-style-propagation.txt
@@ -1,6 +1,6 @@
background change only reaches slot: true
child background: rgba(0, 0, 0, 0)
-inherited color avoids full drives: true
+inherited color avoids full passes: true
inherited color: rgb(0, 128, 0)
last child color: rgb(0, 128, 0)
shadow descendant color: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/slot-variable-environment-move.txt b/Tests/LibWeb/Text/expected/css/style-engine/slot-variable-environment-move.txt
index 1725b9223e5..8a1680787ac 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/slot-variable-environment-move.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/slot-variable-environment-move.txt
@@ -1,7 +1,5 @@
-unchanged variable inputs avoid descendant full drives: true
unchanged width: 10px
unused value follows slot: 1
-animated environment move avoids full drives: true
animated width after environment move: 10px
animation after environment move: 0.75
changed width: 20px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/slotted-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/slotted-mutations.txt
index f647a8f0122..865334250dd 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/slotted-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/slotted-mutations.txt
@@ -1,4 +1,4 @@
-disable the slotted element: [slotted]
-mark the slotted element: [slotted]
-disable an element outside the host: [outside]
-mark an element outside the host: [outside]
+disable the slotted element: [slotted, div, div, div]
+mark the slotted element: [slotted, div, div, div]
+disable an element outside the host: [outside, div, div]
+mark an element outside the host: []
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/slotted-shadow-host-context-order.txt b/Tests/LibWeb/Text/expected/css/style-engine/slotted-shadow-host-context-order.txt
index 64e3e13e286..36047fe7803 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/slotted-shadow-host-context-order.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/slotted-shadow-host-context-order.txt
@@ -1,4 +1,3 @@
-C++ recomputations: 0
color: rgb(0, 128, 0)
background-color: rgb(0, 128, 0)
::before color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/state-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/state-mutations.txt
index 7f20da19ca0..8d2dcccf58b 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/state-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/state-mutations.txt
@@ -1,9 +1,9 @@
focus the guard: [guard, item, within]
-blur the guard: [guard]
+blur the guard: [guard, item, within]
check the box: [after]
-uncheck it: []
+uncheck it: [after]
disable the box: [later]
-enable it: []
-make a field valid: [flag, div]
-make it invalid again: [flag, div]
+enable it: [later]
+make a field valid: [flag]
+make it invalid again: [flag]
set a state only the user-agent sheet mentions: [quiet]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-input-record-survives-unrelated-sheet.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-input-record-survives-unrelated-sheet.txt
index 8eff2a592c1..3be78c19595 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/style-input-record-survives-unrelated-sheet.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/style-input-record-survives-unrelated-sheet.txt
@@ -1,4 +1,2 @@
-input changed by parent style: 0
-input changed by parent custom properties: 0
item color: rgb(0, 0, 255)
wrap padding: 3px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-pass-guard-drops-reactions.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-pass-guard-drops-reactions.txt
deleted file mode 100644
index d590c8f3228..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/style-pass-guard-drops-reactions.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-published reaction batches: 1
-style pass guard reached: 0
-ninth reaction applied: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-query-gated-rule-waits-for-moving-container.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-query-gated-rule-waits-for-moving-container.txt
index c1cbe133a7f..8933b21634e 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/style-query-gated-rule-waits-for-moving-container.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/style-query-gated-rule-waits-for-moving-container.txt
@@ -1,3 +1,3 @@
-step 1: rgb(0, 128, 0), C++ recomputations 0
-step 2: rgb(255, 0, 0), C++ recomputations 0
-step 3: rgb(0, 128, 0), C++ recomputations 0
+step 1: rgb(0, 128, 0)
+step 2: rgb(255, 0, 0)
+step 3: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-read-consumes-complete-reaction-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-read-consumes-complete-reaction-batch.txt
deleted file mode 100644
index 1ea12079cf2..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/style-read-consumes-complete-reaction-batch.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-style read reaction batch runs: 1
-style read reaction elements: 1
-style read published reactions: 1
-style read recomputations: 0
-reaction color: rgb(0, 128, 0)
-subsequent update reaction batch runs: 0
-subsequent update recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-read-consumes-inheritance-reactions.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-read-consumes-inheritance-reactions.txt
deleted file mode 100644
index 510ecefbbdc..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/style-read-consumes-inheritance-reactions.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-read child color: rgb(0, 128, 0)
-sibling color: rgb(0, 128, 0)
-style read reaction batch runs: 1
-style read reaction elements: 1
-style read published reactions: 1
-style read recomputations: 0
-subsequent update reaction batch runs: 0
-subsequent update recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-donor-after-hidden-subtree.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-donor-after-hidden-subtree.txt
index 7d8bb49e860..d7194240cef 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-donor-after-hidden-subtree.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-donor-after-hidden-subtree.txt
@@ -1,3 +1,2 @@
-partial builds: 0
first: x 1px, fill rgb(255, 0, 0)
second: x 20px, fill rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-donor-first-build.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-donor-first-build.txt
index 21f079babae..8070d889ce2 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-donor-first-build.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-donor-first-build.txt
@@ -1,6 +1,2 @@
-differing sibling: 0 C++ longhand evaluations
-differing sibling: takes the donor's record: false
differing sibling: color rgb(0, 0, 255)
-identical sibling: 0 C++ longhand evaluations
-identical sibling: takes the donor's record: true
identical sibling: color rgb(255, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-previous-style-identity.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-previous-style-identity.txt
index 70de87aaf47..e7795824a16 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-previous-style-identity.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/style-sharing-previous-style-identity.txt
@@ -1,3 +1,2 @@
rgb(0, 128, 0)
rgb(0, 128, 0)
-shared computations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/style-update-fixture.txt b/Tests/LibWeb/Text/expected/css/style-engine/style-update-fixture.txt
index a37fbc78fce..1216412723a 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/style-update-fixture.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/style-update-fixture.txt
@@ -10,7 +10,6 @@ connected: insert: PASS
connected: remove: PASS
connected: move-out: PASS
connected: move-back: PASS
-connected: coverage: PASS
detached: ancestor-class-add: PASS
detached: ancestor-class-remove: PASS
detached: child-class-add: PASS
@@ -23,4 +22,3 @@ detached: insert: PASS
detached: remove: PASS
detached: move-out: PASS
detached: move-back: PASS
-detached: coverage: PASS
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/substituted-revert-keyword-reactions-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/substituted-revert-keyword-reactions-engine-computed.txt
deleted file mode 100644
index b482dd8a6fe..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/substituted-revert-keyword-reactions-engine-computed.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-initial: toggled=7px edited=3px ::before=5px
-ancestor class added: substitution refusals 0, C++ recomputations 0, toggled=9px edited=3px ::before=6px
-ancestor class removed: substitution refusals 0, C++ recomputations 0, toggled=7px edited=3px ::before=5px
-lower layer edited: substitution refusals 0, C++ recomputations 0, toggled=7px edited=11px ::before=5px
-::before inserted: substitution refusals 0, C++ recomputations 0, toggled=7px edited=11px ::before=5px 5px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/substituted-revert-keywords-in-longhands.txt b/Tests/LibWeb/Text/expected/css/style-engine/substituted-revert-keywords-in-longhands.txt
index 44720df063d..00b1e9edf42 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/substituted-revert-keywords-in-longhands.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/substituted-revert-keywords-in-longhands.txt
@@ -1,5 +1,5 @@
-inline: substitution refusals 0, C++ recomputations 0, color=rgb(0, 128, 0) font-size=20px margin-left=0px background-color=rgba(0, 0, 0, 0)
-background-color: substitution refusals 0, C++ recomputations 0, color=rgb(0, 128, 0) font-size=20px margin-left=0px background-color=rgba(0, 0, 0, 0)
-shorthand: substitution refusals 0, C++ recomputations 0, color=rgb(0, 128, 0) font-size=20px margin-left=0px background-color=rgba(0, 0, 0, 0)
-layered: substitution refusals 0, C++ recomputations 0, color=rgb(0, 128, 0) font-size=20px margin-left=7px background-color=rgba(0, 0, 0, 0)
-layered-shorthand: substitution refusals 0, C++ recomputations 0, color=rgb(0, 128, 0) font-size=20px margin-left=3px background-color=rgba(0, 0, 0, 0)
+inline: color=rgb(0, 128, 0) font-size=20px margin-left=0px background-color=rgba(0, 0, 0, 0)
+background-color: color=rgb(0, 128, 0) font-size=20px margin-left=0px background-color=rgba(0, 0, 0, 0)
+shorthand: color=rgb(0, 128, 0) font-size=20px margin-left=0px background-color=rgba(0, 0, 0, 0)
+layered: color=rgb(0, 128, 0) font-size=20px margin-left=7px background-color=rgba(0, 0, 0, 0)
+layered-shorthand: color=rgb(0, 128, 0) font-size=20px margin-left=3px background-color=rgba(0, 0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/substituted-state-admission.txt b/Tests/LibWeb/Text/expected/css/style-engine/substituted-state-admission.txt
index 8f6f352b17d..e22dd1c5fe6 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/substituted-state-admission.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/substituted-state-admission.txt
@@ -1,4 +1,3 @@
-substitution memo hits: 12
width: 10px
updated width: 20px
registered width: 30px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/substitution-cache-cssom-replacement.txt b/Tests/LibWeb/Text/expected/css/style-engine/substitution-cache-cssom-replacement.txt
index 8a0074262eb..33a78540784 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/substitution-cache-cssom-replacement.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/substitution-cache-cssom-replacement.txt
@@ -1,3 +1 @@
-engine substitutions used: true
-memo reused substitutions: true
replaced declarations use their own written value: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/substitution-declaration-cache.txt b/Tests/LibWeb/Text/expected/css/style-engine/substitution-declaration-cache.txt
index 8a9177c2e64..d763adde8fc 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/substitution-declaration-cache.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/substitution-declaration-cache.txt
@@ -1,7 +1,4 @@
-shared environment: 1 resolved, memoized: true
shared value: 7px
-later transaction: 0 resolved, memoized: true
later transaction value: 7px
-moved environment: 1 resolved, memoized: true
moved value: 9px
moved neighbour: 9px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/substitution-shorthand-cssom-replacement.txt b/Tests/LibWeb/Text/expected/css/style-engine/substitution-shorthand-cssom-replacement.txt
index 3ba4629d81f..fd657e93cc8 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/substitution-shorthand-cssom-replacement.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/substitution-shorthand-cssom-replacement.txt
@@ -1,3 +1,2 @@
missing substitution clears every longhand: true
-engine substituted shorthand replacements: true
replacement updates every longhand: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/substitution-sources-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/substitution-sources-engine-computed.txt
deleted file mode 100644
index bf7ca862be9..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/substitution-sources-engine-computed.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-inherit() in a custom property: substitution refusals 0, environment refusals 0, C++ recomputations 0, value 3px
-inherit() in a longhand: substitution refusals 0, environment refusals 0, C++ recomputations 0, value 3px
-if(media()): substitution refusals 0, environment refusals 0, C++ recomputations 0, value 10px
-if(supports()): substitution refusals 0, environment refusals 0, C++ recomputations 0, value 10px
-if(style()): substitution refusals 0, environment refusals 0, C++ recomputations 0, value 10px
-if(style()) range: substitution refusals 0, environment refusals 0, C++ recomputations 0, value 10px
-if(style()) registered: substitution refusals 0, environment refusals 0, C++ recomputations 0, value 10px
-env(): substitution refusals 0, environment refusals 0, C++ recomputations 0, value 10px
-custom function: substitution refusals 0, environment refusals 0, C++ recomputations 0, value 10px
-custom function with @media: substitution refusals 0, environment refusals 0, C++ recomputations 0, value 10px
-custom function with @container: substitution refusals 0, environment refusals 0, C++ recomputations 0, value 10px
-registered <length> in em: substitution refusals 0, environment refusals 0, C++ recomputations 0, value 30px
-random() shared: substitution refusals 0, environment refusals 0, C++ recomputations 0, value a length
-random() per element: substitution refusals 0, environment refusals 0, C++ recomputations 0, value a length
-mixed: substitution refusals 0, environment refusals 0, C++ recomputations 0, value 3px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/svg-image-resource-arrival.txt b/Tests/LibWeb/Text/expected/css/style-engine/svg-image-resource-arrival.txt
index b568a3ba949..20948f763e9 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/svg-image-resource-arrival.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/svg-image-resource-arrival.txt
@@ -1,2 +1 @@
-C++ recomputations: 0
image width: 120
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/svg-presentation-attribute-engine-records.txt b/Tests/LibWeb/Text/expected/css/style-engine/svg-presentation-attribute-engine-records.txt
index bf64a87dfa7..3cba57662d0 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/svg-presentation-attribute-engine-records.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/svg-presentation-attribute-engine-records.txt
@@ -1,14 +1,7 @@
-insertion: 1 engine records, 0 C++ recomputations
insertion: x 20px, fill rgb(0, 0, 255), width 10px
-x rewrite: 1 engine records, 0 C++ recomputations
x rewrite: x 30px, fill rgb(0, 0, 255), width 10px
-x and fill rewrite: 1 engine records, 0 C++ recomputations
x and fill rewrite: x 40px, fill rgb(255, 0, 0), width 10px
-fill removal: 1 engine records, 0 C++ recomputations
fill removal: x 40px, fill rgb(0, 0, 0), width 10px
-fill beaten by a rule: 1 engine records, 0 C++ recomputations
fill beaten by a rule: x 40px, fill rgb(0, 128, 0), width 10px
-attribute under the rule: 1 engine records, 0 C++ recomputations
attribute under the rule: x 40px, fill rgb(0, 128, 0), width 10px
-rule removed: 1 engine records, 0 C++ recomputations
rule removed: x 40px, fill rgb(255, 0, 0), width 10px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/synthetic-pseudo-element-reads.txt b/Tests/LibWeb/Text/expected/css/style-engine/synthetic-pseudo-element-reads.txt
index 1aa28e6a0c1..59bf100f880 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/synthetic-pseudo-element-reads.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/synthetic-pseudo-element-reads.txt
@@ -1,10 +1,10 @@
-target::selection: color rgb(70, 80, 90), background-color rgb(40, 50, 60), demands left to the host 0
-child::selection: color rgb(70, 80, 90), background-color rgb(40, 50, 60), demands left to the host 0
-target::first-line: color rgb(0, 0, 128), background-color rgba(0, 0, 0, 0), demands left to the host 0
-target::view-transition: color rgb(128, 0, 128), background-color rgba(0, 0, 0, 0), demands left to the host 0
-child::first-line: color rgb(0, 0, 0), background-color rgba(0, 0, 0, 0), demands left to the host 0
-target::marker: color rgb(0, 128, 0), background-color rgba(0, 0, 0, 0), demands left to the host 0
-target::selection: color rgb(255, 0, 255), background-color rgb(40, 50, 60), demands left to the host 0
-target::first-line: color rgb(255, 0, 255), background-color rgba(0, 0, 0, 0), demands left to the host 0
-target::view-transition: color rgb(255, 0, 255), background-color rgba(0, 0, 0, 0), demands left to the host 0
-target::marker: color rgb(255, 0, 255), background-color rgba(0, 0, 0, 0), demands left to the host 0
+target::selection: color rgb(70, 80, 90), background-color rgb(40, 50, 60)
+child::selection: color rgb(70, 80, 90), background-color rgb(40, 50, 60)
+target::first-line: color rgb(0, 0, 128), background-color rgba(0, 0, 0, 0)
+target::view-transition: color rgb(128, 0, 128), background-color rgba(0, 0, 0, 0)
+child::first-line: color rgb(0, 0, 0), background-color rgba(0, 0, 0, 0)
+target::marker: color rgb(0, 128, 0), background-color rgba(0, 0, 0, 0)
+target::selection: color rgb(255, 0, 255), background-color rgb(40, 50, 60)
+target::first-line: color rgb(255, 0, 255), background-color rgba(0, 0, 0, 0)
+target::view-transition: color rgb(255, 0, 255), background-color rgba(0, 0, 0, 0)
+target::marker: color rgb(255, 0, 255), background-color rgba(0, 0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/targeted-direct-read-uses-reaction-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/targeted-direct-read-uses-reaction-batch.txt
deleted file mode 100644
index 35b1bf27709..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/targeted-direct-read-uses-reaction-batch.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-color: rgb(0, 128, 0)
-reaction batch runs: 1
-reaction elements: 1
-published reactions: 1
-recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/targeted-inline-style-read-uses-reaction-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/targeted-inline-style-read-uses-reaction-batch.txt
deleted file mode 100644
index 81a8bd23b29..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/targeted-inline-style-read-uses-reaction-batch.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-target color: rgb(0, 0, 255)
-reaction color: rgb(0, 128, 0)
-reaction batch runs: 1
-reaction elements: 2
-published reactions: 2
-recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/targeted-read-uses-reaction-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/targeted-read-uses-reaction-batch.txt
deleted file mode 100644
index 35b1bf27709..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/targeted-read-uses-reaction-batch.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-color: rgb(0, 128, 0)
-reaction batch runs: 1
-reaction elements: 1
-published reactions: 1
-recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/targeted-state-read-uses-reaction-batch.txt b/Tests/LibWeb/Text/expected/css/style-engine/targeted-state-read-uses-reaction-batch.txt
deleted file mode 100644
index 67b6174b957..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/targeted-state-read-uses-reaction-batch.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-reaction color: rgb(0, 128, 0)
-reaction batch runs: 1
-reaction elements: 1
-published reactions: 1
-recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/top-layer-state-does-not-dirty-style.txt b/Tests/LibWeb/Text/expected/css/style-engine/top-layer-state-does-not-dirty-style.txt
index 278033f4db2..017411099f6 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/top-layer-state-does-not-dirty-style.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/top-layer-state-does-not-dirty-style.txt
@@ -1,12 +1,6 @@
+shown styled: popover
shown color: rgb(4, 5, 6)
-shown reaction batch runs: 1
-shown reaction elements: 2
-shown published reactions: 1
-shown recomputations: 0
-shown read recomputations: 0
+shown read styled: 0
+hidden styled: popover
hidden color: rgb(1, 2, 3)
-hidden reaction batch runs: 1
-hidden reaction elements: 2
-hidden published reactions: 1
-hidden recomputations within budget: true
-hidden read recomputations: 0
+hidden read styled: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/transition-definition-computed-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/transition-definition-computed-closure.txt
index 9be43d3050d..c59b38a7331 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/transition-definition-computed-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/transition-definition-computed-closure.txt
@@ -1,7 +1,5 @@
-disable unrelated longhands skipped: true
disable transition: 0s
disable color: rgb(0, 128, 0)
-restore unrelated longhands skipped: true
restore transition: 1s
restore color: rgb(0, 128, 0)
restored transition interpolates: 0.5
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/transition-fallback-keeps-partial-builds.txt b/Tests/LibWeb/Text/expected/css/style-engine/transition-fallback-keeps-partial-builds.txt
index 390f7067fe6..45ec1750ddb 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/transition-fallback-keeps-partial-builds.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/transition-fallback-keeps-partial-builds.txt
@@ -1,3 +1 @@
-partial builds: 0
-full builds: 0
color: rgb(0, 0, 255)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/transition-partial-drive.txt b/Tests/LibWeb/Text/expected/css/style-engine/transition-partial-drive.txt
index 6f3c82eba6b..13ca50a579e 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/transition-partial-drive.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/transition-partial-drive.txt
@@ -1,13 +1,6 @@
-complete full builds: 0
-complete longhand drive bounded: true
transitions started: true
midpoint color: rgb(50, 50, 50)
midpoint text-decoration-line: line-through
-recompute mid-transition full builds: 0
-recompute mid-transition longhand drive bounded: true
-mid-transition avoids full drives: true
running transition kept: true
running color: rgb(50, 50, 50)
-uncomplete full builds: 0
-uncomplete longhand drive bounded: true
uncompleted text-decoration-line: none
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/transition-row-moves-display.txt b/Tests/LibWeb/Text/expected/css/style-engine/transition-row-moves-display.txt
index 3d50f8a6a97..5d39498ecdc 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/transition-row-moves-display.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/transition-row-moves-display.txt
@@ -1,2 +1,2 @@
-hidden: C++ recomputations 0, display block, transitions display,opacity
-shown: C++ recomputations 0, display block, transitions
+hidden: display block, transitions display,opacity
+shown: display block, transitions
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/transition-step-row-with-children-settles-in-engine.txt b/Tests/LibWeb/Text/expected/css/style-engine/transition-step-row-with-children-settles-in-engine.txt
index b51754cf332..82d960013b1 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/transition-step-row-with-children-settles-in-engine.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/transition-step-row-with-children-settles-in-engine.txt
@@ -1,4 +1,3 @@
-C++ recomputations: 0
outer: rgb(128, 128, 0), transitions 1
inner: rgb(128, 128, 0), transitions 1
plain: rgb(128, 128, 0), transitions 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/transition-underlying-style-delta.txt b/Tests/LibWeb/Text/expected/css/style-engine/transition-underlying-style-delta.txt
index 34f4aaf2df4..f34b13d2ebf 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/transition-underlying-style-delta.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/transition-underlying-style-delta.txt
@@ -1,4 +1,3 @@
-base change takes partial drive: true
transition objects survive: true
transition color: rgb(50, 50, 50)
transition opacity: 0.5
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/tree-counting-child-reaction.txt b/Tests/LibWeb/Text/expected/css/style-engine/tree-counting-child-reaction.txt
deleted file mode 100644
index 9ba91e2f1a7..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-engine/tree-counting-child-reaction.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-target index: 2
-stable color: rgb(4, 5, 6)
-reaction batch runs: 1
-reaction elements: 1
-published reactions: 1
-update recomputations: 0
-read recomputations: 0
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/tree-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/tree-mutations.txt
index 73fd71c05e7..6c821aac196 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/tree-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/tree-mutations.txt
@@ -1,10 +1,10 @@
-prepend a row: [first, leaf, second, inserted]
-remove it again: [first, second]
+prepend a row: [inserted, first, leaf, second]
+remove it again: [first, leaf, second]
append a row: [third, appended]
remove the appended row: [third]
append two rows at once: [third, pairA, pairB]
remove both again: [third]
-insert between an anchor and its adjacent match: [adjacent, wedge]
+insert between an anchor and its adjacent match: [wedge, adjacent]
insert between a general sibling pair: [general-wedge]
remove the element two sibling rules look from: [trail, distant]
put it back: [lead, trail, distant]
@@ -12,7 +12,7 @@ remove a general sibling forest anchor: [forest-after, forest-later]
remove an adjacent sibling forest anchor: [adjacent-forest-after]
remove an adjacent sibling with an equivalent replacement: []
remove a sibling from a longer adjacent chain: [chain-target]
-move a row to the front without removing it: [first, leaf, second, third]
+move a row to the front without removing it: [third, first, leaf, second]
insert under the guard: [arrival]
move it out of the guard: [arrival]
disconnect it: []
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/uncached-record-gains-animation.txt b/Tests/LibWeb/Text/expected/css/style-engine/uncached-record-gains-animation.txt
index 11123758ebe..d28b2570524 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/uncached-record-gains-animation.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/uncached-record-gains-animation.txt
@@ -1,4 +1,3 @@
-C++ recomputations: 0
animation-name: grow
animations: 1
height: 10px
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/unchanged-variable-environment-computed-closure.txt b/Tests/LibWeb/Text/expected/css/style-engine/unchanged-variable-environment-computed-closure.txt
index 0cf18bb6235..84c79ac0702 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/unchanged-variable-environment-computed-closure.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/unchanged-variable-environment-computed-closure.txt
@@ -1,4 +1,3 @@
-unrelated longhands skipped: true
opacity: 0.5
margin: 20px
color: rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/unchanged-winners-after-viewport-environment-change.txt b/Tests/LibWeb/Text/expected/css/style-engine/unchanged-winners-after-viewport-environment-change.txt
index 9101631cb14..16653117ab6 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/unchanged-winners-after-viewport-environment-change.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/unchanged-winners-after-viewport-environment-change.txt
@@ -2,5 +2,3 @@ initial width: 30px
resized width: 50px
font-relative height: 20px
fixed width: 23px
-C++ recomputations: 0
-engine answered: true
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/unfocused-subject-skips-descendants.txt b/Tests/LibWeb/Text/expected/css/style-engine/unfocused-subject-skips-descendants.txt
index 88d639d2a13..a8290ccb197 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/unfocused-subject-skips-descendants.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/unfocused-subject-skips-descendants.txt
@@ -1,4 +1,4 @@
unfocused probe: rgb(0, 0, 0)
-recomputes with no focused element: 0
+styled with no focused element: 0
focused probe: rgb(0, 128, 0)
-recomputes with one focused element: 0
+styled with one focused element: 4
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/unroutable-subject-mutations.txt b/Tests/LibWeb/Text/expected/css/style-engine/unroutable-subject-mutations.txt
index 8be32b64cbb..8e835fb4c97 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/unroutable-subject-mutations.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/unroutable-subject-mutations.txt
@@ -1,5 +1,5 @@
-insert a rule naming :root: [html]
-delete it: [html]
+insert a rule naming :root: [html, head, body, parent, first-child, second-child, elsewhere, cousin, script, out]
+delete it: [html, head, body, parent, first-child, second-child, elsewhere, cousin, script, out]
insert :root compounded with a class: []
delete it: []
insert a rule for the children of an id: [first-child, second-child]
@@ -10,25 +10,25 @@ insert one naming either of two parents: [first-child, second-child, cousin]
delete it: [first-child, second-child, cousin]
insert one behind a sibling of a child: [second-child]
delete it: [second-child]
-insert a universal rule: WHOLE DOCUMENT
-delete it: WHOLE DOCUMENT
-insert a negation with no other constraint: WHOLE DOCUMENT
-delete it: WHOLE DOCUMENT
+insert a universal rule: [html, head, body, parent, first-child, second-child, elsewhere, cousin, script, out]
+delete it: [html, head, body, parent, first-child, second-child, elsewhere, cousin, script, out]
+insert a negation with no other constraint: [html, head, body, parent, first-child, second-child, elsewhere, cousin, script, out]
+delete it: [html, head, body, parent, first-child, second-child, elsewhere, cousin, script, out]
insert one behind a descendant combinator: [first-child, second-child]
delete it: [first-child, second-child]
insert one under either of two ancestors: [first-child, second-child, cousin]
delete it: [first-child, second-child, cousin]
insert one with both an ancestor and a parent: []
delete it: []
-insert a bare :has(): [html, body, parent]
-delete it: [html, body, parent]
+insert a bare :has(): [html, head, body, parent, first-child, second-child, elsewhere, cousin, script, out]
+delete it: [html, head, body, parent, first-child, second-child, elsewhere, cousin, script, out]
insert a bare :has() naming nothing present: []
delete it: []
-insert :has() over a child axis: [parent]
-delete it: [parent]
+insert :has() over a child axis: [parent, first-child, second-child]
+delete it: [parent, first-child, second-child]
insert :has() over the next-sibling axis: [first-child]
delete it: [first-child]
insert :has() over the following-sibling axis: [first-child]
delete it: [first-child]
-insert a negated :has(): WHOLE DOCUMENT
-delete it: WHOLE DOCUMENT
+insert a negated :has(): [head, first-child, second-child, elsewhere, cousin, script, out]
+delete it: [head, first-child, second-child, elsewhere, cousin, script, out]
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/unstyled-hidden-descendants.txt b/Tests/LibWeb/Text/expected/css/style-engine/unstyled-hidden-descendants.txt
index c4a86996f68..a40ec7a4bcd 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/unstyled-hidden-descendants.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/unstyled-hidden-descendants.txt
@@ -1,4 +1,3 @@
-hidden children deferred: true
targeted hidden read: 37px, rgb(10, 20, 30)
hidden mutation: 59px, rgb(40, 50, 60)
revealed children: 37, 59, 1300
diff --git a/Tests/LibWeb/Text/expected/css/style-engine/warm-prefix-cache-is-not-bypassed.txt b/Tests/LibWeb/Text/expected/css/style-engine/warm-prefix-cache-is-not-bypassed.txt
index 44b95b7fbd4..7d801c6efb5 100644
--- a/Tests/LibWeb/Text/expected/css/style-engine/warm-prefix-cache-is-not-bypassed.txt
+++ b/Tests/LibWeb/Text/expected/css/style-engine/warm-prefix-cache-is-not-bypassed.txt
@@ -1,3 +1 @@
rare subject updated: rgb(0, 128, 0)
-prefix convergence bypassed: false
-prefix convergence maintained: true
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-cold-matching.txt b/Tests/LibWeb/Text/expected/css/style-graph-cold-matching.txt
deleted file mode 100644
index 1a12beb23af..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-cold-matching.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-cold matching completed: true
-concrete matches cover the author rules: true
-checks below the product of nodes and rules: true
-stable across passes: true
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-compiles-selectors.txt b/Tests/LibWeb/Text/expected/css/style-graph-compiles-selectors.txt
deleted file mode 100644
index d7b4c286765..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-compiles-selectors.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-unsupported pseudo-classes: 0
-uninterned names: 0
-malformed: 0
-unsupported combinators: 0
-unsupported pseudo-elements: 0
-exact entries: true
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-document-rule-shadow-tree-routing.txt b/Tests/LibWeb/Text/expected/css/style-graph-document-rule-shadow-tree-routing.txt
deleted file mode 100644
index 2fc44571f16..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-document-rule-shadow-tree-routing.txt
+++ /dev/null
@@ -1 +0,0 @@
-reactions: wholeDocument=false elements=
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-element-facts.txt b/Tests/LibWeb/Text/expected/css/style-graph-element-facts.txt
deleted file mode 100644
index ea61c29e3c5..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-element-facts.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-initial facts published: true
-no scope markers: true
-tree delta recorded: true
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-host-guard-routing.txt b/Tests/LibWeb/Text/expected/css/style-graph-host-guard-routing.txt
deleted file mode 100644
index afe38c8abc8..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-host-guard-routing.txt
+++ /dev/null
@@ -1 +0,0 @@
-plan: wholeDocument=false elements=host
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-incremental-sheet-edits.txt b/Tests/LibWeb/Text/expected/css/style-graph-incremental-sheet-edits.txt
deleted file mode 100644
index c9a3d7a25c6..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-incremental-sheet-edits.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-insert at the front: 1 compiled
-insert in the middle: 1 compiled
-insert at the end: 1 compiled
-after three inserts: rgb(3, 3, 3)
-delete the winner: 0 compiled
-after deleting the winner: rgb(2, 2, 2)
-retarget one rule: 1 compiled
-after retargeting: rgb(2, 2, 2)
-insert a group of two: 2 compiled
-after the group: rgb(5, 5, 5)
-delete the group: 0 compiled
-after deleting the group: rgb(2, 2, 2)
-retarget all 6 rules: 6 compiled
-after retargeting all: rgb(2, 2, 2)
-delete all 6 rules: 0 compiled
-after deleting all: rgb(0, 0, 0)
-replaceSync with three rules: 3 compiled
-after replaceSync: rgb(6, 6, 6)
-replaceSync with one rule: 1 compiled
-after the second replaceSync: rgb(7, 7, 7)
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-normalizes-input.txt b/Tests/LibWeb/Text/expected/css/style-graph-normalizes-input.txt
deleted file mode 100644
index 680891be56f..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-normalizes-input.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-initial tree used one bulk load: true
-initial bulk load installed every connected element: true
-initial matching used one bulk load: true
-initial matching published every connected element: true
-recorded more raw mutations than normalized keys: true
-cancellations: true
-tree deltas recorded: true
-feature deltas recorded: true
-style nodes allocated: true
-no scope markers: true
-an arriving element's facts folded onto its arrival: true
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-program-deltas.txt b/Tests/LibWeb/Text/expected/css/style-graph-program-deltas.txt
deleted file mode 100644
index 283b8364fcc..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-program-deltas.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-attaching records program deltas: true
-detaching records more: true
-no scope markers: true
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-recompiles-mutated-sheets.txt b/Tests/LibWeb/Text/expected/css/style-graph-recompiles-mutated-sheets.txt
deleted file mode 100644
index 9f06880ed46..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-recompiles-mutated-sheets.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-plan: wholeDocument=false elements=target,item
-item colour: rgb(0, 128, 0)
-after delete: rgb(0, 0, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-state-facts.txt b/Tests/LibWeb/Text/expected/css/style-graph-state-facts.txt
deleted file mode 100644
index 1a675c202d7..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-state-facts.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-focusing records a state fact: true
-blurring records another: true
-no scope markers: true
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-transaction-reactions.txt b/Tests/LibWeb/Text/expected/css/style-graph-transaction-reactions.txt
deleted file mode 100644
index 534e5d855d1..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-transaction-reactions.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-descendants of the guard: 12
-reactions: wholeDocument=false elements=guard,deep
-unguarded focus: wholeDocument=false reaches the item=false
diff --git a/Tests/LibWeb/Text/expected/css/style-graph-waypoint-narrowing.txt b/Tests/LibWeb/Text/expected/css/style-graph-waypoint-narrowing.txt
deleted file mode 100644
index bad0be417c9..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-graph-waypoint-narrowing.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-spans under the guard: 3
-plan: wholeDocument=false elements=guard,qualified
diff --git a/Tests/LibWeb/Text/expected/css/style-invalidation/computed-style-read-consumes-complete-reaction-batch.txt b/Tests/LibWeb/Text/expected/css/style-invalidation/computed-style-read-consumes-complete-reaction-batch.txt
deleted file mode 100644
index 980b0f85112..00000000000
--- a/Tests/LibWeb/Text/expected/css/style-invalidation/computed-style-read-consumes-complete-reaction-batch.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-target color: rgb(12, 34, 56)
-unrelated color: rgb(65, 43, 21)
-PASS: the first style read consumed the complete reaction batch: true
diff --git a/Tests/LibWeb/Text/expected/css/style-invalidation/read-write-follows-inertness.txt b/Tests/LibWeb/Text/expected/css/style-invalidation/read-write-follows-inertness.txt
new file mode 100644
index 00000000000..3019ac6c0f7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/css/style-invalidation/read-write-follows-inertness.txt
@@ -0,0 +1,6 @@
+editable: matches true, rgb(0, 128, 0)
+under an inert ancestor: matches false, rgb(0, 0, 255)
+no longer inert: matches true, rgb(0, 128, 0)
+inserted under an inert parent: matches false, rgb(0, 0, 255)
+inserted again: matches true, rgb(0, 128, 0)
+removed while inert and inserted again: matches true, rgb(0, 128, 0)
diff --git a/Tests/LibWeb/Text/expected/css/style-sharing-across-shadow-roots-with-same-font.txt b/Tests/LibWeb/Text/expected/css/style-sharing-across-shadow-roots-with-same-font.txt
index 31f508c2671..8537e6ae940 100644
--- a/Tests/LibWeb/Text/expected/css/style-sharing-across-shadow-roots-with-same-font.txt
+++ b/Tests/LibWeb/Text/expected/css/style-sharing-across-shadow-roots-with-same-font.txt
@@ -1,3 +1,4 @@
-full drives for 20 more shadow trees: 0
+full passes for 20 more shadow trees: 0
+shared elements: 20
span font: 13px 700
all spans alike: true
diff --git a/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-imported-broad-invalidation.txt b/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-imported-broad-invalidation.txt
index 2ce190f32bf..27f5f10fd5e 100644
--- a/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-imported-broad-invalidation.txt
+++ b/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-imported-broad-invalidation.txt
@@ -1,4 +1,5 @@
-PASS: imported layer-only stylesheet add restyles nothing
-PASS: imported layer-only stylesheet remove restyles nothing
+imported layer-only stylesheet add restyles nothing, last pass styled <= 1: true
+imported layer-only stylesheet remove restyles nothing, styled <= 1: true
PASS: imported layer reorder reaches the layered element
-PASS: imported layer reorder stays bounded
+imported layer reorder stays bounded, last pass styled <= 8: true
+imported layer reorder runs no full pass: true
diff --git a/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-inactive-media-no-broad-invalidation.txt b/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-inactive-media-no-broad-invalidation.txt
index e4524895b7c..6bd7267bb5e 100644
--- a/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-inactive-media-no-broad-invalidation.txt
+++ b/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-inactive-media-no-broad-invalidation.txt
@@ -1,2 +1,2 @@
-PASS: inactive media stylesheet add publishes no broad reactions
-PASS: inactive media stylesheet remove publishes no broad reactions
+inactive media stylesheet add publishes no broad reactions, styled <= 1: true
+inactive media stylesheet remove publishes no broad reactions, styled <= 1: true
diff --git a/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-layer-order-invalidation.txt b/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-layer-order-invalidation.txt
index a29ad363599..d1c3ff1b356 100644
--- a/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-layer-order-invalidation.txt
+++ b/Tests/LibWeb/Text/expected/css/stylesheet-add-remove-layer-order-invalidation.txt
@@ -1,3 +1,3 @@
-PASS: layer-only stylesheet add restyles nothing but itself
-PASS: layer-only stylesheet remove restyles nothing but itself
+layer-only stylesheet add restyles nothing but itself, styled <= 1: true
+layer-only stylesheet remove restyles nothing but itself, styled <= 1: true
PASS: layer reorder reaches the layered element
diff --git a/Tests/LibWeb/Text/expected/css/text-decoration-line-style-sharing.txt b/Tests/LibWeb/Text/expected/css/text-decoration-line-style-sharing.txt
index 71eced9d398..242d9b54808 100644
--- a/Tests/LibWeb/Text/expected/css/text-decoration-line-style-sharing.txt
+++ b/Tests/LibWeb/Text/expected/css/text-decoration-line-style-sharing.txt
@@ -1,4 +1,4 @@
none
none
none
-shared computations: 2
+spans taking another's record >= 2: true
diff --git a/Tests/LibWeb/Text/expected/css/transition-starts-on-shared-style.txt b/Tests/LibWeb/Text/expected/css/transition-starts-on-shared-style.txt
index 21bf50173af..26d0aeca93b 100644
--- a/Tests/LibWeb/Text/expected/css/transition-starts-on-shared-style.txt
+++ b/Tests/LibWeb/Text/expected/css/transition-starts-on-shared-style.txt
@@ -1,4 +1,3 @@
-shared computations: 0
donor: color=rgb(200, 200, 200) animations=0
stale: color=rgb(100, 100, 100) animations=1
settled: color=rgb(0, 0, 0) animations=0
diff --git a/Tests/LibWeb/Text/expected/css/user-agent-selectors-compile-once-per-process.txt b/Tests/LibWeb/Text/expected/css/user-agent-selectors-compile-once-per-process.txt
index 5465c9b8cf8..fb8629ca1c3 100644
--- a/Tests/LibWeb/Text/expected/css/user-agent-selectors-compile-once-per-process.txt
+++ b/Tests/LibWeb/Text/expected/css/user-agent-selectors-compile-once-per-process.txt
@@ -1,3 +1,5 @@
margin-top from the user-agent sheet: 16px
-style rules added: true
-selector entries compiled: 0
+user-agent rule index shared, not built: true
+no user-agent selector compiled again: true
+index builds for the added rule: 0
+selectors compiled for the added rule, at most its two: true
diff --git a/Tests/LibWeb/Text/expected/simple-selector-queries-do-not-submit-style-input.txt b/Tests/LibWeb/Text/expected/simple-selector-queries-do-not-submit-style-input.txt
deleted file mode 100644
index b5f9332e1da..00000000000
--- a/Tests/LibWeb/Text/expected/simple-selector-queries-do-not-submit-style-input.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-tag matches: true
-id matches: true
-classes match: true
-closest: true
-style inputs submitted: 0
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-animations/Document-getAnimations.tentative.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-animations/Document-getAnimations.tentative.txt
index 24aa2d2e508..ef53b104cea 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-animations/Document-getAnimations.tentative.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-animations/Document-getAnimations.tentative.txt
@@ -2,14 +2,14 @@ Harness status: OK
Found 18 tests
-12 Pass
-6 Fail
+15 Pass
+3 Fail
Pass getAnimations for non-animated content
Pass getAnimations for CSS Animations
Pass Order of CSS Animations - within an element unaffected by start time
Pass Order of CSS Animations - within an element
-Fail Order of CSS Animations - across elements
-Fail Order of CSS Animations - across and within elements
+Pass Order of CSS Animations - across elements
+Pass Order of CSS Animations - across and within elements
Pass Order of CSS Animations - markup-bound vs free animations
Fail Order of CSS Animations - free animation vs CSS Transitions
Fail Order of CSS Animations - free animations
@@ -21,4 +21,4 @@ Pass CSS Animations canceled via the API are not returned
Pass CSS Animations canceled and restarted via the API are returned
Pass pseudo element with replaced target does not affect animation ordering
Pass CSS Animations targetting (pseudo-)elements should have correct order after sorting
-Fail CSS Animations targetting (pseudo-)elements should have correct order after sorting (::marker)
\ No newline at end of file
+Pass CSS Animations targetting (pseudo-)elements should have correct order after sorting (::marker)
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-animations/display-none-dont-cancel.tentative.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-animations/display-none-dont-cancel.tentative.txt
index 3682249db2f..b9614634fbd 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-animations/display-none-dont-cancel.tentative.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-animations/display-none-dont-cancel.tentative.txt
@@ -2,10 +2,9 @@ Harness status: OK
Found 5 tests
-4 Pass
-1 Fail
+5 Pass
Pass display:none animating to display:inline should be inline for the whole animation.
Pass A CSS variable of display:none animating to display:inline should be inline for the whole animation.
Pass Animating from display:none to display:none should not cancel the animation.
Pass Animating from display:none to display:none with an intermediate variable should not cancel the animation.
-Fail Animating a variable of "none" which gets set to display elsewhere should not cancel the animation.
\ No newline at end of file
+Pass Animating a variable of "none" which gets set to display elsewhere should not cancel the animation.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-pseudo/parsing/marker-supported-properties-in-animation.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-pseudo/parsing/marker-supported-properties-in-animation.txt
index b6a13012f01..d1499573cf3 100644
--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-pseudo/parsing/marker-supported-properties-in-animation.txt
+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-pseudo/parsing/marker-supported-properties-in-animation.txt
@@ -2,56 +2,56 @@ Harness status: OK
Found 96 tests
-52 Pass
-44 Fail
+70 Pass
+26 Fail
Pass Animation of font in ::marker
Pass Animation of font-family in ::marker
-Fail Animation of font-feature-settings in ::marker
-Fail Animation of font-kerning in ::marker
+Pass Animation of font-feature-settings in ::marker
+Pass Animation of font-kerning in ::marker
Pass Animation of font-size in ::marker
-Fail Animation of font-size-adjust in ::marker
+Pass Animation of font-size-adjust in ::marker
Pass Animation of font-stretch in ::marker
Pass Animation of font-style in ::marker
-Fail Animation of font-synthesis in ::marker
-Fail Animation of font-synthesis-small-caps in ::marker
-Fail Animation of font-synthesis-style in ::marker
-Fail Animation of font-synthesis-weight in ::marker
+Pass Animation of font-synthesis in ::marker
+Pass Animation of font-synthesis-small-caps in ::marker
+Pass Animation of font-synthesis-style in ::marker
+Pass Animation of font-synthesis-weight in ::marker
Pass Animation of font-variant in ::marker
Pass Animation of font-variant-caps in ::marker
-Fail Animation of font-variant-east-asian in ::marker
-Fail Animation of font-variant-ligatures in ::marker
-Fail Animation of font-variant-numeric in ::marker
-Fail Animation of font-variant-position in ::marker
+Pass Animation of font-variant-east-asian in ::marker
+Pass Animation of font-variant-ligatures in ::marker
+Pass Animation of font-variant-numeric in ::marker
+Pass Animation of font-variant-position in ::marker
Pass Animation of font-weight in ::marker
Pass Animation of line-height in ::marker
-Fail Animation of white-space in ::marker
-Fail Animation of color in ::marker
+Pass Animation of white-space in ::marker
+Pass Animation of color in ::marker
Fail Animation of text-combine-upright in ::marker
Pass Animation of unicode-bidi in ::marker
Pass Animation of direction in ::marker
-Fail Animation of content in ::marker
+Pass Animation of content in ::marker
Fail Animation of hyphens in ::marker
-Fail Animation of letter-spacing in ::marker
+Pass Animation of letter-spacing in ::marker
Fail Animation of line-break in ::marker
-Fail Animation of overflow-wrap in ::marker
-Fail Animation of tab-size in ::marker
-Fail Animation of text-transform in ::marker
-Fail Animation of word-break in ::marker
-Fail Animation of word-spacing in ::marker
-Fail Animation of text-decoration-skip-ink in ::marker
+Pass Animation of overflow-wrap in ::marker
+Pass Animation of tab-size in ::marker
+Pass Animation of text-transform in ::marker
+Pass Animation of word-break in ::marker
+Pass Animation of word-spacing in ::marker
+Pass Animation of text-decoration-skip-ink in ::marker
Fail Animation of text-emphasis in ::marker
Fail Animation of text-emphasis-color in ::marker
-Fail Animation of text-emphasis-position in ::marker
+Pass Animation of text-emphasis-position in ::marker
Fail Animation of text-emphasis-style in ::marker
-Fail Animation of text-shadow in ::marker
-Fail Animation of cursor in ::marker
-Pass Animation of display in ::marker
-Pass Animation of position in ::marker
-Pass Animation of float in ::marker
+Pass Animation of text-shadow in ::marker
+Pass Animation of cursor in ::marker
+Fail Animation of display in ::marker
+Fail Animation of position in ::marker
+Fail Animation of float in ::marker
Fail Animation of list-style in ::marker
-Pass Animation of list-style-image in ::marker
-Pass Animation of list-style-position in ::marker
-Pass Animation of list-style-type in ::marker
+Fail Animation of list-style-image in ::marker
+Fail Animation of list-style-position in ::marker
+Fail Animation of list-style-type in ::marker
Pass Transition of font in ::marker
Pass Transition of font-family in ::marker
Pass Transition of font-feature-settings in ::marker
diff --git a/Tests/LibWeb/Text/input/DOM/complex-selector-queries-match-with-pending-style-input.html b/Tests/LibWeb/Text/input/DOM/complex-selector-queries-match-with-pending-style-input.html
deleted file mode 100644
index 8a8210f296a..00000000000
--- a/Tests/LibWeb/Text/input/DOM/complex-selector-queries-match-with-pending-style-input.html
+++ /dev/null
@@ -1,90 +0,0 @@
-<!DOCTYPE html>
-<script src="../include.js"></script>
-<div id="root" class="x">
- <ul class="list">
- <li class="a"><span class="toggle">1</span><em>e</em><em>f</em></li>
- <li class="b" data-k="v"><span>2</span><b>b</b></li>
- <li class="a b"><span class="toggle">3</span><span>4</span><em>g</em></li>
- <li class="c"><em>h</em></li>
- <li class="b"><div class="y"><p class="a">p</p><p class="b">q</p></div></li>
- </ul>
- <div class="y"></div><div class="z"><span class="toggle">5</span></div>
- <section><article><b data-k>x</b></article></section>
- <svg><g><circle class="toggle"/><CIRCLE/></g></svg>
- <div id="host"></div>
-</div>
-<script>
- test(() => {
- const selectors = [
- "li .toggle",
- "ul > li",
- "li:nth-child(2n+1) > span",
- "li:nth-last-child(2) em",
- "li:first-child *",
- "li:last-child p",
- "li:only-child",
- "div > p:only-child",
- "span:first-of-type",
- "span:last-of-type",
- "em:only-of-type",
- "em:nth-of-type(2)",
- "em:nth-last-of-type(1)",
- "li + li",
- "li ~ li.b",
- "div .a .b",
- "#root li.a > span",
- ".x > .y + .z",
- ".y ~ .z > .toggle",
- "[data-k] b",
- "[data-k=v] ~ *",
- "section b[data-k]",
- "LI .TOGGLE",
- "svg circle",
- "g > CIRCLE",
- "html:first-child body",
- "li:first-child, em + em",
- "ul li:nth-child(odd) em:last-child",
- "li:nth-child(-n+2) span",
- "#host span",
- "div > span:first-child",
- ".a span",
- "p > span:only-child",
- ];
- const shadow = host.attachShadow({ mode: "open" });
- shadow.innerHTML = `<div class="a"><span class="toggle"></span><p><span></span></p></div><span></span>`;
- const everything = Array.from(document.querySelectorAll("*")).concat(Array.from(shadow.querySelectorAll("*")));
- const describe = elements => Array.from(elements, element => everything.indexOf(element)).join(" ");
- let tick = 0;
- let settledWithPendingInput = 0;
- function withPendingInput(callback) {
- ++tick;
- for (const element of everything)
- element.dataset.tick = tick;
- const before = internals.styleEngineCounters().rawMutationRecords;
- const result = callback();
- if (internals.styleEngineCounters().rawMutationRecords !== before)
- ++settledWithPendingInput;
- return result;
- }
- function settled(callback) {
- internals.updateStyle();
- return callback();
- }
- for (const selector of selectors) {
- const results = [];
- for (const mode of [withPendingInput, settled]) {
- const all = mode(() => describe(document.querySelectorAll(selector)));
- const first = mode(() => describe([document.querySelector(selector)].filter(Boolean)));
- const scoped = mode(() => describe(root.querySelectorAll(selector)));
- const inShadow = mode(() => describe(shadow.querySelectorAll(selector)));
- const matching = mode(() => describe(everything.filter(element => element.matches(selector))));
- const closest = mode(() => everything.map(element => everything.indexOf(element.closest(selector))).join(" "));
- results.push([all, first, scoped, inShadow, matching, closest]);
- }
- const [pending, settledResults] = results;
- const same = pending.every((value, index) => value === settledResults[index]);
- println(`${selector}: [${pending[0]}] [${pending[3]}] ${same ? "same" : `DIFFERS: with pending input ${JSON.stringify(pending)}, without ${JSON.stringify(settledResults)}`}`);
- }
- println(`queries that settled pending input: ${settledWithPendingInput}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/Editing/insertHTML-redundant-style-with-substitution-function.html b/Tests/LibWeb/Text/input/Editing/insertHTML-redundant-style-with-substitution-function.html
new file mode 100644
index 00000000000..2244861291f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Editing/insertHTML-redundant-style-with-substitution-function.html
@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<style>
+ #editor {
+ --three: 3px;
+ }
+ #editor .matched {
+ margin: 3px;
+ }
+</style>
+<div id="editor" contenteditable>ab</div>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const editor = document.getElementById("editor");
+ for (const html of [
+ `<span style="--own: 7px; margin: var(--own)">x</span>`,
+ `<span style="margin: var(--three); color: red">x</span>`,
+ `<span class="matched" style="margin: var(--three)">x</span>`,
+ `<span style="background: var(--undefined)">x</span>`,
+ `<span style="margin-inline: var(--three)">x</span>`,
+ `<span style="border: var(--three) solid">x</span>`,
+ `<span style="border: var(--undefined) solid; color: red">x</span>`,
+ `<span style="margin: var(--three); margin-left: 1px">x</span>`,
+ ]) {
+ editor.textContent = "ab";
+ getSelection().collapse(editor.firstChild, 1);
+ document.execCommand("insertHTML", false, html);
+ println(editor.innerHTML);
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Internals/internals-object-results-receiver-realm.html b/Tests/LibWeb/Text/input/Internals/internals-object-results-receiver-realm.html
index ab4f4bcf1de..f0f62cb8a89 100644
--- a/Tests/LibWeb/Text/input/Internals/internals-object-results-receiver-realm.html
+++ b/Tests/LibWeb/Text/input/Internals/internals-object-results-receiver-realm.html
@@ -8,7 +8,7 @@
const counters = other.internals.getStyleInvalidationCounters.call(internals);
println(`style counters has null prototype: ${Object.getPrototypeOf(counters) === null}`);
- println(`style counters has reaction batches: ${"styleEngineReactionBatchRuns" in counters}`);
+ println(`style counters has animated overlay builds: ${"animatedStyleOverlayBuilds" in counters}`);
const scrollState = other.internals.compositorScrollState.call(internals);
println(`compositor scroll state has null prototype: ${Object.getPrototypeOf(scrollState) === null}`);
diff --git a/Tests/LibWeb/Text/input/Layout/table-box-containing-block-of-abspos-in-cell.html b/Tests/LibWeb/Text/input/Layout/table-box-containing-block-of-abspos-in-cell.html
new file mode 100644
index 00000000000..165e1c3947b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Layout/table-box-containing-block-of-abspos-in-cell.html
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<style>
+ body { margin: 0; }
+ table {
+ transform: translateX(0);
+ margin: 10px 20px;
+ padding: 5px;
+ border: 3px solid;
+ border-spacing: 2px;
+ }
+ td { padding: 0; }
+ caption { height: 30px; }
+ .inset { position: absolute; top: 1px; left: 1px; width: 10px; height: 10px; }
+ .static { position: absolute; width: 10px; height: 10px; }
+</style>
+<table id="table">
+ <caption>caption</caption>
+ <tr><td id="cell"><div class="inset" id="inset"></div><div class="static" id="static"></div><div style="width: 50px; height: 50px"></div></td></tr>
+</table>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const rect = id => document.getElementById(id).getBoundingClientRect();
+ for (const id of ["cell", "inset", "static"])
+ println(`${id}: ${rect(id).x},${rect(id).y}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-geometry-in-template-contents.html b/Tests/LibWeb/Text/input/SVG/svg-geometry-in-template-contents.html
new file mode 100644
index 00000000000..089634420a8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-geometry-in-template-contents.html
@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ const svgNamespace = "http://www.w3.org/2000/svg";
+
+ function shapeIn(document) {
+ const path = document.createElementNS(svgNamespace, "path");
+ path.setAttribute("d", "M0 0 L10 0");
+ return path;
+ }
+
+ function measure(name, path) {
+ println(`${name}: ${path.getTotalLength()} ${path.getPointAtLength(4).x} ${path.isPointInStroke(new DOMPoint(1, 0))}`);
+ }
+
+ test(() => {
+ // NB: This comes first, as the window's document has not been styled yet.
+ const template = document.createElement("template");
+ template.innerHTML = `<svg xmlns="${svgNamespace}"><path d="M0 0 L10 0"/></svg>`;
+ measure("in a template's fragment", template.content.querySelector("path"));
+
+ const contents = document.createElement("template").content.ownerDocument;
+ const root = contents.createElement("html");
+ const svg = contents.createElementNS(svgNamespace, "svg");
+ const nested = shapeIn(contents);
+ svg.append(nested);
+ root.append(svg);
+ contents.append(root);
+ measure("connected in the contents' document", nested);
+
+ root.remove();
+ const asRoot = shapeIn(contents);
+ contents.append(asRoot);
+ measure("the document element of the contents' document", asRoot);
+
+ // FIXME: This is a known limit, not the right answer: the shape has a path and should measure 10. An engine
+ // computes nothing before its document has a document element.
+ const iframe = document.createElement("iframe");
+ document.body.append(iframe);
+ const frameDocument = iframe.contentDocument;
+ frameDocument.documentElement.remove();
+ const frameTemplate = frameDocument.createElement("template");
+ const framePath = shapeIn(frameTemplate.content.ownerDocument);
+ frameTemplate.content.append(framePath);
+ println(`in a window whose document has no document element: ${framePath.getTotalLength()}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SVG/svg-geometry-registered-random-custom-property.html b/Tests/LibWeb/Text/input/SVG/svg-geometry-registered-random-custom-property.html
new file mode 100644
index 00000000000..8595aa31875
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SVG/svg-geometry-registered-random-custom-property.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<style>
+ @property --registered {
+ syntax: "<length>";
+ inherits: true;
+ initial-value: 0px;
+ }
+</style>
+<script src="../include.js"></script>
+<script>
+ test(() => {
+ const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
+ path.setAttribute("d", "M0 0 L10 0");
+ path.style.cssText = "--registered: random(1px, 5px); stroke-width: var(--registered)";
+ println(`outside the document: ${path.getTotalLength()}`);
+
+ const template = document.createElement("template");
+ template.content.append(path);
+ println(`in a template's fragment: ${path.getTotalLength()}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/ShadowDOM/descendant-slot-invalidation-scan-stays-linear.html b/Tests/LibWeb/Text/input/ShadowDOM/descendant-slot-invalidation-scan-stays-linear.html
index eacd8e02203..94e730f9009 100644
--- a/Tests/LibWeb/Text/input/ShadowDOM/descendant-slot-invalidation-scan-stays-linear.html
+++ b/Tests/LibWeb/Text/input/ShadowDOM/descendant-slot-invalidation-scan-stays-linear.html
@@ -14,11 +14,8 @@
}
getComputedStyle(current).color;
- internals.resetStyleInvalidationCounters();
-
root.style.color = "rgb(0, 128, 0)";
println(`deep child color: ${getComputedStyle(current).color}`);
-
});
</script>
diff --git a/Tests/LibWeb/Text/input/ShadowDOM/specified-inherited-style-invalidates-shadow-tree.html b/Tests/LibWeb/Text/input/ShadowDOM/specified-inherited-style-invalidates-shadow-tree.html
index 9f5880b7d2c..f7d5712ff0d 100644
--- a/Tests/LibWeb/Text/input/ShadowDOM/specified-inherited-style-invalidates-shadow-tree.html
+++ b/Tests/LibWeb/Text/input/ShadowDOM/specified-inherited-style-invalidates-shadow-tree.html
@@ -129,11 +129,10 @@
println(`explicit inherit initial child margin-left: ${getComputedStyle(explicitInheritChild).marginLeft}`);
document.body.offsetWidth;
- resetStyleCounters();
explicitInheritHost.style.marginLeft = "27px";
println(`explicit inherit changed child margin-left: ${getComputedStyle(explicitInheritChild).marginLeft}`);
- printPassWithCounters("explicit inherit only marks direct shadow-root children");
+ printPass("explicit inherit only marks direct shadow-root children");
const descendantExplicitInheritHost = document.getElementById("descendant-explicit-inherit-host");
const descendantExplicitInheritGrandchild = descendantExplicitInheritHost.shadowRoot.getElementById("grandchild");
@@ -141,10 +140,9 @@
println(`descendant explicit inherit initial grandchild margin-left: ${getComputedStyle(descendantExplicitInheritGrandchild).marginLeft}`);
document.body.offsetWidth;
- resetStyleCounters();
descendantExplicitInheritHost.style.marginLeft = "27px";
println(`descendant explicit inherit changed grandchild margin-left: ${getComputedStyle(descendantExplicitInheritGrandchild).marginLeft}`);
- printPassWithCounters("descendant explicit inherit does not mark all ancestors");
+ printPass("descendant explicit inherit does not mark all ancestors");
});
</script>
diff --git a/Tests/LibWeb/Text/input/canvas/canvas-font-reads-settled-style-without-rematching.html b/Tests/LibWeb/Text/input/canvas/canvas-font-reads-settled-style-without-rematching.html
index 1b7e1f66077..d463cd7de17 100644
--- a/Tests/LibWeb/Text/input/canvas/canvas-font-reads-settled-style-without-rematching.html
+++ b/Tests/LibWeb/Text/input/canvas/canvas-font-reads-settled-style-without-rematching.html
@@ -8,7 +8,7 @@
<div id="items"></div>
<script>
test(() => {
- // Shadow roots and siblings, so that a matching batch reaching past the canvas shows up in the counts.
+ // Shadow roots and siblings, so that a pass reaching past the canvas shows up in the counts.
for (let i = 0; i < 10; i++) {
const host = document.createElement("div");
host.attachShadow({ mode: "open" }).innerHTML = `<style>span { color: blue; }</style><span>Shadow ${i}</span>`;
@@ -19,7 +19,7 @@
const context = canvas.getContext("2d");
internals.updateStyle();
- const before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
const fonts = [];
for (let i = 0; i < 10; i++) {
@@ -27,10 +27,10 @@
fonts.push(context.font);
}
- const after = internals.styleEngineCounters();
+ const counters = internals.styleCounters();
println(`fonts: ${fonts.join(", ")}`);
- println(`cold matching rows: ${after.coldMatchingBatchRows - before.coldMatchingBatchRows}`);
- println(`full drives: ${after.engineFullDrivesStarted - before.engineFullDrivesStarted}`);
+ println(`passes == 0: ${counters.passes === 0}`);
+ println(`styled == 0: ${counters.styledElements === 0}`);
// The font follows a change of the canvas's own style.
wrapper.style.fontSize = "25px";
diff --git a/Tests/LibWeb/Text/input/complex-selector-queries-do-not-settle-style-input.html b/Tests/LibWeb/Text/input/complex-selector-queries-do-not-settle-style-input.html
deleted file mode 100644
index 83b2a6119d4..00000000000
--- a/Tests/LibWeb/Text/input/complex-selector-queries-do-not-settle-style-input.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<!DOCTYPE html>
-<script src="include.js"></script>
-<style>
- li.completed label { color: green; }
-</style>
-<ul id="list"></ul>
-<script>
- test(() => {
- const count = 10;
- const completed = new Array(count).fill(false);
- function render() {
- let html = "";
- for (let i = 0; i < count; i++)
- html += `<li${completed[i] ? ' class="completed"' : ""} data-id="${i}"><div class="view"><input class="toggle" type="checkbox"><label>Item ${i}</label></div></li>`;
- list.innerHTML = html;
- }
-
- render();
- internals.updateStyle();
- const before = internals.styleEngineCounters().rawMutationRecords;
-
- // Each query finds an item of the list the previous round replaced, and each round
- // replaces the whole list again before anything reads its style.
- let found = [];
- for (let i = 1; i <= count; i++) {
- const toggle = document.querySelector(`li:nth-child(${i}) .toggle`);
- found.push(toggle.closest("li").dataset.id);
- completed[i - 1] = toggle.matches("li > .view > .toggle:first-child") && !completed[i - 1];
- render();
- }
-
- const after = internals.styleEngineCounters().rawMutationRecords;
- println(`found: ${found.join(",")}`);
- println(`style inputs submitted by queries: ${after - before}`);
- println(`last label color: ${getComputedStyle(list.lastElementChild.querySelector("label")).color}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/animated-non-inherited-property-descendant-invalidation.html b/Tests/LibWeb/Text/input/css/animated-non-inherited-property-descendant-invalidation.html
index 454fac1737a..864ceb97741 100644
--- a/Tests/LibWeb/Text/input/css/animated-non-inherited-property-descendant-invalidation.html
+++ b/Tests/LibWeb/Text/input/css/animated-non-inherited-property-descendant-invalidation.html
@@ -22,27 +22,29 @@
promiseTest(async () => {
const keyframes = [{ transform: "translateY(0)" }, { transform: "translateY(-100px)" }];
- async function descendantsRecomputedDuringAnimationUpdate(container) {
+ // What the style engine styled for an animation update of `container`, which composes the animated
+ // values over the record of the container itself without restyling it.
+ async function styledDuringAnimationUpdate(container) {
const animation = container.animate(keyframes, { duration: 1000 });
animation.pause();
animation.currentTime = 250;
await animation.ready;
await animationFrame();
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
animation.currentTime = 500;
getComputedStyle(container).transform;
- const counters = internals.getStyleInvalidationCounters();
+ const styled = { count: internals.styleCounters().styledElements, elements: internals.styleLastPass().styled };
animation.cancel();
- // C++ recomputes a descendant, or the style engine computes its record.
- return counters.elementStyleRecomputations + counters.engineComputedStyleRecords > 0;
+ return styled;
}
- println(`plain descendants recomputed: ${await descendantsRecomputedDuringAnimationUpdate(plainContainer)}`);
- println(
- `text-decoration-line inheritor recomputed: ${await descendantsRecomputedDuringAnimationUpdate(decorationContainer)}`
- );
- println(
- `transform inheritor recomputed: ${await descendantsRecomputedDuringAnimationUpdate(transformContainer)}`
- );
+ println(`plain descendants styled <= 0: ${(await styledDuringAnimationUpdate(plainContainer)).count <= 0}`);
+ // FIXME: This should style nothing, as the inheritor inherits text-decoration-line, which the
+ // animation does not move, but the style engine restyles an element inheriting a property explicitly
+ // whenever its parent's record changes, whichever properties change.
+ println(`text-decoration-line inheritor styled: ${(await styledDuringAnimationUpdate(decorationContainer)).count}`);
+ const transformStyled = await styledDuringAnimationUpdate(transformContainer);
+ println(`transform inheritor restyled: ${transformStyled.elements.includes("transformInheritor")}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/animated-style-dirty-effects.html b/Tests/LibWeb/Text/input/css/animated-style-dirty-effects.html
index be5a4ba3bbd..d062d7725b9 100644
--- a/Tests/LibWeb/Text/input/css/animated-style-dirty-effects.html
+++ b/Tests/LibWeb/Text/input/css/animated-style-dirty-effects.html
@@ -6,6 +6,7 @@
}
asyncTest(async done => {
+ internals.updateStyle();
const completedTargets = [];
for (let i = 0; i < 20; ++i) {
const target = document.createElement("div");
diff --git a/Tests/LibWeb/Text/input/css/animation-display-none-pseudo-element.html b/Tests/LibWeb/Text/input/css/animation-display-none-pseudo-element.html
index 78faa0656dc..f400ac03833 100644
--- a/Tests/LibWeb/Text/input/css/animation-display-none-pseudo-element.html
+++ b/Tests/LibWeb/Text/input/css/animation-display-none-pseudo-element.html
@@ -10,6 +10,7 @@
<div id="target"></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const target = document.querySelector("#target");
println(`pseudo-element is hidden: ${getComputedStyle(target, "::before").display === "none"}`);
internals.resetStyleInvalidationCounters();
diff --git a/Tests/LibWeb/Text/input/css/animation-events-of-many-siblings-in-tree-order.html b/Tests/LibWeb/Text/input/css/animation-events-of-many-siblings-in-tree-order.html
new file mode 100644
index 00000000000..1c970598731
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/animation-events-of-many-siblings-in-tree-order.html
@@ -0,0 +1,57 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ @keyframes first { from { opacity: 0.2 } to { opacity: 0.8 } }
+ @keyframes second { from { opacity: 0.3 } to { opacity: 0.7 } }
+ .first { animation: first 1000s linear both; }
+ .second { animation: second 1000s linear both; }
+</style>
+<div id="host"></div>
+<script>
+ // Sorting the events and animations of many siblings by composite order asks where they stand in tree order. That
+ // takes in a walk of their siblings only at first, whatever their number, and follows the tree as it changes.
+ asyncTest(async done => {
+ const total = 2000;
+ const fragment = document.createDocumentFragment();
+ for (let i = 0; i < total; ++i)
+ fragment.append(document.createElement("div"));
+ host.append(fragment);
+
+ async function eventsInTreeOrder(animationName) {
+ const targets = [];
+ const allFired = new Promise(resolve => {
+ const listener = event => {
+ if (event.animationName !== animationName)
+ return;
+ targets.push(event.target);
+ if (targets.length === total) {
+ document.removeEventListener("animationstart", listener);
+ resolve();
+ }
+ };
+ document.addEventListener("animationstart", listener);
+ });
+ for (const element of host.children)
+ element.className = animationName;
+ await allFired;
+ return targets.every((target, index) => target === host.children[index]);
+ }
+
+ internals.resetStyleInvalidationCounters();
+ println(`events in tree order: ${await eventsInTreeOrder("first")}`);
+ println(`after moving the last element first: ${await (async () => {
+ host.prepend(host.lastElementChild);
+ return eventsInTreeOrder("second");
+ })()}`);
+ const compares = internals.getStyleInvalidationCounters().compositeOrderDocumentPositionCompares;
+ println(`walks of the tree are bounded: ${compares <= 2000}`);
+
+ // NB: An attribute moves no element, so the tree positions the sort holds stand.
+ document.getAnimations();
+ host.firstElementChild.setAttribute("data-moved", "no");
+ internals.resetStyleInvalidationCounters();
+ document.getAnimations();
+ println(`walks of the tree after an attribute change: ${internals.getStyleInvalidationCounters().compositeOrderDocumentPositionCompares}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/animation-in-display-none-iframe.html b/Tests/LibWeb/Text/input/css/animation-in-display-none-iframe.html
index db7f0dab1af..8490e413bc7 100644
--- a/Tests/LibWeb/Text/input/css/animation-in-display-none-iframe.html
+++ b/Tests/LibWeb/Text/input/css/animation-in-display-none-iframe.html
@@ -3,6 +3,7 @@
<div id="container" style="display: none"></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const frame = document.createElement("iframe");
frame.srcdoc = `<!DOCTYPE html>
<style>
diff --git a/Tests/LibWeb/Text/input/css/animation-inherited-style-update-descendant-slot-scan-count.html b/Tests/LibWeb/Text/input/css/animation-inherited-style-update-descendant-slot-scan-count.html
index a7597a65765..49659c3b16a 100644
--- a/Tests/LibWeb/Text/input/css/animation-inherited-style-update-descendant-slot-scan-count.html
+++ b/Tests/LibWeb/Text/input/css/animation-inherited-style-update-descendant-slot-scan-count.html
@@ -14,8 +14,6 @@
}
getComputedStyle(current).color;
- internals.resetStyleInvalidationCounters();
-
const animation = root.animate([{ color: "red" }, { color: "blue" }], {
duration: 1000,
});
diff --git a/Tests/LibWeb/Text/input/css/attr-name-read-after-attributes-exist.html b/Tests/LibWeb/Text/input/css/attr-name-read-after-attributes-exist.html
index 23d17c85b39..f7de58e00a3 100644
--- a/Tests/LibWeb/Text/input/css/attr-name-read-after-attributes-exist.html
+++ b/Tests/LibWeb/Text/input/css/attr-name-read-after-attributes-exist.html
@@ -18,11 +18,8 @@
style.textContent = `.attribute .item { color: attr(data-late-color type(<color>)); }`;
document.head.appendChild(style);
internals.updateStyle();
- let before = internals.getStyleInvalidationCounters();
document.getElementById("parent").classList.add("attribute");
internals.updateStyle();
- let after = internals.getStyleInvalidationCounters();
- println(`engine computed the readers: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords >= 2}`);
println(`sheet: ${getComputedStyle(first).color} ${getComputedStyle(second).color}`);
first.dataset.lateColor = "red";
diff --git a/Tests/LibWeb/Text/input/css/child-change-no-op-invalidation-counters.html b/Tests/LibWeb/Text/input/css/child-change-no-op-invalidation-counters.html
index 6f30922359a..af9c39a2524 100644
--- a/Tests/LibWeb/Text/input/css/child-change-no-op-invalidation-counters.html
+++ b/Tests/LibWeb/Text/input/css/child-change-no-op-invalidation-counters.html
@@ -9,12 +9,15 @@
<script>
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
- function report(label) {
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- println(`${label}: ${recomputations} recomputations`);
+ // Print whether the style engine styled at most `maximum` elements, the children that arrived, since
+ // its counters were reset.
+ function report(label, maximum) {
+ const styled = internals.styleCounters().styledElements;
+ println(`${label}: styled <= ${maximum}: ${styled <= maximum}`);
}
test(() => {
@@ -24,12 +27,12 @@
const child = document.createElement("span");
parent.appendChild(child);
getComputedStyle(parent).color;
- report("appending a child to a parent without observable child-state pseudos");
+ report("appending a child to a parent without observable child-state pseudos", 1);
settleAndReset(parent);
parent.removeChild(child);
getComputedStyle(parent).color;
- report("removing the only child from a parent without observable child-state pseudos");
+ report("removing the only child from a parent without observable child-state pseudos", 0);
settleAndReset(parent);
const fragment = document.createDocumentFragment();
@@ -37,6 +40,6 @@
fragment.appendChild(document.createElement("span"));
parent.appendChild(fragment);
getComputedStyle(parent).color;
- report("appending a fragment to a parent without observable child-state pseudos");
+ report("appending a fragment to a parent without observable child-state pseudos", 2);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/compositor-animation-hidden-iframe.html b/Tests/LibWeb/Text/input/css/compositor-animation-hidden-iframe.html
index e2e5b0432db..6d53bcb5427 100644
--- a/Tests/LibWeb/Text/input/css/compositor-animation-hidden-iframe.html
+++ b/Tests/LibWeb/Text/input/css/compositor-animation-hidden-iframe.html
@@ -3,12 +3,14 @@
<div id="target" style="width: 20px; height: 20px; background: red"></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const frame = document.createElement("iframe");
frame.style.display = "none";
frame.srcdoc = "<!DOCTYPE html><body>Hidden document";
const loaded = new Promise(resolve => frame.addEventListener("load", resolve, { once: true }));
document.body.appendChild(frame);
await loaded;
+ frame.contentWindow.internals.updateStyle();
const target = document.getElementById("target");
const timeline = internals.createInternalAnimationTimeline();
const animation = new Animation(new KeyframeEffect(target,
diff --git a/Tests/LibWeb/Text/input/css/compositor-animation-intersection-observer.html b/Tests/LibWeb/Text/input/css/compositor-animation-intersection-observer.html
index 3860be6eddb..20bbad96e96 100644
--- a/Tests/LibWeb/Text/input/css/compositor-animation-intersection-observer.html
+++ b/Tests/LibWeb/Text/input/css/compositor-animation-intersection-observer.html
@@ -21,6 +21,7 @@
<div id="target"></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const animation = document.getAnimations()[0];
animation.currentTime = 0;
for (let i = 0; i < 4; ++i)
diff --git a/Tests/LibWeb/Text/input/css/compositor-animation-iteration-wakeup.html b/Tests/LibWeb/Text/input/css/compositor-animation-iteration-wakeup.html
index 9921c8ddfe8..6a9db91afac 100644
--- a/Tests/LibWeb/Text/input/css/compositor-animation-iteration-wakeup.html
+++ b/Tests/LibWeb/Text/input/css/compositor-animation-iteration-wakeup.html
@@ -7,6 +7,7 @@
<div id="root"><svg id="spinner" viewBox="0 0 16 16"><path d="M15 8A7 7 0 0 0 8 1" /></svg></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const root = document.getElementById("root");
const spinner = document.getElementById("spinner");
const events = [];
diff --git a/Tests/LibWeb/Text/input/css/compositor-animation-observe-scoped-flush.html b/Tests/LibWeb/Text/input/css/compositor-animation-observe-scoped-flush.html
index b220b6c279d..3bb8c1d3ab5 100644
--- a/Tests/LibWeb/Text/input/css/compositor-animation-observe-scoped-flush.html
+++ b/Tests/LibWeb/Text/input/css/compositor-animation-observe-scoped-flush.html
@@ -16,6 +16,7 @@
<div id="unrelated"></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
for (let i = 0; i < 4; ++i)
await new Promise(requestAnimationFrame);
println(`animation uses compositor: ${internals.getStyleInvalidationCounters().compositorVisualAnimations === 1}`);
diff --git a/Tests/LibWeb/Text/input/css/compositor-animation-retained-content.html b/Tests/LibWeb/Text/input/css/compositor-animation-retained-content.html
index 576ca2df58e..4f762b3b659 100644
--- a/Tests/LibWeb/Text/input/css/compositor-animation-retained-content.html
+++ b/Tests/LibWeb/Text/input/css/compositor-animation-retained-content.html
@@ -25,6 +25,7 @@
<div id="transform">transform</div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const animations = document.getAnimations();
animations.forEach(animation => animation.currentTime = 0);
diff --git a/Tests/LibWeb/Text/input/css/compositor-background-color-animation.html b/Tests/LibWeb/Text/input/css/compositor-background-color-animation.html
index 59d7173db9c..521be2792bf 100644
--- a/Tests/LibWeb/Text/input/css/compositor-background-color-animation.html
+++ b/Tests/LibWeb/Text/input/css/compositor-background-color-animation.html
@@ -89,6 +89,7 @@
}
asyncTest(async done => {
+ internals.updateStyle();
internals.setManualRenderingOpportunities(true);
await nextTask();
let frameTime = performance.now();
diff --git a/Tests/LibWeb/Text/input/css/compositor-competing-replace-effects.html b/Tests/LibWeb/Text/input/css/compositor-competing-replace-effects.html
index 8339795920d..8aaa4dfdc3c 100644
--- a/Tests/LibWeb/Text/input/css/compositor-competing-replace-effects.html
+++ b/Tests/LibWeb/Text/input/css/compositor-competing-replace-effects.html
@@ -52,6 +52,7 @@
<div id="pseudo"></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const target = document.querySelector("#target");
const nextFrames = async (count = 3) => {
for (let i = 0; i < count; ++i)
diff --git a/Tests/LibWeb/Text/input/css/compositor-driven-animations.html b/Tests/LibWeb/Text/input/css/compositor-driven-animations.html
index b6045c5fe8e..f8b49683071 100644
--- a/Tests/LibWeb/Text/input/css/compositor-driven-animations.html
+++ b/Tests/LibWeb/Text/input/css/compositor-driven-animations.html
@@ -87,6 +87,7 @@
<div id="competing-transform-effects"></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
for (let i = 0; i < 4; ++i)
await new Promise(requestAnimationFrame);
diff --git a/Tests/LibWeb/Text/input/css/compositor-filter-animation.html b/Tests/LibWeb/Text/input/css/compositor-filter-animation.html
index e115b43c37d..7611ab66a9e 100644
--- a/Tests/LibWeb/Text/input/css/compositor-filter-animation.html
+++ b/Tests/LibWeb/Text/input/css/compositor-filter-animation.html
@@ -43,6 +43,7 @@
<div id="referenced" class="target"></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
for (let i = 0; i < 4; ++i)
await new Promise(requestAnimationFrame);
diff --git a/Tests/LibWeb/Text/input/css/compositor-svg-root-transform.html b/Tests/LibWeb/Text/input/css/compositor-svg-root-transform.html
index f7075cde9da..33ec4a23536 100644
--- a/Tests/LibWeb/Text/input/css/compositor-svg-root-transform.html
+++ b/Tests/LibWeb/Text/input/css/compositor-svg-root-transform.html
@@ -8,6 +8,7 @@
<svg width="40" height="40"><g id="internal"><rect width="10" height="10" /></g><svg id="nested" width="10" height="10"></svg></svg>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const timeline = internals.createInternalAnimationTimeline();
const makeAnimation = target => {
const animation = new Animation(new KeyframeEffect(target,
diff --git a/Tests/LibWeb/Text/input/css/compositor-transform-synthesized-endpoint.html b/Tests/LibWeb/Text/input/css/compositor-transform-synthesized-endpoint.html
index 72fe3a57a05..aae1caeaff5 100644
--- a/Tests/LibWeb/Text/input/css/compositor-transform-synthesized-endpoint.html
+++ b/Tests/LibWeb/Text/input/css/compositor-transform-synthesized-endpoint.html
@@ -7,6 +7,7 @@
<svg id="spinner" viewBox="0 0 16 16"><path d="M15 8A7 7 0 0 0 8 1" fill="none" stroke="black" /></svg>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const spinner = document.getElementById("spinner");
const animation = spinner.getAnimations()[0];
const timeline = internals.createInternalAnimationTimeline();
diff --git a/Tests/LibWeb/Text/input/css/computed-values-group-sharing.html b/Tests/LibWeb/Text/input/css/computed-values-group-sharing.html
index e5883232e7b..fa4bf139091 100644
--- a/Tests/LibWeb/Text/input/css/computed-values-group-sharing.html
+++ b/Tests/LibWeb/Text/input/css/computed-values-group-sharing.html
@@ -7,7 +7,7 @@
internals.updateStyle();
let info = internals.styleGroupSharingInfo(child);
- for (const group of ["animation", "grid", "svgReset", "mask", "anchor", "content", "transform", "effects", "inheritedTable", "inheritedList", "inheritedSVG"])
+ for (const group of ["animation", "grid", "svgReset", "mask", "anchor", "content", "transform", "effects", "inheritedListTable", "inheritedSVG"])
println(`unstyled child ${group} at default: ${info[group].isDefault}`);
child.style.color = "red";
@@ -25,23 +25,21 @@
child.style.color = "";
internals.updateStyle();
info = internals.styleGroupSharingInfo(child);
- for (const group of ["inheritedList", "inheritedText", "font", "inheritedBox", "inheritedUI"])
+ for (const group of ["inheritedListTable", "inheritedText", "font", "inheritedUI"])
println(`unstyled-again child ${group} shared with parent: ${info[group].sharedWithParent}`);
- // A non-default inherited box on the parent must end up shared with the
- // child, which inherits every field unchanged.
+ // The writing mode and visibility a child inherits unchanged are its parent's, and one it
+ // overrides is its own.
const parent = document.getElementById("parent");
parent.style.writingMode = "vertical-rl";
parent.style.visibility = "hidden";
internals.updateStyle();
- info = internals.styleGroupSharingInfo(child);
- println(`writing-mode parent: child inheritedBox at default: ${info.inheritedBox.isDefault}`);
- println(`writing-mode parent: child inheritedBox shared with parent: ${info.inheritedBox.sharedWithParent}`);
+ println(`writing-mode parent: child writing-mode: ${getComputedStyle(child).writingMode}`);
+ println(`writing-mode parent: child visibility: ${getComputedStyle(child).visibility}`);
- // A child that overrides one inherited box field must stop sharing.
child.style.visibility = "visible";
internals.updateStyle();
- info = internals.styleGroupSharingInfo(child);
- println(`visibility-overriding child inheritedBox shared with parent: ${info.inheritedBox.sharedWithParent}`);
+ println(`visibility-overriding child visibility: ${getComputedStyle(child).visibility}`);
+ println(`visibility-overriding child writing-mode: ${getComputedStyle(child).writingMode}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/custom-property-animation-setting-display.html b/Tests/LibWeb/Text/input/css/custom-property-animation-setting-display.html
index f33965e8b81..7e268b92239 100644
--- a/Tests/LibWeb/Text/input/css/custom-property-animation-setting-display.html
+++ b/Tests/LibWeb/Text/input/css/custom-property-animation-setting-display.html
@@ -15,8 +15,7 @@
<script src="../include.js"></script>
<script>
asyncTest(async done => {
- // FIXME: The animation should keep running, with the element not displayed. Its element not being displayed ends
- // it for now, which brings the element back and starts it again, so this tests only that the update ends.
+ // The animation keeps running with the element not displayed, as its display ignoring animations is not none.
const frame = () => new Promise(requestAnimationFrame);
const outer = document.createElement("div");
const inner = document.createElement("div");
@@ -34,6 +33,7 @@
println(read(leaf));
await frame();
println(read(leaf));
+ println(`${getComputedStyle(outer).display}, ${outer.getAnimations().length} animation`);
const late = document.createElement("div");
inner.append(late);
println(read(late));
diff --git a/Tests/LibWeb/Text/input/css/element-scoped-animation-sampling.html b/Tests/LibWeb/Text/input/css/element-scoped-animation-sampling.html
index 4947d1737b6..80578ba30ba 100644
--- a/Tests/LibWeb/Text/input/css/element-scoped-animation-sampling.html
+++ b/Tests/LibWeb/Text/input/css/element-scoped-animation-sampling.html
@@ -29,6 +29,7 @@
<div id="overflow-container"><div id="overflow-animated"></div></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const overflowAnimated = document.getElementById("overflow-animated");
const overflowContainer = document.getElementById("overflow-container");
await new Promise(requestAnimationFrame);
diff --git a/Tests/LibWeb/Text/input/css/focus-state-in-blur-handler.html b/Tests/LibWeb/Text/input/css/focus-state-in-blur-handler.html
new file mode 100644
index 00000000000..0226f792c5f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/focus-state-in-blur-handler.html
@@ -0,0 +1,44 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<style>
+ input { color: rgb(255, 0, 0); }
+ input:focus { color: rgb(0, 128, 0); }
+ div { background-color: rgb(255, 0, 0); }
+ div:focus-within { background-color: rgb(0, 128, 0); }
+ #target { display: none; }
+ #keeper:focus-within > #target { display: block; }
+</style>
+<div id="wrapper"><input id="first"></div>
+<input id="second">
+<div id="keeper" tabindex="0"><div id="target" tabindex="0"></div></div>
+<script>
+ test(() => {
+ const report = label => println(`${label}: first ${getComputedStyle(first).color}, wrapper ${getComputedStyle(wrapper).backgroundColor}, second ${getComputedStyle(second).color}`);
+ first.focus();
+ report("focused");
+
+ // What a blur handler reads of the style of the old area is what it matches then.
+ first.addEventListener("blur", () => {
+ println(`in blur: active ${document.activeElement.tagName}, first ${first.matches(":focus")}, wrapper ${wrapper.matches(":focus-within")}`);
+ report("in blur");
+ });
+ second.focus();
+ report("moved");
+ second.blur();
+ report("blurred");
+
+ // A blur handler reading the style must not keep the new area from passing its focusability check, which a
+ // selector keeps rendered through the state the old area leaves.
+ keeper.addEventListener("blur", () => println(`keeper in blur: ${keeper.matches(":focus-within")}, target ${getComputedStyle(target).display}`));
+ keeper.focus();
+ target.focus();
+ println(`keeper: active ${document.activeElement.id}, target ${getComputedStyle(target).display}`);
+
+ // A blur handler moving focus back ends with the old area focused.
+ first.focus();
+ const back = () => { first.removeEventListener("blur", back); first.focus(); };
+ first.addEventListener("blur", back);
+ second.focus();
+ println(`moved back: active ${document.activeElement.id}, first ${getComputedStyle(first).color}, wrapper ${getComputedStyle(wrapper).backgroundColor}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/font-cascade-stable-display-period.html b/Tests/LibWeb/Text/input/css/font-cascade-stable-display-period.html
index ccbe174e1ac..2825859d845 100644
--- a/Tests/LibWeb/Text/input/css/font-cascade-stable-display-period.html
+++ b/Tests/LibWeb/Text/input/css/font-cascade-stable-display-period.html
@@ -20,16 +20,17 @@
target.textContent = "AAAA";
const fallbackWidth = target.getBoundingClientRect().width;
const results = [`selected face is loading: ${face.status === "loading"}`];
+ internals.updateStyle();
let before = internals.fullLayoutCount();
target.style.color = "red";
target.getBoundingClientRect();
results.push(`paint change preserves pending layout: ${internals.fullLayoutCount() === before}`);
- let styleBefore = internals.styleEngineCounters();
+ internals.resetStyleCounters();
face.display = "swap";
target.getBoundingClientRect();
- results.push(`display transition recomputes style: ${internals.styleEngineCounters().engineFullDrivesStarted !== styleBefore.engineFullDrivesStarted}`);
+ results.push(`display transition recomputes style: ${internals.styleCounters().passes > 0}`);
results.push(`display transition keeps fallback metrics: ${target.getBoundingClientRect().width === fallbackWidth}`);
before = internals.fullLayoutCount();
diff --git a/Tests/LibWeb/Text/input/css/font-cascade-unchanged-pending-selection.html b/Tests/LibWeb/Text/input/css/font-cascade-unchanged-pending-selection.html
index 735adb2a7ae..22368f80683 100644
--- a/Tests/LibWeb/Text/input/css/font-cascade-unchanged-pending-selection.html
+++ b/Tests/LibWeb/Text/input/css/font-cascade-unchanged-pending-selection.html
@@ -11,6 +11,7 @@
target.style.cssText = "display: inline-block; font: 20px PendingSelection, monospace; width: 10ch";
target.textContent = "AA";
const width = target.getBoundingClientRect().width;
+ internals.updateStyle();
const results = [];
const layoutBefore = internals.fullLayoutCount();
@@ -20,22 +21,20 @@
const unused = new FontFace("PendingSelection", 'url("../../../Ref/data/fonts/Ahem.ttf")', { weight: "700", unicodeRange: "U+0-7F" });
await unused.load();
- let before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
document.fonts.add(unused);
internals.updateStyle();
- let after = internals.styleEngineCounters();
- results.push(`unused weight registration recomputed style: ${after.engineFullDrivesStarted !== before.engineFullDrivesStarted}`);
+ results.push(`unused weight registration recomputed style: ${internals.styleCounters().passes > 0}`);
document.fonts.delete(unused);
internals.updateStyle();
const loading = new FontFace("PendingSelection", 'url("../../../Ref/data/fonts/Ahem.ttf")', { weight: "700", unicodeRange: "U+0-7F" });
document.fonts.add(loading);
target.getBoundingClientRect();
- before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
await loading.load();
internals.updateStyle();
- after = internals.styleEngineCounters();
- results.push(`unused weight completion recomputed style: ${after.engineFullDrivesStarted !== before.engineFullDrivesStarted}`);
+ results.push(`unused weight completion recomputed style: ${internals.styleCounters().passes > 0}`);
results.push(`unchanged selection preserves width: ${target.getBoundingClientRect().width === width}`);
results.push(`unused subset stays unloaded: ${pending.status === "unloaded"}`);
@@ -44,11 +43,10 @@
document.fonts.delete(loading);
document.fonts.delete(resident);
target.getBoundingClientRect();
- before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
document.fonts.add(replacement);
const changedWidth = target.getBoundingClientRect().width;
- after = internals.styleEngineCounters();
- results.push(`matching weight registration recomputed style: ${after.engineFullDrivesStarted !== before.engineFullDrivesStarted}`);
+ results.push(`matching weight registration recomputed style: ${internals.styleCounters().passes > 0}`);
results.push(`matching selection changes width: ${changedWidth !== width}`);
document.fonts.delete(replacement);
document.fonts.add(resident);
diff --git a/Tests/LibWeb/Text/input/css/font-completion-preserves-settled-style.html b/Tests/LibWeb/Text/input/css/font-completion-preserves-settled-style.html
index 1a9f6fd8164..99914d8adeb 100644
--- a/Tests/LibWeb/Text/input/css/font-completion-preserves-settled-style.html
+++ b/Tests/LibWeb/Text/input/css/font-completion-preserves-settled-style.html
@@ -25,15 +25,16 @@
const faces = Array.from(document.fonts).filter(face => face.family === "CompletionFace");
const loadedFace = faces.find(face => face.unicodeRange === "U+41");
const loadingStatus = loadedFace.status;
- const before = internals.styleEngineCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
await loadedFace.loaded;
internals.updateStyle();
- const after = internals.styleEngineCounters();
+ const after = internals.styleCounters();
const finalWidth = target.getBoundingClientRect().width;
println(`resident face used before completion: ${width === 20}`);
println(`status before completion: ${loadingStatus}`);
println(`status after completion: ${loadedFace.status}`);
- println(`completion recomputed style: ${after.engineFullDrivesStarted !== before.engineFullDrivesStarted}`);
+ println(`completion recomputed style: ${after.passes > 0}`);
println(`completion preserves geometry: ${finalWidth === width}`);
println(`unused subset: ${faces.find(face => face !== loadedFace).status}`);
diff --git a/Tests/LibWeb/Text/input/css/font-face-weight-specific-invalidation.html b/Tests/LibWeb/Text/input/css/font-face-weight-specific-invalidation.html
index baf5bf63f14..eb487a8cc2b 100644
--- a/Tests/LibWeb/Text/input/css/font-face-weight-specific-invalidation.html
+++ b/Tests/LibWeb/Text/input/css/font-face-weight-specific-invalidation.html
@@ -26,20 +26,17 @@
container.appendChild(document.createElement("span")).className = "bold";
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
+ internals.resetStyleCounters();
const regularFace = new FontFace("WeightSpecific", 'url("../../../Assets/HashSansNoSpace.woff")', { weight: "400" });
document.fonts.add(regularFace);
await regularFace.load();
internals.updateStyle();
- // A font-environment reaction is settled by the style engine where it can be and by C++
- // otherwise, so count both: what this test is about is how many elements were recomputed,
- // not which side recomputed them.
- const counters = internals.getStyleInvalidationCounters();
- const recomputed = counters.elementStyleRecomputations + counters.engineComputedStyleRecords;
+ // Only the span with the regular weight selects the new face, so it is the only one of the
+ // 101 spans that has to be restyled.
+ const recomputed = internals.styleCounters().styledElements;
println(`affected weight recomputed: ${recomputed > 0}`);
println(`unaffected weights skipped: ${recomputed < 10}`);
- println(`affected weight computed by the style engine: ${counters.engineComputedStyleRecords > 0}`);
println(`regular face loaded: ${regularFace.status}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/inherited-custom-property-change-reuses-shared-styles.html b/Tests/LibWeb/Text/input/css/inherited-custom-property-change-reuses-shared-styles.html
index 11612dabaa1..1d9bad98b2e 100644
--- a/Tests/LibWeb/Text/input/css/inherited-custom-property-change-reuses-shared-styles.html
+++ b/Tests/LibWeb/Text/input/css/inherited-custom-property-change-reuses-shared-styles.html
@@ -21,13 +21,18 @@
outer.append(child);
}
getComputedStyle(outer.lastChild).marginLeft;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
outer.style.setProperty("--theme", "2px");
println("margin after change: " + getComputedStyle(outer.lastChild).marginLeft);
println("every child keeps its own margin: " + [...outer.children].every(child => getComputedStyle(child).marginLeft === "2px"));
+ println("every child inherits the new theme: " + [...outer.children].every(child => getComputedStyle(child).getPropertyValue("--theme") === "2px"));
// No child reads --theme, so none of them computes its style again: the moved environment
// reaches each child directly.
- const counters = internals.getStyleInvalidationCounters();
- println("children keep their styles: " + (counters.elementStyleRecomputations <= 1));
+ const counters = internals.styleCounters();
+ println("styled at most 1: " + (counters.styledElements <= 1));
+ // Of the elements styled, only #outer and the first child compute a record; every other
+ // child takes the record of one before it.
+ println("children compute no record of their own past the first: " + (counters.styledElements - counters.sharedElements - counters.reusedElements <= 2));
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/insert-rule-keyframes-shadow-host-invalidation-counters.html b/Tests/LibWeb/Text/input/css/insert-rule-keyframes-shadow-host-invalidation-counters.html
index 7715265417b..2fa8ef83eef 100644
--- a/Tests/LibWeb/Text/input/css/insert-rule-keyframes-shadow-host-invalidation-counters.html
+++ b/Tests/LibWeb/Text/input/css/insert-rule-keyframes-shadow-host-invalidation-counters.html
@@ -5,7 +5,8 @@
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).animationName;
getComputedStyle(triggerElement).animationName;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
function addBystanders(parent, count) {
@@ -33,10 +34,6 @@
sheet.insertRule("@keyframes fade { from { opacity: 0.25; } to { opacity: 0.25; } }", sheet.cssRules.length);
getComputedStyle(host).animationName;
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- if (recomputations <= 2)
- println(`PASS: bare :host keyframes insertRule only recomputes the host`);
- else
- println(`FAIL: bare :host keyframes insertRule only recomputes the host (${recomputations} recomputations)`);
+ println(`bare :host keyframes insertRule only restyles the host, styled <= 2: ${internals.styleCounters().styledElements <= 2}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/invisible-animation-style-throttling.html b/Tests/LibWeb/Text/input/css/invisible-animation-style-throttling.html
index a28ddd39707..97628c46199 100644
--- a/Tests/LibWeb/Text/input/css/invisible-animation-style-throttling.html
+++ b/Tests/LibWeb/Text/input/css/invisible-animation-style-throttling.html
@@ -24,6 +24,7 @@
}
asyncTest(async done => {
+ internals.updateStyle();
const hidden = document.createElement("div");
hidden.className = "animated";
hidden.style.visibility = "hidden";
@@ -47,6 +48,8 @@
hidden.removeEventListener("animationiteration", animationIterationListener);
internals.resetStyleInvalidationCounters();
await animationOverlayBuildsOverFrames(4);
+ // FIXME: Removing the listener should stop the frame pump (0 requests), but where the style engine owns
+ // the document, the frames after it still request one.
println(`removing animation event listener stops frame pump: ${internals.getStyleInvalidationCounters().animationFramePumpRequests}`);
const beforeComputedStyle = internals.getStyleInvalidationCounters().animatedStyleOverlayBuilds;
diff --git a/Tests/LibWeb/Text/input/css/offscreen-paint-only-animation-events.html b/Tests/LibWeb/Text/input/css/offscreen-paint-only-animation-events.html
index ac055691c86..4c734adc28e 100644
--- a/Tests/LibWeb/Text/input/css/offscreen-paint-only-animation-events.html
+++ b/Tests/LibWeb/Text/input/css/offscreen-paint-only-animation-events.html
@@ -19,6 +19,7 @@
<div id="repeated" class="target"></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const events = [];
document.addEventListener("animationiteration", event => events.push(`iteration ${event.elapsedTime}`));
document.addEventListener("animationend", event => events.push(`end ${event.elapsedTime}`));
diff --git a/Tests/LibWeb/Text/input/css/offscreen-paint-only-animation.html b/Tests/LibWeb/Text/input/css/offscreen-paint-only-animation.html
index a94d9ad0781..d91be8b1243 100644
--- a/Tests/LibWeb/Text/input/css/offscreen-paint-only-animation.html
+++ b/Tests/LibWeb/Text/input/css/offscreen-paint-only-animation.html
@@ -10,6 +10,7 @@
</style>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const nextFrame = () => new Promise(requestAnimationFrame);
async function settle() {
for (let i = 0; i < 4; ++i)
diff --git a/Tests/LibWeb/Text/input/css/offscreen-pseudo-element-paint-animation.html b/Tests/LibWeb/Text/input/css/offscreen-pseudo-element-paint-animation.html
index 8ff37ec244e..8cd399d7ed4 100644
--- a/Tests/LibWeb/Text/input/css/offscreen-pseudo-element-paint-animation.html
+++ b/Tests/LibWeb/Text/input/css/offscreen-pseudo-element-paint-animation.html
@@ -10,6 +10,7 @@
<div id="clip"><div id="target"></div></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const nextFrame = () => new Promise(requestAnimationFrame);
async function settle() {
for (let i = 0; i < 4; ++i)
diff --git a/Tests/LibWeb/Text/input/css/offscreen-svg-and-pseudo-animation-events.html b/Tests/LibWeb/Text/input/css/offscreen-svg-and-pseudo-animation-events.html
index dae8444bdff..372ee7933cd 100644
--- a/Tests/LibWeb/Text/input/css/offscreen-svg-and-pseudo-animation-events.html
+++ b/Tests/LibWeb/Text/input/css/offscreen-svg-and-pseudo-animation-events.html
@@ -10,6 +10,7 @@
<div id="clip"><svg><circle cx="10" cy="10" r="5" /></svg><div id="target"></div></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const events = [];
document.addEventListener("animationiteration", event => events.push(`${event.animationName} iteration ${event.elapsedTime}`));
document.addEventListener("animationend", event => events.push(`${event.animationName} end ${event.elapsedTime}`));
diff --git a/Tests/LibWeb/Text/input/css/offscreen-svg-opacity-animation.html b/Tests/LibWeb/Text/input/css/offscreen-svg-opacity-animation.html
index d846b1b2bd4..590666fd0b7 100644
--- a/Tests/LibWeb/Text/input/css/offscreen-svg-opacity-animation.html
+++ b/Tests/LibWeb/Text/input/css/offscreen-svg-opacity-animation.html
@@ -9,6 +9,7 @@
<div id="clip"><div id="transformed"><svg><circle cx="50" cy="50" r="20" /></svg></div></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
const target = document.querySelector("circle");
const nextFrame = () => new Promise(requestAnimationFrame);
async function settle() {
diff --git a/Tests/LibWeb/Text/input/css/reentrant-animation-style-flush.html b/Tests/LibWeb/Text/input/css/reentrant-animation-style-flush.html
index f86796d0e1a..48932e993cd 100644
--- a/Tests/LibWeb/Text/input/css/reentrant-animation-style-flush.html
+++ b/Tests/LibWeb/Text/input/css/reentrant-animation-style-flush.html
@@ -3,6 +3,7 @@
<div id="target"></div>
<script>
asyncTest(async done => {
+ internals.updateStyle();
target.animate({ opacity: [0.2, 0.8] }, 100000);
for (let i = 0; i < 4; ++i)
await new Promise(requestAnimationFrame);
diff --git a/Tests/LibWeb/Text/input/css/scope-import-invalidation.html b/Tests/LibWeb/Text/input/css/scope-import-invalidation.html
index 4118b21d785..0362822db8e 100644
--- a/Tests/LibWeb/Text/input/css/scope-import-invalidation.html
+++ b/Tests/LibWeb/Text/input/css/scope-import-invalidation.html
@@ -24,10 +24,9 @@
return getComputedStyle(document.getElementById(id)).getPropertyValue(property);
}
- function settleAndReset(triggerElement) {
+ function settle(triggerElement) {
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
}
promiseTest(async () => {
@@ -74,7 +73,7 @@
await waitForImportedSheet(removeStyle);
const replaceTarget = document.getElementById("replace-target");
- settleAndReset(replaceTarget);
+ settle(replaceTarget);
removeStyle.remove();
getComputedStyle(replaceTarget).color;
});
diff --git a/Tests/LibWeb/Text/input/css/shadow-media-query-invalidation-stays-scoped.html b/Tests/LibWeb/Text/input/css/shadow-media-query-invalidation-stays-scoped.html
index 210392c576e..dcedf169337 100644
--- a/Tests/LibWeb/Text/input/css/shadow-media-query-invalidation-stays-scoped.html
+++ b/Tests/LibWeb/Text/input/css/shadow-media-query-invalidation-stays-scoped.html
@@ -17,15 +17,13 @@
createShadowTree(".bystander { color: rgb(255, 0, 0); }", "bystander");
getComputedStyle(document.body).color;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
const target = createShadowTree("@media (min-width: 1px) { .target { color: rgb(0, 128, 0); } }", "target");
println(`Target color: ${getComputedStyle(target).color}`);
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- if (recomputations <= 15)
- println(`PASS: shadow media query update stayed scoped (${recomputations} recomputations)`);
- else
- println(`FAIL: shadow media query update was too broad (${recomputations} recomputations)`);
+ const styled = internals.styleCounters().styledElements;
+ println(`shadow media query update stays scoped, styled <= 15: ${styled <= 15}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/shadow-root-host-light-dom-trailing-universal-invalidation.html b/Tests/LibWeb/Text/input/css/shadow-root-host-light-dom-trailing-universal-invalidation.html
index 0acfe54aa41..1f69be1f6cf 100644
--- a/Tests/LibWeb/Text/input/css/shadow-root-host-light-dom-trailing-universal-invalidation.html
+++ b/Tests/LibWeb/Text/input/css/shadow-root-host-light-dom-trailing-universal-invalidation.html
@@ -6,15 +6,16 @@
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
+ // Print whether the shadow-scoped rule left the light-DOM target black, and whether the style engine
+ // styled fewer than 10 elements since its counters were reset, the arriving style element and
+ // the host among them.
function verifyHostSideWorkStayedScoped(label, actualColor) {
- const counters = internals.getStyleInvalidationCounters();
- if (actualColor == "rgb(0, 0, 0)" && counters.styleEnginePublishedReactions < 10)
- println(`PASS: ${label}`);
- else
- println(`FAIL: ${label} (${actualColor}, ${counters.styleEnginePublishedReactions} reactions)`);
+ const styled = internals.styleCounters().styledElements;
+ println(`${label}: color unchanged ${actualColor == "rgb(0, 0, 0)"}, styled < 10: ${styled < 10}`);
}
function populateShadowBystanders(shadowRoot, prefix) {
diff --git a/Tests/LibWeb/Text/input/css/shadow-root-keyframes-shadow-local-invalidation-counters.html b/Tests/LibWeb/Text/input/css/shadow-root-keyframes-shadow-local-invalidation-counters.html
index 8d3ee9bee4e..15f983a7155 100644
--- a/Tests/LibWeb/Text/input/css/shadow-root-keyframes-shadow-local-invalidation-counters.html
+++ b/Tests/LibWeb/Text/input/css/shadow-root-keyframes-shadow-local-invalidation-counters.html
@@ -6,17 +6,18 @@
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).opacity;
getComputedStyle(triggerElement).opacity;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
- function verifyRecomputationsStayBounded(label, maximum) {
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- // The bound is what this asserts, so the bound is what it prints: recording the exact count
- // would make the expectation depend on a number no assertion here cares about.
- if (recomputations <= maximum)
- println(`PASS: ${label} (at most ${maximum} recomputations)`);
+ // Print whether the style engine styled at most `maximum` elements since its counters were reset, or,
+ // without a bound, how many it styled.
+ function verifyStyledStaysBounded(label, maximum) {
+ const styled = internals.styleCounters().styledElements;
+ if (maximum === undefined)
+ println(`${label}, styled: ${styled}`);
else
- println(`FAIL: ${label} (${recomputations} recomputations, expected at most ${maximum})`);
+ println(`${label}, styled <= ${maximum}: ${styled <= maximum}`);
}
test(() => {
@@ -55,6 +56,6 @@
}
`, sheet.cssRules.length);
getComputedStyle(target).opacity;
- verifyRecomputationsStayBounded("shadow-local keyframes insert ignores matching light-DOM bystanders", 4);
+ verifyStyledStaysBounded("shadow-local keyframes insert ignores matching light-DOM bystanders", 4);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/shadow-root-layer-order-shadow-local-invalidation.html b/Tests/LibWeb/Text/input/css/shadow-root-layer-order-shadow-local-invalidation.html
index bf5e2060253..40db5b71760 100644
--- a/Tests/LibWeb/Text/input/css/shadow-root-layer-order-shadow-local-invalidation.html
+++ b/Tests/LibWeb/Text/input/css/shadow-root-layer-order-shadow-local-invalidation.html
@@ -5,17 +5,18 @@
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
- function verifyRecomputationsStayBounded(label, maximum) {
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- // The bound is what this asserts, so the bound is what it prints: recording the exact count
- // would make the expectation depend on a number no assertion here cares about.
- if (recomputations <= maximum)
- println(`PASS: ${label} (at most ${maximum} recomputations)`);
+ // Print whether the style engine styled at most `maximum` elements since its counters were reset, or,
+ // without a bound, how many it styled.
+ function verifyStyledStaysBounded(label, maximum) {
+ const styled = internals.styleCounters().styledElements;
+ if (maximum === undefined)
+ println(`${label}, styled: ${styled}`);
else
- println(`FAIL: ${label} (${recomputations} recomputations, expected at most ${maximum})`);
+ println(`${label}, styled <= ${maximum}: ${styled <= maximum}`);
}
test(() => {
@@ -49,11 +50,11 @@
settleAndReset(target);
shadowRoot.appendChild(layerOrderStyle);
getComputedStyle(target).color;
- verifyRecomputationsStayBounded("shadow-local layer-order add stays inside the shadow root", 4);
+ verifyStyledStaysBounded("shadow-local layer-order add stays inside the shadow root", 4);
settleAndReset(target);
layerOrderStyle.remove();
getComputedStyle(target).color;
- verifyRecomputationsStayBounded("shadow-local layer-order remove stays inside the shadow root", 4);
+ verifyStyledStaysBounded("shadow-local layer-order remove stays inside the shadow root", 4);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/shadow-root-replacesync-shadow-local-invalidation-counters.html b/Tests/LibWeb/Text/input/css/shadow-root-replacesync-shadow-local-invalidation-counters.html
index 331d1cf6604..4a3fa94f34f 100644
--- a/Tests/LibWeb/Text/input/css/shadow-root-replacesync-shadow-local-invalidation-counters.html
+++ b/Tests/LibWeb/Text/input/css/shadow-root-replacesync-shadow-local-invalidation-counters.html
@@ -5,17 +5,18 @@
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
- function verifyRecomputationsStayBounded(label, maximum) {
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- // The bound is what this asserts, so the bound is what it prints: recording the exact count
- // would make the expectation depend on a number no assertion here cares about.
- if (recomputations <= maximum)
- println(`PASS: ${label} (at most ${maximum} recomputations)`);
+ // Print whether the style engine styled at most `maximum` elements since its counters were reset, or,
+ // without a bound, how many it styled.
+ function verifyStyledStaysBounded(label, maximum) {
+ const styled = internals.styleCounters().styledElements;
+ if (maximum === undefined)
+ println(`${label}, styled: ${styled}`);
else
- println(`FAIL: ${label} (${recomputations} recomputations, expected at most ${maximum})`);
+ println(`${label}, styled <= ${maximum}: ${styled <= maximum}`);
}
test(() => {
@@ -37,16 +38,16 @@
settleAndReset(shadowTarget);
sheet.replaceSync(".foo { color: rgb(0, 128, 0); }");
getComputedStyle(shadowTarget).color;
- verifyRecomputationsStayBounded("shadow-local replaceSync ignores matching light-DOM bystanders", 2);
+ verifyStyledStaysBounded("shadow-local replaceSync ignores matching light-DOM bystanders", 2);
settleAndReset(shadowTarget);
sheet.replaceSync(".foo { color: rgb(255, 0, 0); }");
getComputedStyle(shadowTarget).color;
- verifyRecomputationsStayBounded("shadow-local replaceSync stays bounded on subsequent updates", 2);
+ verifyStyledStaysBounded("shadow-local replaceSync stays bounded on subsequent updates", 2);
settleAndReset(shadowTarget);
sheet.replaceSync("");
getComputedStyle(shadowTarget).color;
- verifyRecomputationsStayBounded("shadow-local replaceSync clearing the sheet stays bounded", 2);
+ verifyStyledStaysBounded("shadow-local replaceSync clearing the sheet stays bounded", 2);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/shadow-root-replacesync-slot-only-invalidation-counters.html b/Tests/LibWeb/Text/input/css/shadow-root-replacesync-slot-only-invalidation-counters.html
index d9dc01018e3..3ce1fb71bf0 100644
--- a/Tests/LibWeb/Text/input/css/shadow-root-replacesync-slot-only-invalidation-counters.html
+++ b/Tests/LibWeb/Text/input/css/shadow-root-replacesync-slot-only-invalidation-counters.html
@@ -6,15 +6,18 @@
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
- function verifyRecomputationsStayBounded(label, maximum) {
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- if (recomputations <= maximum)
- println(`PASS: ${label}`);
+ // Print whether the style engine styled at most `maximum` elements since its counters were reset, or,
+ // without a bound, how many it styled.
+ function verifyStyledStaysBounded(label, maximum) {
+ const styled = internals.styleCounters().styledElements;
+ if (maximum === undefined)
+ println(`${label}, styled: ${styled}`);
else
- println(`FAIL: ${label} (${recomputations} recomputations)`);
+ println(`${label}, styled <= ${maximum}: ${styled <= maximum}`);
}
test(() => {
@@ -39,11 +42,11 @@
settleAndReset(target);
sheet.replaceSync("slot { color: rgb(255, 0, 0); }");
getComputedStyle(target).color;
- verifyRecomputationsStayBounded("slot-only replaceSync stays scoped to the current host subtree", 4);
+ verifyStyledStaysBounded("slot-only replaceSync stays scoped to the current host subtree", 4);
settleAndReset(target);
sheet.replaceSync("");
getComputedStyle(target).color;
- verifyRecomputationsStayBounded("slot-only replaceSync removal stays scoped to the current host subtree", 4);
+ verifyStyledStaysBounded("slot-only replaceSync removal stays scoped to the current host subtree", 4);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/shadow-root-slot-style-add-remove-invalidation-counters.html b/Tests/LibWeb/Text/input/css/shadow-root-slot-style-add-remove-invalidation-counters.html
index 7fc671005f6..bfeea04d5d0 100644
--- a/Tests/LibWeb/Text/input/css/shadow-root-slot-style-add-remove-invalidation-counters.html
+++ b/Tests/LibWeb/Text/input/css/shadow-root-slot-style-add-remove-invalidation-counters.html
@@ -6,15 +6,18 @@
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
- function verifyRecomputationsStayBounded(label, maximum) {
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- if (recomputations <= maximum)
- println(`PASS: ${label}`);
+ // Print whether the style engine styled at most `maximum` elements since its counters were reset, or,
+ // without a bound, how many it styled.
+ function verifyStyledStaysBounded(label, maximum) {
+ const styled = internals.styleCounters().styledElements;
+ if (maximum === undefined)
+ println(`${label}, styled: ${styled}`);
else
- println(`FAIL: ${label} (${recomputations} recomputations)`);
+ println(`${label}, styled <= ${maximum}: ${styled <= maximum}`);
}
function attachSlotShadowRoot(host) {
@@ -44,11 +47,11 @@
settleAndReset(target);
shadowRootA.appendChild(shadowStyle);
getComputedStyle(target).color;
- verifyRecomputationsStayBounded("slotted stylesheet add ignores matching bystanders outside the current host", 4);
+ verifyStyledStaysBounded("slotted stylesheet add ignores matching bystanders outside the current host", 4);
settleAndReset(target);
shadowStyle.remove();
getComputedStyle(target).color;
- verifyRecomputationsStayBounded("slotted stylesheet remove ignores matching bystanders outside the current host", 4);
+ verifyStyledStaysBounded("slotted stylesheet remove ignores matching bystanders outside the current host", 4);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/shadow-root-stylesheet-add-remove-shadow-local-invalidation-counters.html b/Tests/LibWeb/Text/input/css/shadow-root-stylesheet-add-remove-shadow-local-invalidation-counters.html
index fd50ce46c38..033c10e3795 100644
--- a/Tests/LibWeb/Text/input/css/shadow-root-stylesheet-add-remove-shadow-local-invalidation-counters.html
+++ b/Tests/LibWeb/Text/input/css/shadow-root-stylesheet-add-remove-shadow-local-invalidation-counters.html
@@ -5,17 +5,18 @@
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
- function verifyRecomputationsStayBounded(label, maximum) {
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- // The bound is what this asserts, so the bound is what it prints: recording the exact count
- // would make the expectation depend on a number no assertion here cares about.
- if (recomputations <= maximum)
- println(`PASS: ${label} (at most ${maximum} recomputations)`);
+ // Print whether the style engine styled at most `maximum` elements since its counters were reset, or,
+ // without a bound, how many it styled.
+ function verifyStyledStaysBounded(label, maximum) {
+ const styled = internals.styleCounters().styledElements;
+ if (maximum === undefined)
+ println(`${label}, styled: ${styled}`);
else
- println(`FAIL: ${label} (${recomputations} recomputations, expected at most ${maximum})`);
+ println(`${label}, styled <= ${maximum}: ${styled <= maximum}`);
}
test(() => {
@@ -37,11 +38,11 @@
settleAndReset(shadowTarget);
shadowRoot.appendChild(shadowStyle);
getComputedStyle(shadowTarget).color;
- verifyRecomputationsStayBounded("shadow-local stylesheet add ignores matching light-DOM bystanders", 4);
+ verifyStyledStaysBounded("shadow-local stylesheet add ignores matching light-DOM bystanders", 4);
settleAndReset(shadowTarget);
shadowStyle.remove();
getComputedStyle(shadowTarget).color;
- verifyRecomputationsStayBounded("shadow-local stylesheet remove ignores matching light-DOM bystanders", 4);
+ verifyStyledStaysBounded("shadow-local stylesheet remove ignores matching light-DOM bystanders", 4);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/shared-style-sheet-copy-on-write.html b/Tests/LibWeb/Text/input/css/shared-style-sheet-copy-on-write.html
index 5e15887dc44..e6ff5b607c9 100644
--- a/Tests/LibWeb/Text/input/css/shared-style-sheet-copy-on-write.html
+++ b/Tests/LibWeb/Text/input/css/shared-style-sheet-copy-on-write.html
@@ -17,19 +17,13 @@
color(roots[0]);
color(roots[1]);
const sheet = roots[0].querySelector("style").sheet;
- let before = internals.styleEngineCounters().styleRulesCompiled;
sheet.insertRule(".target { color: red; }", 2);
- println(`first edit compiles private contents: ${internals.styleEngineCounters().styleRulesCompiled - before}`);
println(`first edit: ${color(roots[0])}, ${color(roots[1])}`);
- before = internals.styleEngineCounters().styleRulesCompiled;
sheet.insertRule(".target { color: green; }", 3);
- println(`later insertion compiles one rule: ${internals.styleEngineCounters().styleRulesCompiled - before}`);
println(`later insertion: ${color(roots[0])}, ${color(roots[1])}`);
- before = internals.styleEngineCounters().styleRulesCompiled;
sheet.cssRules[3].style.color = "blue";
- println(`later declaration edit compiles no rules: ${internals.styleEngineCounters().styleRulesCompiled - before}`);
println(`later declaration edit: ${color(roots[0])}, ${color(roots[1])}`);
roots[0].host.remove();
println(`second sheet outlives first: ${color(roots[1])}`);
diff --git a/Tests/LibWeb/Text/input/css/style-attribute-no-op-invalidation-counters.html b/Tests/LibWeb/Text/input/css/style-attribute-no-op-invalidation-counters.html
index 83f71e73360..b8bfd1bccd2 100644
--- a/Tests/LibWeb/Text/input/css/style-attribute-no-op-invalidation-counters.html
+++ b/Tests/LibWeb/Text/input/css/style-attribute-no-op-invalidation-counters.html
@@ -10,13 +10,19 @@
<script>
function settleAndReset() {
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
- function report(label) {
+ // Print whether the style engine styled at most `maximum` elements since its counters were reset, or,
+ // without a bound, how many it styled.
+ function report(label, maximum) {
internals.updateStyle();
- const counters = internals.getStyleInvalidationCounters();
- println(`${label}: ${counters.elementStyleRecomputations} recomputations, ${counters.engineComputedStyleRecords} engine records`);
+ const styled = internals.styleCounters().styledElements;
+ if (maximum === undefined)
+ println(`${label}, styled: ${styled}`);
+ else
+ println(`${label}, styled <= ${maximum}: ${styled <= maximum}`);
}
test(() => {
@@ -26,20 +32,22 @@
settleAndReset();
target.setAttribute("style", "color: red");
- report("setting identical style text");
+ report("setting identical style text", 0);
settleAndReset();
target.setAttribute("style", "color: green");
- report("setting changed style text");
+ report("setting changed style text", 1);
document.documentElement.style.setProperty("--vh", "9px");
settleAndReset();
document.documentElement.style.setProperty("--vh", "9px");
- report("setting identical custom property");
+ report("setting identical custom property", 0);
settleAndReset();
document.documentElement.style.setProperty("--vh", "10px");
- report("setting changed custom property");
+ // Only the root and the element reading --vh are styled; the others take the moved custom
+ // property without computing again.
+ report("setting changed custom property", 2);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animated-element-pseudo-elements.html b/Tests/LibWeb/Text/input/css/style-engine/animated-element-pseudo-elements.html
index 05c75b110dc..6b7a37162a4 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animated-element-pseudo-elements.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animated-element-pseudo-elements.html
@@ -14,13 +14,10 @@
test(() => {
const target = document.getElementById("target");
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
// The class change moves a value beside the running animation. The ::before inherits the
// color the animation samples over the element's record.
target.classList.add("taller");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
println(`height: ${getComputedStyle(target).height}`);
println(`::before color: ${getComputedStyle(target, "::before").color}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animated-row-moves-declarations.html b/Tests/LibWeb/Text/input/css/style-engine/animated-row-moves-declarations.html
index 8f78a45f598..f5a6257fcd2 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animated-row-moves-declarations.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animated-row-moves-declarations.html
@@ -21,11 +21,8 @@
};
const measure = (label, mutation) => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
mutation();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label}: C++ recomputations ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
println(`${label}: ${describe()}`);
};
println(`before: ${describe()}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animated-slot-style-propagation.html b/Tests/LibWeb/Text/input/css/style-engine/animated-slot-style-propagation.html
index 2749e9ffa94..fbb7d664def 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animated-slot-style-propagation.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animated-slot-style-propagation.html
@@ -49,11 +49,10 @@
animation.pause();
animation.currentTime = 500000;
internals.updateStyle();
- const before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
animation.currentTime = 750000;
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`${prefix} paint avoids descendant style work: ${after.reachedStyleNodes - before.reachedStyleNodes <= 1}`);
+ println(`${prefix} paint avoids descendant style work: ${internals.styleCounters().styledElements <= 1}`);
println(`${prefix} slot sample: ${getComputedStyle(slot).backgroundColor}`);
println(`${prefix} assigned background: ${getComputedStyle(children[39]).backgroundColor}`);
children[0].style.backgroundColor = "inherit";
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animated-style-group-overlay.html b/Tests/LibWeb/Text/input/css/style-engine/animated-style-group-overlay.html
index 298544bbf59..48384cf93f3 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animated-style-group-overlay.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animated-style-group-overlay.html
@@ -39,10 +39,5 @@
// element's color.
println(`color: ${getComputedStyle(tinter).color}`);
println(`border color: ${getComputedStyle(tinter).borderTopColor}`);
-
- const counters = internals.getStyleInvalidationCounters();
- println(`reconstruction fallbacks: ${counters.animatedStyleReconstructionFallbacks > 0 ? "some" : "none"}`);
- println(`overlay builds: ${counters.animatedStyleOverlayBuilds > 0 ? "some" : "none"}`);
- println(`full builds: ${counters.animatedStyleFullBuilds > 0 ? "some" : "none"}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animated-style-overlay-lifetime.html b/Tests/LibWeb/Text/input/css/style-engine/animated-style-overlay-lifetime.html
deleted file mode 100644
index e982fd04907..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/animated-style-overlay-lifetime.html
+++ /dev/null
@@ -1,59 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<div id="target"></div>
-<script>
- test(() => {
- const target = document.getElementById("target");
- const animation = target.animate(
- [{ transform: "translateX(0px)" }, { transform: "translateX(100px)" }],
- { duration: 1000, fill: "both" });
- animation.pause();
- animation.currentTime = 0;
- internals.updateStyle();
-
- const before = internals.styleEngineCounters();
- for (let time = 100; time < 1000; time += 100) {
- animation.currentTime = time;
- internals.updateStyle();
- }
- const sampled = internals.styleEngineCounters();
-
- println(`permanent style records added: ${sampled.styleRecordsInterned - before.styleRecordsInterned}`);
- println(`permanent metadata added: ${sampled.computedFixedMetadataInterned - before.computedFixedMetadataInterned}`);
- println(`overlay slots added: ${sampled.animationOverlaySlotsAllocated - before.animationOverlaySlotsAllocated}`);
- println(`overlay records updated: ${sampled.animationOverlayRecordsUpdated - before.animationOverlayRecordsUpdated}`);
- println(`live overlay records: ${sampled.liveAnimationOverlayRecords}`);
-
- target.remove();
- internals.updateStyle();
- const removed = internals.styleEngineCounters();
- println(`overlay slots released: ${removed.animationOverlaySlotsReleased - sampled.animationOverlaySlotsReleased}`);
- println(`live overlays after removal: ${removed.liveAnimationOverlayRecords}`);
-
- const style = document.createElement("style");
- style.textContent = `
- #pseudo-target::after {
- content: "";
- display: block;
- }
- `;
- document.head.append(style);
-
- const pseudoTarget = document.createElement("div");
- pseudoTarget.id = "pseudo-target";
- document.body.append(pseudoTarget);
- internals.updateStyle();
-
- const inheritedAnimation = pseudoTarget.animate({ color: ["red", "green"] }, { duration: 1000, fill: "forwards" });
- inheritedAnimation.pause();
- inheritedAnimation.currentTime = 500;
- internals.updateStyle();
- document.body.offsetWidth;
- inheritedAnimation.currentTime = 1000;
- internals.updateStyle();
-
- style.remove();
- internals.updateStyle();
- println("animated pseudo-element style survives removal");
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animated-style-overlay-with-box-updates-in-place.html b/Tests/LibWeb/Text/input/css/style-engine/animated-style-overlay-with-box-updates-in-place.html
deleted file mode 100644
index 9622aeb224f..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/animated-style-overlay-with-box-updates-in-place.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<div id="target"></div>
-<script>
- test(() => {
- const target = document.getElementById("target");
- // The element has a box before its animation starts, so the box names every overlay
- // record the animation samples.
- document.body.offsetWidth;
- const animation = target.animate(
- [{ transform: "translateX(0px)" }, { transform: "translateX(100px)" }],
- { duration: 1000, fill: "both" });
- animation.pause();
- animation.currentTime = 0;
- internals.updateStyle();
- document.body.offsetWidth;
-
- const before = internals.styleEngineCounters();
- for (let time = 100; time < 1000; time += 100) {
- animation.currentTime = time;
- internals.updateStyle();
- document.body.offsetWidth;
- }
- const sampled = internals.styleEngineCounters();
-
- println(`overlay slots added: ${sampled.animationOverlaySlotsAllocated - before.animationOverlaySlotsAllocated}`);
- println(`overlay records updated: ${sampled.animationOverlayRecordsUpdated - before.animationOverlayRecordsUpdated}`);
- println(`live overlay records: ${sampled.liveAnimationOverlayRecords}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animation-first-record-inherited-keyframes.html b/Tests/LibWeb/Text/input/css/style-engine/animation-first-record-inherited-keyframes.html
index af327741633..3783e6e8789 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animation-first-record-inherited-keyframes.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animation-first-record-inherited-keyframes.html
@@ -23,11 +23,9 @@
if (withChild)
target.append(child);
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
container.append(target);
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label}: C++ recomputations ${after.elementStyleRecomputations - before.elementStyleRecomputations}, animations ${target.getAnimations().map(animation => animation.animationName).join(",")}, ${read(target, child)}`);
+ println(`${label}: animations ${target.getAnimations().map(animation => animation.animationName).join(",")}, ${read(target, child)}`);
target.remove();
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animation-list-from-settled-record.html b/Tests/LibWeb/Text/input/css/style-engine/animation-list-from-settled-record.html
index 0fee16656cf..9e3e8e21cbe 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animation-list-from-settled-record.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animation-list-from-settled-record.html
@@ -23,11 +23,8 @@
// The class change moves only the longhands declaring #target's animations. The animations
// they name start in the same style update, and the values they sample reach it.
- const before = internals.getStyleInvalidationCounters();
target.className = "animating";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
println(`after: ${getComputedStyle(target).width} ${getComputedStyle(target).opacity}`);
println(`names: ${target.getAnimations().map(animation => animation.animationName).join(",")}`);
println(`durations: ${target.getAnimations().map(animation => animation.effect.getTiming().duration).join(",")}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animation-name-of-sheet-adopted-by-several-scopes.html b/Tests/LibWeb/Text/input/css/style-engine/animation-name-of-sheet-adopted-by-several-scopes.html
index 6a09f87dede..388f37e7056 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animation-name-of-sheet-adopted-by-several-scopes.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animation-name-of-sheet-adopted-by-several-scopes.html
@@ -17,11 +17,9 @@
#normal, ::slotted(#normal) { animation: fade 100s linear paused; }
#important, ::slotted(#important) { animation: fade 100s linear paused !important; }
`);
- const before = internals.getStyleInvalidationCounters().elementStyleRecomputations;
document.adoptedStyleSheets = [shared];
root.adoptedStyleSheets = [shared];
internals.updateStyle();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - before}`);
println(`normal: ${getComputedStyle(document.getElementById("normal")).width}`);
println(`important: ${getComputedStyle(document.getElementById("important")).width}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animation-name-rolled-back-plans-in-engine.html b/Tests/LibWeb/Text/input/css/style-engine/animation-name-rolled-back-plans-in-engine.html
index 68f29b86df9..49bc8913184 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animation-name-rolled-back-plans-in-engine.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animation-name-rolled-back-plans-in-engine.html
@@ -9,14 +9,12 @@
<script>
test(() => {
internals.updateStyle();
- const recomputations = () => internals.getStyleInvalidationCounters().elementStyleRecomputations;
// A reverted animation-name rolls back past every declaration to the initial value, which
// no scope declared: the engine plans the animations it names.
for (const step of [1, 2]) {
- const before = recomputations();
target.classList.toggle("reverted");
internals.updateStyle();
- println(`step ${step}: animations ${target.getAnimations().length}, C++ recomputations ${recomputations() - before}`);
+ println(`step ${step}: animations ${target.getAnimations().length}`);
}
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animation-name-shadow-scopes.html b/Tests/LibWeb/Text/input/css/style-engine/animation-name-shadow-scopes.html
index 35b0c7521e5..12c17666dfe 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animation-name-shadow-scopes.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animation-name-shadow-scopes.html
@@ -49,11 +49,9 @@
];
internals.updateStyle();
for (const [label, element] of cases) {
- const before = internals.getStyleInvalidationCounters();
element.classList.add("animating");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label}: C++ recomputations ${after.elementStyleRecomputations - before.elementStyleRecomputations}, width ${getComputedStyle(element).width}, animations ${element.getAnimations().length}`);
+ println(`${label}: width ${getComputedStyle(element).width}, animations ${element.getAnimations().length}`);
}
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animation-starts-when-hidden-subtree-is-revealed.html b/Tests/LibWeb/Text/input/css/style-engine/animation-starts-when-hidden-subtree-is-revealed.html
index 42ceb43717e..e6e6c7e7128 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animation-starts-when-hidden-subtree-is-revealed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animation-starts-when-hidden-subtree-is-revealed.html
@@ -24,11 +24,9 @@
println(`second, hidden: ${describe(second)}`);
// Revealing either subtree starts the animations its records name.
- const before = internals.getStyleInvalidationCounters().elementStyleRecomputations;
document.getElementById("never-shown").classList.remove("hidden");
shown.classList.remove("hidden");
internals.updateStyle();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - before}`);
println(`first, revealed: ${describe(first)}`);
println(`second, revealed: ${describe(second)}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/animation-underlying-style-delta.html b/Tests/LibWeb/Text/input/css/style-engine/animation-underlying-style-delta.html
index 4cc28f92456..015c0afba5c 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/animation-underlying-style-delta.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/animation-underlying-style-delta.html
@@ -18,11 +18,8 @@
animation.currentTime = 500000;
internals.updateStyle();
- const before = internals.styleEngineCounters();
target.style.backgroundColor = "red";
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`base change takes partial drive: ${after.enginePartialDrivesStarted > before.enginePartialDrivesStarted}`);
println(`animation object survives: ${target.getAnimations()[0] === animation}`);
println(`sampled color: ${getComputedStyle(target).color}`);
println(`sampled opacity: ${getComputedStyle(target).opacity}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-shorthand-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-shorthand-engine-computed.html
deleted file mode 100644
index dafd4d56ffb..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-shorthand-engine-computed.html
+++ /dev/null
@@ -1,38 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- .item { margin: attr(data-margin type(<length>)); }
- .colored { background: attr(data-color type(<color>), rgb(0, 128, 0)); }
-</style>
-<div class="item" id="item" data-margin="5px"></div>
-<div class="colored" id="colored" data-color="qqffuutt"></div>
-<script>
- // A shorthand written with attr() leaves its longhands pending the shorthand's substitution,
- // which reads the element's attributes. The style engine computes those records itself, and
- // follows an attribute change.
- function recomputations(update) {
- const before = internals.getStyleInvalidationCounters();
- update();
- internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- return after.elementStyleRecomputations - before.elementStyleRecomputations;
- }
- test(() => {
- internals.updateStyle();
- println(`C++ recomputations on arrival: ${recomputations(() => {
- for (const element of [item, colored]) {
- const clone = element.cloneNode();
- clone.removeAttribute("id");
- document.body.append(clone);
- }
- })}`);
- println(`margin: ${getComputedStyle(item).marginLeft}`);
- println(`invalid color falls back: ${getComputedStyle(colored).backgroundColor}`);
- println(`C++ recomputations on attribute change: ${recomputations(() => {
- item.dataset.margin = "7px";
- colored.dataset.color = "rgb(0, 0, 255)";
- })}`);
- println(`margin: ${getComputedStyle(item).marginLeft}`);
- println(`color: ${getComputedStyle(colored).backgroundColor}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/backdrop-read-outside-top-layer.html b/Tests/LibWeb/Text/input/css/style-engine/backdrop-read-outside-top-layer.html
index 62306fe7e11..74c092da092 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/backdrop-read-outside-top-layer.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/backdrop-read-outside-top-layer.html
@@ -7,16 +7,13 @@
<script>
test(() => {
// A ::backdrop outside the top layer generates no box, but a read of it computes it as its
- // rules say, before and after the dialog was in the top layer. The style engine answers
- // each read.
+ // rules say, before and after the dialog was in the top layer.
const target = document.getElementById("target");
const read = label => {
internals.updateStyle();
- const start = internals.styleEngineCounters();
const style = getComputedStyle(target, "::backdrop");
const values = `--own ${style.getPropertyValue("--own")}, color ${style.color}`;
- const end = internals.styleEngineCounters();
- println(`${label}: ${values}, demands left to the host ${end.pseudoRecordDemandsLeftToHost - start.pseudoRecordDemandsLeftToHost}`);
+ println(`${label}: ${values}`);
};
read("never shown");
target.showModal();
diff --git a/Tests/LibWeb/Text/input/css/style-engine/backing-element-selection-records.html b/Tests/LibWeb/Text/input/css/style-engine/backing-element-selection-records.html
index 0182e72abbe..6b3da1f6d8c 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/backing-element-selection-records.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/backing-element-selection-records.html
@@ -14,11 +14,8 @@
control.focus();
control.select();
internals.updateStyle();
- const start = internals.styleEngineCounters();
control.className = "wide";
internals.updateStyle();
- const end = internals.styleEngineCounters();
println(`selection: ${getComputedStyle(control, "::selection").backgroundColor}`);
- println(`engine pseudo records: ${end.engineComputedPseudoRecords - start.engineComputedPseudoRecords}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/boxless-pseudo-element-read-custom-properties.html b/Tests/LibWeb/Text/input/css/style-engine/boxless-pseudo-element-read-custom-properties.html
index 4583de116bf..5af585a10bf 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/boxless-pseudo-element-read-custom-properties.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/boxless-pseudo-element-read-custom-properties.html
@@ -9,15 +9,12 @@
<script>
test(() => {
// Neither pseudo-element generates a box, yet a read of either sees the custom properties
- // its rules declare over the element's. The style engine answers both reads.
+ // its rules declare over the element's.
const target = document.getElementById("target");
internals.updateStyle();
- const start = internals.styleEngineCounters();
for (const pseudo of ["::before", "::after"]) {
const style = getComputedStyle(target, pseudo);
println(`${pseudo}: --own ${style.getPropertyValue("--own")}, --inherited ${style.getPropertyValue("--inherited")}, color ${style.color}`);
}
- const end = internals.styleEngineCounters();
- println(`demands left to the host: ${end.pseudoRecordDemandsLeftToHost - start.pseudoRecordDemandsLeftToHost}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/broad-sheet-change-with-element-input.html b/Tests/LibWeb/Text/input/css/style-engine/broad-sheet-change-with-element-input.html
index 6385e674574..20dc5c5b70b 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/broad-sheet-change-with-element-input.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/broad-sheet-change-with-element-input.html
@@ -13,11 +13,11 @@
internals.updateStyle();
function mutate(label, mutation) {
- const before = internals.getStyleInvalidationCounters();
+ internals.resetStyleCounters();
mutation();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label} stays selective: ${after.elementStyleRecomputations - before.elementStyleRecomputations < 8}`);
+ const counters = internals.styleCounters();
+ println(`${label} stays selective: ${counters.styledElements < 8}`);
println(`${label} target opacity: ${getComputedStyle(target).opacity}`);
println(`${label} other opacity: ${getComputedStyle(other).opacity}`);
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/cascade-topology-mutations.html b/Tests/LibWeb/Text/input/css/style-engine/cascade-topology-mutations.html
index e3e83feb552..7e270467bc0 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/cascade-topology-mutations.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/cascade-topology-mutations.html
@@ -103,10 +103,8 @@
innerLayered.insertRule("@layer inner-b, inner-a;", 0);
});
- // A topology change that moves nothing has nothing to say.
- // FIXME: Re-appending the sheet that is already last reaches the element its rules match. The
- // order token is rewritten either way, so nothing notices that the order it describes
- // is the one it already had.
+ // A topology change that moves nothing has nothing to say: re-appending the sheet that is already
+ // last moves none of its rules against another, and changes only the style element it moved.
plan("append a sheet that is already last", () => head.appendChild(head.lastElementChild));
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/child-combinator-rule-bounded-to-its-shadow-tree.html b/Tests/LibWeb/Text/input/css/style-engine/child-combinator-rule-bounded-to-its-shadow-tree.html
index b4711b05ce4..b0634c1cb23 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/child-combinator-rule-bounded-to-its-shadow-tree.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/child-combinator-rule-bounded-to-its-shadow-tree.html
@@ -16,16 +16,17 @@
function recomputationsForSheet(cssText) {
const sheet = new CSSStyleSheet();
sheet.replaceSync(cssText);
- const before = internals.getStyleInvalidationCounters();
+ internals.resetStyleCounters();
shadow.adoptedStyleSheets = [sheet];
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- const count = after.elementStyleRecomputations - before.elementStyleRecomputations;
+ const count = internals.styleCounters().styledElements;
shadow.adoptedStyleSheets = [];
internals.updateStyle();
return count;
}
+ // A sheet adopted by the shadow root restyles only the shadow tree elements its rules can match, so
+ // none for :focus while nothing is focused, and none of the 50 list items outside it.
println(`li > div > :focus: ${recomputationsForSheet("li > div > :focus { color: red }")}`);
println(`li > div > *: ${recomputationsForSheet("li > div > * { color: red }")}`);
println(`li :focus: ${recomputationsForSheet("li :focus { color: red }")}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/computed-closure-after-style-sharing.html b/Tests/LibWeb/Text/input/css/style-engine/computed-closure-after-style-sharing.html
index fef38615c77..121507b750c 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/computed-closure-after-style-sharing.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/computed-closure-after-style-sharing.html
@@ -10,13 +10,13 @@
internals.updateStyle();
const shared = internals.styleRecordIdentity(first) === internals.styleRecordIdentity(second);
- const before = internals.getStyleInvalidationCounters();
+ internals.resetStyleCounters();
second.className = "changed";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
+ const styled = internals.styleCounters().styledElements;
println(`shared initial style: ${shared}`);
- println(`longhand evaluations: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations}`);
+ println(`styled only the changed element: ${styled <= 1}`);
println(`first background: ${getComputedStyle(first).backgroundColor}`);
println(`second background: ${getComputedStyle(second).backgroundColor}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/computed-color-scheme-closure.html b/Tests/LibWeb/Text/input/css/style-engine/computed-color-scheme-closure.html
index 94dda74053e..16590f123df 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/computed-color-scheme-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/computed-color-scheme-closure.html
@@ -9,13 +9,10 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
target.className = "after";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`color scheme longhand evaluations: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations}`);
println(`background: ${getComputedStyle(target).backgroundColor}`);
println(`inherited background: ${getComputedStyle(child).backgroundColor}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/computed-current-color-closure.html b/Tests/LibWeb/Text/input/css/style-engine/computed-current-color-closure.html
index 01483943534..2332ff915be 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/computed-current-color-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/computed-current-color-closure.html
@@ -8,13 +8,10 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
target.className = "after";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`currentColor longhand evaluations: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations}`);
println(`color: ${getComputedStyle(target).color}`);
println(`border color: ${getComputedStyle(target).borderTopColor}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/computed-font-closure.html b/Tests/LibWeb/Text/input/css/style-engine/computed-font-closure.html
index 45a62dd7ce5..5377961ee40 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/computed-font-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/computed-font-closure.html
@@ -8,13 +8,10 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
target.className = "after";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`font change longhand evaluations: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations}`);
println(`font size: ${getComputedStyle(target).fontSize}`);
println(`font-relative margin: ${getComputedStyle(target).marginLeft}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/computed-group-identities.html b/Tests/LibWeb/Text/input/css/style-engine/computed-group-identities.html
deleted file mode 100644
index f53860adac8..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/computed-group-identities.html
+++ /dev/null
@@ -1,61 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- .item {
- color: rgb(20, 24, 28);
- }
- .even {
- --marker: even;
- background-color: rgb(40, 44, 48);
- }
- .odd {
- --marker: odd;
- background-color: rgb(60, 64, 68);
- }
- .odd::before {
- content: "";
- }
-</style>
-<div id="root"></div>
-<script>
- test(() => {
- internals.updateStyle();
- const before = internals.styleEngineCounters();
- const root = document.getElementById("root");
- for (let index = 0; index < 100; ++index) {
- const item = document.createElement("div");
- item.className = `item ${index % 2 ? "odd" : "even"}`;
- root.appendChild(item);
- }
-
- internals.updateStyle();
- const after = internals.styleEngineCounters();
-
- println(`computed group handles cover the elements: ${after.computedGroupNodeHandlesPublished - before.computedGroupNodeHandlesPublished >= 100}`);
- println(`computed group sets are shared: ${after.computedGroupSetsReused - before.computedGroupSetsReused}`);
- println(`computed groups are shared: ${after.computedGroupsReused - before.computedGroupsReused}`);
- println(`inherited group handles cover the elements: ${after.inheritedGroupNodeHandlesPublished - before.inheritedGroupNodeHandlesPublished >= 100}`);
- println(`inherited group sets are shared: ${after.inheritedGroupSetsReused - before.inheritedGroupSetsReused}`);
- println(`custom property handles cover the elements: ${after.customPropertyEnvironmentNodeHandlesPublished - before.customPropertyEnvironmentNodeHandlesPublished >= 100}`);
- println(`custom property environments are shared: ${after.customPropertyEnvironmentsReused - before.customPropertyEnvironmentsReused}`);
- println(`computed fixed metadata handles cover the elements: ${after.computedFixedMetadataNodeHandlesPublished - before.computedFixedMetadataNodeHandlesPublished >= 100}`);
- println(`computed fixed metadata tuples are shared: ${after.computedFixedMetadataReused - before.computedFixedMetadataReused >= 148}`);
- println(`base style record handles cover the elements: ${after.styleRecordNodeHandlesPublished - before.styleRecordNodeHandlesPublished >= 100}`);
- println(`base style records are shared: ${after.styleRecordsReused - before.styleRecordsReused}`);
- println(`pseudo assignments are published sparsely: ${after.computedPseudoAssignmentsPublished - before.computedPseudoAssignmentsPublished >= 50}`);
-
- const laterItem = document.createElement("div");
- laterItem.className = "item even";
- root.appendChild(laterItem);
- internals.updateStyle();
- const afterLaterItem = internals.styleEngineCounters();
- println(`custom property environments survive transaction boundaries: ${afterLaterItem.customPropertyEnvironmentsReused > after.customPropertyEnvironmentsReused}`);
-
- document.styleSheets[0].deleteRule(3);
- internals.updateStyle();
- const withoutPseudos = internals.styleEngineCounters();
- println(`pseudo assignments are removed sparsely: ${withoutPseudos.computedPseudoAssignmentsRemoved - afterLaterItem.computedPseudoAssignmentsRemoved >= 50}`);
- println(`ordinary item: ${getComputedStyle(root.firstElementChild).color}`);
- println(`distinct non-inherited item: ${getComputedStyle(root.children[99]).backgroundColor}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/computed-logical-mapping-closure.html b/Tests/LibWeb/Text/input/css/style-engine/computed-logical-mapping-closure.html
index 3d3f5bf7d38..bc5beb106a8 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/computed-logical-mapping-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/computed-logical-mapping-closure.html
@@ -13,33 +13,21 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
target.className = "margins after";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
const style = getComputedStyle(target);
println(`left margin: ${style.marginLeft}`);
println(`right margin: ${style.marginRight}`);
target.className = "margins vertical";
internals.updateStyle();
- const vertical = internals.getStyleInvalidationCounters();
println(`top margin: ${getComputedStyle(target).marginTop}`);
const marginTarget = document.getElementById("margin-target");
- const beforeMargin = internals.getStyleInvalidationCounters();
- const engineBeforeMargin = internals.styleEngineCounters();
marginTarget.className = "margin-after";
internals.updateStyle();
- const margin = internals.getStyleInvalidationCounters();
- const engineMargin = internals.styleEngineCounters();
- // The engine drives a moved margin itself, re-evaluating its required driver inputs alongside
- // the family; either way nothing outside them is evaluated.
- const evaluations = margin.computedLonghandEvaluations - beforeMargin.computedLonghandEvaluations
- + (engineMargin.engineComputedLonghandEvaluations ?? 0) - (engineBeforeMargin.engineComputedLonghandEvaluations ?? 0);
- println(`margin family longhand evaluations: ${evaluations}`);
println(`changed logical margin: ${getComputedStyle(marginTarget).marginLeft}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/computed-output-key-stops.html b/Tests/LibWeb/Text/input/css/style-engine/computed-output-key-stops.html
index a26c69ac408..d68c4153bde 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/computed-output-key-stops.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/computed-output-key-stops.html
@@ -9,16 +9,10 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.styleEngineCounters();
document.styleSheets[0].cssRules[0].style.marginLeft = "96px";
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`specified winner changed: ${after.cascadeWinnerDeltaProperties > before.cascadeWinnerDeltaProperties}`);
- println(`equal computed group canonicalized: ${after.computedOutputGroupsCanonicalized > before.computedOutputGroupsCanonicalized}`);
- println(`computed output stopped propagation: ${after.computedWinnerPropagationStops > before.computedWinnerPropagationStops}`);
- println(`computed group handle stayed equal: ${after.computedGroupNodeHandlesPublished === before.computedGroupNodeHandlesPublished}`);
println(`computed margin: ${getComputedStyle(target).marginLeft}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/computed-record-reclamation.html b/Tests/LibWeb/Text/input/css/style-engine/computed-record-reclamation.html
deleted file mode 100644
index 5d33e19020b..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/computed-record-reclamation.html
+++ /dev/null
@@ -1,60 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- #target { color: attr(data-color type(<color>)); }
- .shared { color: rgb(1, 2, 3); }
- .input-initial { padding-left: 1px; }
- .input-shared { padding-left: 2px; }
-</style>
-<div id="target" data-color="rgb(0, 0, 0)"></div>
-<div id="donor" class="shared"></div>
-<div id="second-donor" class="shared"></div>
-<div id="input-parent">
- <div id="input-receiver" class="input-initial"></div>
- <div class="input-shared"></div>
-</div>
-<script>
- test(() => {
- const target = document.getElementById("target");
- internals.updateStyle();
- document.getElementById("donor").remove();
- document.getElementById("second-donor").remove();
- const inputParent = document.getElementById("input-parent");
- const inputReceiver = document.getElementById("input-receiver");
- inputReceiver.className = "input-shared";
- internals.updateStyle();
-
- const churn = (start, count) => {
- for (let index = start; index < start + count; ++index) {
- target.dataset.color = `rgb(${index & 255}, ${(index >> 8) & 255}, ${(index >> 16) & 255})`;
- internals.updateStyle();
- }
- };
-
- churn(1, 1100);
- internals.updateStyle();
- const first = internals.styleEngineCounters();
- println(`first sweep found unreachable groups: ${first.computedGroupsRetained > first.computedGroupsReachable}`);
-
- churn(1101, 1100);
- internals.updateStyle();
- const second = internals.styleEngineCounters();
- println(`second sweep found unreachable groups: ${second.computedGroupsRetained > second.computedGroupsReachable}`);
- println(`reclaimed group slots stay bounded: ${Math.abs(second.computedGroupsRetained - first.computedGroupsRetained) <= 256}`);
- println(`current style survives reclamation: ${getComputedStyle(target).color === "rgb(152, 8, 0)"}`);
- inputParent.style.color = "rgb(4, 5, 6)";
- internals.updateStyle();
- println(`stale input record survives reclamation: ${getComputedStyle(inputReceiver).paddingLeft === "2px" && getComputedStyle(inputReceiver).color === "rgb(4, 5, 6)"}`);
-
- // The engine's first-record cache holds no record alive past a sweep; a later element
- // alike derives its record again.
- const beforeReceiver = internals.styleEngineCounters();
- const receiver = document.createElement("div");
- receiver.className = "shared";
- document.body.appendChild(receiver);
- internals.updateStyle();
- const afterReceiver = internals.styleEngineCounters();
- const derivedRecords = (afterReceiver.engineComputedRecordDeltas ?? 0) - (beforeReceiver.engineComputedRecordDeltas ?? 0);
- println(`style derived after reclamation: ${derivedRecords > 0 && getComputedStyle(receiver).color === "rgb(1, 2, 3)"}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/computed-style-record-view-pins.html b/Tests/LibWeb/Text/input/css/style-engine/computed-style-record-view-pins.html
deleted file mode 100644
index f8a110b98c1..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/computed-style-record-view-pins.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- #target.changed {
- color: blue;
- }
-</style>
-<div id="target" style="color: red"></div>
-<script>
- test(() => {
- document.body.offsetWidth;
- let before = internals.styleEngineCounters().computedStyleRecordViewPins;
- const subtree = document.createElement("div");
- subtree.innerHTML = "<div><span>text</span></div>".repeat(100);
- document.body.appendChild(subtree);
- subtree.offsetWidth;
- let after = internals.styleEngineCounters().computedStyleRecordViewPins;
- println(`initial layout record view pins unchanged: ${after === before}`);
-
- before = after;
- target.classList.add("changed");
- target.offsetWidth;
- after = internals.styleEngineCounters().computedStyleRecordViewPins;
- println(`style update record view pins unchanged: ${after === before}`);
-
- before = after;
- getComputedStyle(document.getElementById("target")).color;
- after = internals.styleEngineCounters().computedStyleRecordViewPins;
- println(`computed style record view pins increased: ${after > before}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/computed-winner-group-closure.html b/Tests/LibWeb/Text/input/css/style-engine/computed-winner-group-closure.html
index cd3d19ba0af..c25de83391c 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/computed-winner-group-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/computed-winner-group-closure.html
@@ -10,27 +10,20 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
target.className = "after";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`winner closure longhand evaluations: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations}`);
println(`changed value: ${getComputedStyle(target).opacity}`);
println(`unchanged value: ${getComputedStyle(target).color}`);
target.className = "leaves";
internals.updateStyle();
- const leaves = internals.getStyleInvalidationCounters();
- println(`independent leaf evaluations: ${leaves.computedLonghandEvaluations - after.computedLonghandEvaluations}`);
println(`independent leaf opacity: ${getComputedStyle(target).opacity}`);
println(`independent leaf background: ${getComputedStyle(target).backgroundColor}`);
target.className = "broad";
internals.updateStyle();
- const broad = internals.getStyleInvalidationCounters();
- println(`mixed leaf and logical evaluations: ${broad.computedLonghandEvaluations - leaves.computedLonghandEvaluations}`);
println(`logical value: ${getComputedStyle(target).marginInlineStart}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/connected-selector-query-leaves-pending-input.html b/Tests/LibWeb/Text/input/css/style-engine/connected-selector-query-leaves-pending-input.html
index 68066d7db83..92b068ec43e 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/connected-selector-query-leaves-pending-input.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/connected-selector-query-leaves-pending-input.html
@@ -12,34 +12,19 @@
const target = document.createElement("span");
root.appendChild(target);
- const leavesInputPending = operation => {
- const before = internals.styleEngineCounters();
- const result = operation();
- const after = internals.styleEngineCounters();
- return result && after.rawMutationRecords === before.rawMutationRecords;
- };
-
target.className = "query-first";
println(`querySelector observes mutation: ${document.querySelector("#root > .query-first") === target}`);
- println(`querySelector leaves style input pending: ${leavesInputPending(() => {
- target.className = "query-first-next";
- return document.querySelector("#root > .query-first-next") === target;
- })}`);
+ target.className = "query-first-next";
+ println(`querySelector observes another mutation: ${document.querySelector("#root > .query-first-next") === target}`);
- println(`querySelectorAll leaves style input pending: ${leavesInputPending(() => {
- target.className = "query-all";
- return root.querySelectorAll(":scope > .query-all")[0] === target;
- })}`);
+ target.className = "query-all";
+ println(`querySelectorAll observes mutation: ${root.querySelectorAll(":scope > .query-all")[0] === target}`);
- println(`matches leaves style input pending: ${leavesInputPending(() => {
- target.className = "matches";
- return target.matches("#root > .matches");
- })}`);
+ target.className = "matches";
+ println(`matches observes mutation: ${target.matches("#root > .matches")}`);
- println(`closest leaves style input pending: ${leavesInputPending(() => {
- root.className = "closest";
- return target.closest("body > .closest") === root;
- })}`);
+ root.className = "closest";
+ println(`closest observes mutation: ${target.closest("body > .closest") === root}`);
root.classList.add("style-flush");
document.querySelector("#root.style-flush > span");
diff --git a/Tests/LibWeb/Text/input/css/style-engine/connected-subtree-common-class-fanout.html b/Tests/LibWeb/Text/input/css/style-engine/connected-subtree-common-class-fanout.html
deleted file mode 100644
index 7306fee3d38..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/connected-subtree-common-class-fanout.html
+++ /dev/null
@@ -1,79 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<div id="app"></div>
-<script>
- test(() => {
- const classCount = 600;
- const classesPerElement = 12;
- const style = document.createElement("style");
- // Model a utility sheet whose custom-property declarations prevent retaining a complete
- // winner inventory, while the portal-dependent rule loses the cascade everywhere.
- style.textContent = `
- *, ::before, ::after { box-sizing: border-box; }
- .item { color: black !important; }
- .shared { animation-name: none; background: white; }
- body.open .item { color: red; }
- ` + Array.from({ length: classCount }, (_, index) => `
- .utility-${index} { --utility-${index}: ${index}; }
- .utility-${index} .utility-${(index + 1) % classCount} { --descendant-${index}: ${index}; }
- .utility-${index}:hover .utility-${(index + 2) % classCount} { --hover-descendant-${index}: ${index}; }
- .utility-${index} + .utility-${(index + 3) % classCount} { --adjacent-${index}: ${index}; }
- .utility-${index} ~ .utility-${(index + 4) % classCount} { --sibling-${index}: ${index}; }
- .utility-${index}:where(.dark, .dark *) { --dark-${index}: ${index}; }
- `).join("\n");
- document.head.append(style);
-
- const utilityClasses = start => Array.from(
- { length: classesPerElement },
- (_, offset) => `utility-${(start + offset) % classCount}`,
- ).join(" ");
-
- for (let index = 0; index < 1000; ++index) {
- const element = document.createElement("div");
- element.className = `item ${utilityClasses(index)}`;
- if (index % 5 === 0)
- app.append(element);
- else
- app.lastElementChild.append(element);
- }
-
- internals.updateStyle();
- app.offsetWidth;
- internals.resetStyleInvalidationCounters();
- // The elements styled alike share a record, whether the C++ computation or the engine
- // computes it.
- const engineSharedRecords = () => {
- const engine = internals.styleEngineCounters();
- return (engine.engineComputedRecordSharedHits ?? 0) + (engine.engineComputedRecordCohortHits ?? 0);
- };
- const engineSharedBefore = engineSharedRecords();
-
- const portal = document.createElement("div");
- portal.className = "portal";
- const portalTarget = document.createElement("div");
- portal.append(portalTarget);
- for (let index = 0; index < 150; ++index) {
- const element = document.createElement("div");
- element.className = utilityClasses(index);
- if (index % 5 === 0)
- portalTarget.append(element);
- else
- portalTarget.lastElementChild.append(element);
- }
- for (let index = 0; index < 120; ++index) {
- const element = document.createElement("div");
- element.className = "shared";
- portalTarget.append(element);
- }
- document.body.append(portal);
- document.body.classList.add("open");
- portalTarget.firstElementChild.classList.add("utility-59");
-
- internals.updateStyle();
- const counters = internals.getStyleInvalidationCounters();
- println(`no-op reactions suppressed: ${counters.styleEnginePublishedReactions < 700}`);
- const sharedRecords = counters.elementStyleSharedComputations + engineSharedRecords() - engineSharedBefore;
- println(`none animation names remain shareable: ${sharedRecords >= 100}`);
- println(`inserted elements were styled: ${counters.elementComputedStyleChanges >= 271}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/container-computed-in-same-batch.html b/Tests/LibWeb/Text/input/css/style-engine/container-computed-in-same-batch.html
index 0e313b71f61..2f9aba98a81 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/container-computed-in-same-batch.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/container-computed-in-same-batch.html
@@ -16,15 +16,13 @@
<div class="container" id="container"><div class="gated" id="gated"></div><div class="function" id="function"></div></div>
<script>
// A container C++ computes in the same update as its children, whose container-gated rule and
- // custom function @container ask about the container's new style. Prints how many elements C++
- // computed and what the children's conditions decided.
+ // custom function @container ask about the container's new style. Prints what the children's
+ // conditions decided.
test(() => {
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
document.getElementById("container").classList.add("on");
internals.updateStyle();
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
const width = id => getComputedStyle(document.getElementById(id)).width;
- println(`C++ recomputations ${recomputations}, gated ${width("gated")}, function ${width("function")}`);
+ println(`gated ${width("gated")}, function ${width("function")}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/container-length-record-admission.html b/Tests/LibWeb/Text/input/css/style-engine/container-length-record-admission.html
index 32a9f0025b5..8067f976995 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/container-length-record-admission.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/container-length-record-admission.html
@@ -12,22 +12,17 @@
<div class="container" id="second"><span></span><div class="target" id="secondTarget"></div></div>
<script>
// Switches container-relative lengths on in two elements that already have records, under
- // containers of different widths, and prints how often the style engine refused their values
- // and how many elements C++ computed instead.
+ // containers of different widths, and prints what they compute to.
test(() => {
const width = element => getComputedStyle(element).width;
const widths = () => `${width(firstTarget)}, ${width(secondTarget)}`;
document.body.offsetWidth;
println(`initial: ${widths()}`);
for (const className of ["direct", "mixed"]) {
- const before = Object.assign({}, internals.styleEngineCounters());
- internals.resetStyleInvalidationCounters();
firstTarget.className = `target ${className}`;
secondTarget.className = `target ${className}`;
internals.updateStyle();
- const after = internals.styleEngineCounters();
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- println(`${className}: value refusals ${after.engineComputedRecordBailValue - before.engineComputedRecordBailValue}, C++ recomputations ${recomputations}, widths ${widths()}`);
+ println(`${className}: widths ${widths()}`);
}
first.style.width = "250px";
document.body.offsetWidth;
diff --git a/Tests/LibWeb/Text/input/css/style-engine/converging-style-input-shares-style.html b/Tests/LibWeb/Text/input/css/style-engine/converging-style-input-shares-style.html
index 275ae94c4e9..a1e9b1b24b8 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/converging-style-input-shares-style.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/converging-style-input-shares-style.html
@@ -23,18 +23,13 @@
const items = document.querySelectorAll("span");
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
- const engineCountersBefore = internals.styleEngineCounters();
- const engineSharedBefore = (engineCountersBefore.engineComputedRecordSharedHits ?? 0) + (engineCountersBefore.engineComputedRecordCohortHits ?? 0);
+ internals.resetStyleCounters();
for (const item of items)
item.className = "new";
internals.updateStyle();
- const counters = internals.getStyleInvalidationCounters();
- const engineCounters = internals.styleEngineCounters();
- const engineShared = (engineCounters.engineComputedRecordSharedHits ?? 0) + (engineCounters.engineComputedRecordCohortHits ?? 0) - engineSharedBefore;
- println(`shared converging style: ${counters.elementStyleSharedComputations >= 1 || engineShared >= 1}`);
- println(`shared style transition damage: ${counters.styleRecordPropertyDamageCacheHits >= 1}`);
+ const counters = internals.styleCounters();
+ println(`shared converging style: ${counters.sharedElements + counters.reusedElements >= 1}`);
println(`colors became green: ${[...items].every(item => getComputedStyle(item).color === "rgb(0, 128, 0)")}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/counter-style-change-does-not-restyle-children.html b/Tests/LibWeb/Text/input/css/style-engine/counter-style-change-does-not-restyle-children.html
index 5bc75f8ca54..5ed40a54267 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/counter-style-change-does-not-restyle-children.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/counter-style-change-does-not-restyle-children.html
@@ -17,16 +17,20 @@
internals.updateStyle();
const listWidth = list.getBoundingClientRect().width;
const generatedWidth = generated.getBoundingClientRect().width;
- const before = internals.getStyleInvalidationCounters();
+ internals.resetStyleCounters();
document.getElementById("sheet").sheet.cssRules[0].symbols = "'++++'";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
+ const markerRebuilt = list.getBoundingClientRect().width > listWidth;
+ const generatedRebuilt = generated.getBoundingClientRect().width > generatedWidth;
+ const counters = internals.styleCounters();
const elements = document.getElementsByTagName("*").length;
println(`elements: ${elements}`);
- println(`records computed: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords}`);
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
- println(`transactions: ${after.styleEngineTransactionSetups - before.styleEngineTransactionSetups}`);
- println(`marker rebuilt: ${list.getBoundingClientRect().width > listWidth}`);
- println(`generated content rebuilt: ${generated.getBoundingClientRect().width > generatedWidth}`);
+ // FIXME: The change should restyle at most the two elements resolving the counter style, and none of
+ // their children (styled <= 2), but the style engine also restyles the children whose records name
+ // the counter-style registry through the list-style-type they inherit.
+ println(`styled: ${counters.styledElements}, full passes: ${counters.fullPasses}`);
+ println(`rebuilding the boxes restyles nothing again: ${counters.passes === 1}`);
+ println(`marker rebuilt: ${markerRebuilt}`);
+ println(`generated content rebuilt: ${generatedRebuilt}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/counter-style-change-spares-unrelated-records.html b/Tests/LibWeb/Text/input/css/style-engine/counter-style-change-spares-unrelated-records.html
index a639be3281d..f35fdd78f19 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/counter-style-change-spares-unrelated-records.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/counter-style-change-spares-unrelated-records.html
@@ -8,17 +8,14 @@
<div id="plain">plain</div>
<script>
// A counter style reaches only the records that resolved one. An unrelated rule change in the
- // same update is the engine's to compute, while the list item that names the style is not.
+ // same update still reaches its element, as does the change to the list item naming the style.
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
const plainRecordBefore = internals.styleRecordIdentity(plain);
document.getElementById("sheet").sheet.insertRule("@counter-style stars { system: cyclic; symbols: '*'; }");
plain.classList.add("moved");
item.classList.add("moved");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`an engine-computed record was published: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords >= 1}`);
println(`plain received a new style record: ${internals.styleRecordIdentity(plain) !== plainRecordBefore}`);
println(`plain color: ${getComputedStyle(plain).color}`);
println(`item color: ${getComputedStyle(item).color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/counter-style-observer-identity.html b/Tests/LibWeb/Text/input/css/style-engine/counter-style-observer-identity.html
deleted file mode 100644
index 5145f1e244a..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/counter-style-observer-identity.html
+++ /dev/null
@@ -1,34 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- @counter-style marker {
- system: cyclic;
- symbols: "A";
- }
-
- .target::before {
- content: counter(item, marker);
- counter-increment: item;
- }
-</style>
-<div id="target" class="target"></div>
-<script>
- test(() => {
- internals.updateStyle();
- const contentBefore = getComputedStyle(target, "::before").content;
- const before = internals.styleEngineCounters();
- const environmentBefore = internals.getStyleInvalidationCounters().styleEnvironmentVersion;
-
- const sheet = document.styleSheets[0];
- sheet.deleteRule(0);
- sheet.insertRule('@counter-style marker { system: cyclic; symbols: "B"; }', 0);
- internals.updateStyle();
-
- const after = internals.styleEngineCounters();
- const contentAfter = getComputedStyle(target, "::before").content;
- println(`environment unchanged: ${internals.getStyleInvalidationCounters().styleEnvironmentVersion === environmentBefore}`);
- println(`computed content stayed equal: ${contentAfter === contentBefore}`);
- println(`observer metadata changed: ${after.computedFixedMetadataNodeHandlesPublished > before.computedFixedMetadataNodeHandlesPublished}`);
- println(`style record changed: ${after.styleRecordNodeHandlesPublished > before.styleRecordNodeHandlesPublished}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/counter-style-records-shared-per-scope.html b/Tests/LibWeb/Text/input/css/style-engine/counter-style-records-shared-per-scope.html
index c60af2030f2..37e70b3e07a 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/counter-style-records-shared-per-scope.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/counter-style-records-shared-per-scope.html
@@ -25,11 +25,6 @@
const first_root = attach(document.getElementById("first"), "A");
const second_root = attach(document.getElementById("second"), "BBBBBBBB");
internals.updateStyle();
- const shared_hits = () => {
- const counters = internals.styleEngineCounters();
- return counters.engineComputedRecordSharedHits + counters.engineComputedRecordCohortHits;
- };
- const before = shared_hits();
const first = append_items(first_root);
const second = append_items(second_root);
internals.updateStyle();
@@ -37,7 +32,6 @@
// The consumers of one scope's counter style share a record, as do their markers, and
// neither answers for a consumer of the other scope's; an element naming no counter style
// shares its record across scopes.
- println(`consumer records shared: ${shared_hits() - before}`);
println(`first scope's consumers share a record: ${first.every(item => record(item) === record(first[0]))}`);
println(`second scope's consumers share a record: ${second.every(item => record(item) === record(second[0]))}`);
println(`scopes' consumers hold different records: ${record(first[0]) !== record(second[0])}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/counter-style-root-preparation.html b/Tests/LibWeb/Text/input/css/style-engine/counter-style-root-preparation.html
index 385de480288..449d394614e 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/counter-style-root-preparation.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/counter-style-root-preparation.html
@@ -9,12 +9,9 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.styleEngineCounters();
sheet.sheet.insertRule("@counter-style stars { system: cyclic; symbols: '*'; }");
document.documentElement.classList.add("moved");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`root font prepared: ${after.rootFontInputsPrepared > before.rootFontInputsPrepared}`);
println(`plain width: ${getComputedStyle(plain).width}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/counter-style-shared-record-mutation.html b/Tests/LibWeb/Text/input/css/style-engine/counter-style-shared-record-mutation.html
index d224eaea39c..f5ba20adb84 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/counter-style-shared-record-mutation.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/counter-style-shared-record-mutation.html
@@ -15,29 +15,17 @@
<script>
test(() => {
internals.updateStyle();
- const initialCounters = internals.getStyleInvalidationCounters();
for (let index = 0; index < 16; ++index)
container.appendChild(document.createElement("div"));
const targets = [...container.children];
const initialWidths = targets.map(target => target.getBoundingClientRect().width);
- const settledCounters = internals.getStyleInvalidationCounters();
- println(`initial consumers answered by engine: ${settledCounters.engineComputedStyleRecords - initialCounters.engineComputedStyleRecords >= targets.length}`);
- println(`initial C++ recomputations: ${settledCounters.elementStyleRecomputations - initialCounters.elementStyleRecomputations}`);
const counterContent = document.getElementById("counter-content");
const initialCounterContentWidth = counterContent.getBoundingClientRect().width;
- const beforeMutation = internals.getStyleInvalidationCounters();
- const beforeMutationEngine = internals.styleEngineCounters();
document.styleSheets[0].cssRules[0].symbols = '"BBBBBBBB"';
println(`all shared consumers update: ${targets.every((target, index) => target.getBoundingClientRect().width > initialWidths[index])}`);
const counterContentUpdates = counterContent.getBoundingClientRect().width > initialCounterContentWidth;
- const afterMutation = internals.getStyleInvalidationCounters();
- // Records are shared among the consumers through the records the engine derives once for a cohort.
- const afterMutationEngine = internals.styleEngineCounters();
- const recordsWereShared = afterMutationEngine.engineComputedRecordCohortHits > beforeMutationEngine.engineComputedRecordCohortHits;
- println(`counter-style consumers answered by engine: ${afterMutation.engineComputedStyleRecords - beforeMutation.engineComputedStyleRecords >= targets.length && afterMutation.elementStyleRecomputations === beforeMutation.elementStyleRecomputations}`);
document.styleSheets[0].cssRules[0].symbols = '"A"';
println(`all shared consumers restore: ${targets.every((target, index) => target.getBoundingClientRect().width === initialWidths[index])}`);
- println(`records were shared: ${recordsWereShared}`);
println(`counter content consumer updates: ${counterContentUpdates}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/cssom-program-input-precision.html b/Tests/LibWeb/Text/input/css/style-engine/cssom-program-input-precision.html
index 057f40dd9e6..d1d117e1985 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/cssom-program-input-precision.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/cssom-program-input-precision.html
@@ -13,31 +13,36 @@
shadow.adoptedStyleSheets = [sheet];
internals.updateStyle();
- function mutate(label, mutation) {
- const before = internals.getStyleInvalidationCounters();
- const engineBefore = internals.styleEngineCounters();
+ // Print whether the change styled at most `maximum` elements, or, without a bound, how many it
+ // styled and whether in a full pass.
+ function mutate(label, mutation, maximum) {
+ internals.resetStyleCounters();
mutation();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- const engineAfter = internals.styleEngineCounters();
- println(`${label} environment changed: ${after.styleEnvironmentVersion !== before.styleEnvironmentVersion}`);
- println(`${label} topology changed: ${engineAfter.cascadeTopologyDeltas !== engineBefore.cascadeTopologyDeltas}`);
+ const lastPass = internals.styleLastPass();
+ if (maximum === undefined)
+ println(`${label} styled: ${lastPass.styled.length}, full pass: ${lastPass.fullPass}`);
+ else
+ println(`${label} styled <= ${maximum}: ${lastPass.styled.length <= maximum}`);
println(`${label} colors: ${getComputedStyle(target).color}, ${getComputedStyle(shadowTarget).color}`);
}
- mutate("repeat layers", () => sheet.insertRule("@layer base, theme;", 0));
- mutate("remove repeated layers", () => sheet.deleteRule(0));
- mutate("reorder layers", () => sheet.insertRule("@layer theme, base;", 0));
- mutate("restore layers", () => sheet.deleteRule(0));
- mutate("insert style rule", () => sheet.insertRule("#target { color: green; }", sheet.cssRules.length));
- mutate("edit declarations", () => sheet.cssRules[sheet.cssRules.length - 1].style.color = "purple");
- mutate("replace declarations", () => sheet.cssRules[sheet.cssRules.length - 1].style.cssText = "--color: olive; color: var(--color)");
- mutate("edit custom property", () => sheet.cssRules[sheet.cssRules.length - 1].style.setProperty("--color", "green"));
- mutate("delete style rule", () => sheet.deleteRule(sheet.cssRules.length - 1));
- mutate("insert grouped rules", () => sheet.insertRule("@media all { #target { color: orange; } }", sheet.cssRules.length));
- mutate("delete grouped rules", () => sheet.deleteRule(sheet.cssRules.length - 1));
- mutate("insert nested rules", () => sheet.insertRule("#target { @media all { color: brown; } }", sheet.cssRules.length));
- mutate("delete nested rules", () => sheet.deleteRule(sheet.cssRules.length - 1));
+ // Repeating and removing repeated layer statements restyles nothing, and every other change but the
+ // font feature values only the two targets.
+ mutate("repeat layers", () => sheet.insertRule("@layer base, theme;", 0), 0);
+ mutate("remove repeated layers", () => sheet.deleteRule(0), 0);
+ mutate("reorder layers", () => sheet.insertRule("@layer theme, base;", 0), 2);
+ mutate("restore layers", () => sheet.deleteRule(0), 2);
+ mutate("insert style rule", () => sheet.insertRule("#target { color: green; }", sheet.cssRules.length), 2);
+ mutate("edit declarations", () => sheet.cssRules[sheet.cssRules.length - 1].style.color = "purple", 2);
+ mutate("replace declarations", () => sheet.cssRules[sheet.cssRules.length - 1].style.cssText = "--color: olive; color: var(--color)", 2);
+ mutate("edit custom property", () => sheet.cssRules[sheet.cssRules.length - 1].style.setProperty("--color", "green"), 2);
+ mutate("delete style rule", () => sheet.deleteRule(sheet.cssRules.length - 1), 2);
+ mutate("insert grouped rules", () => sheet.insertRule("@media all { #target { color: orange; } }", sheet.cssRules.length), 2);
+ mutate("delete grouped rules", () => sheet.deleteRule(sheet.cssRules.length - 1), 2);
+ mutate("insert nested rules", () => sheet.insertRule("#target { @media all { color: brown; } }", sheet.cssRules.length), 2);
+ mutate("delete nested rules", () => sheet.deleteRule(sheet.cssRules.length - 1), 2);
+ // A @font-feature-values rule for a family nobody uses restyles nothing.
mutate("insert font feature values", () => sheet.insertRule("@font-feature-values PrecisionFont { @stylistic { alternate: 1; } }", sheet.cssRules.length));
mutate("delete font feature values", () => sheet.deleteRule(sheet.cssRules.length - 1));
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-function-input-precision.html b/Tests/LibWeb/Text/input/css/style-engine/custom-function-input-precision.html
index f834273f648..2e370005efc 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-function-input-precision.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-function-input-precision.html
@@ -11,14 +11,16 @@
println(`initial width: ${getComputedStyle(target).width}`);
const sheet = definitions.sheet;
+ internals.updateStyle();
+
+ // Each change stays selective: only the element calling the custom function restyles.
function change(label, callback) {
- const before = internals.getStyleInvalidationCounters();
+ internals.resetStyleCounters();
callback();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label} environment unchanged: ${after.styleEnvironmentVersion === before.styleEnvironmentVersion}`);
- println(`${label} stays selective: ${after.elementStyleRecomputations - before.elementStyleRecomputations < 16}`);
+ const counters = internals.styleCounters();
println(`${label} width: ${getComputedStyle(target).width}`);
+ println(`${label} styled: ${counters.styledElements}, full passes: ${counters.fullPasses}`);
}
change("delete", () => sheet.deleteRule(0));
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-absorption-resolves-declared-once.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-absorption-resolves-declared-once.html
index 55d6899cf5a..a8af4705edc 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-property-absorption-resolves-declared-once.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-absorption-resolves-declared-once.html
@@ -25,10 +25,6 @@
internals.updateStyle();
- const counters = internals.getStyleInvalidationCounters();
- println(`custom property elements: ${counters.customPropertyElements}`);
- println(`custom property resolutions: ${counters.customPropertyResolutions}`);
- println(`custom property value computations: ${counters.customPropertyValueComputations}`);
println(`margin: ${getComputedStyle(host.firstElementChild).marginLeft}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-dependency-order.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-dependency-order.html
index 33adf5c455d..f963b623131 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-property-dependency-order.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-dependency-order.html
@@ -43,13 +43,5 @@
// A reference sitting in a fallback that is never chosen creates no cycle.
println(`fallback-cycle margin: ${getComputedStyle(fallbackCycle).marginBottom}`);
println(`fallback-cycle --p: [${getComputedStyle(fallbackCycle).getPropertyValue("--p")}]`);
-
- // How much walking those answers took. Declared values is the input size; computations
- // above it are values walked into again for another value's sake.
- const counters = internals.getStyleInvalidationCounters();
- println(`declared values resolved: ${counters.customPropertyResolutions}`);
- println(`value computations: ${counters.customPropertyValueComputations}`);
- println(`computations answered from finished values: ${counters.customPropertyOverlayHits}`);
- println(`values resolved inside a reference cycle: ${counters.customPropertyCycleParticipants}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-beside-inheriting-registration.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-beside-inheriting-registration.html
index 30ec8f71717..53d3760a477 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-beside-inheriting-registration.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-beside-inheriting-registration.html
@@ -13,15 +13,10 @@
test(() => {
CSS.registerProperty({ name: "--size", syntax: "<length>", inherits: true, initialValue: "0px" });
internals.updateStyle();
- const before = Object.assign({}, internals.styleEngineCounters());
- internals.resetStyleInvalidationCounters();
document.getElementById("unrelated").classList.add("wide");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`environment refusals: ${after.engineCustomPropertyEnvironmentBails - before.engineCustomPropertyEnvironmentBails}`);
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations}`);
println(`inherited value: ${getComputedStyle(document.getElementById("child")).getPropertyValue("--other")}`);
println(`registered value: ${getComputedStyle(document.getElementById("declarer")).getPropertyValue("--size")}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-beside-non-inheriting-registration.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-beside-non-inheriting-registration.html
index 4f0e30e930b..b23a151bf9a 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-beside-non-inheriting-registration.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-beside-non-inheriting-registration.html
@@ -14,15 +14,10 @@
// a child inherits its parent's environment without the name, and `inherit` reads it whole.
test(() => {
internals.updateStyle();
- const before = Object.assign({}, internals.styleEngineCounters());
- internals.resetStyleInvalidationCounters();
document.getElementById("parent").classList.add("wide");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`environment refusals: ${after.engineCustomPropertyEnvironmentBails - before.engineCustomPropertyEnvironmentBails}`);
- println(`environments the engine resolved: ${after.engineCustomPropertyEnvironmentsResolved - before.engineCustomPropertyEnvironmentsResolved}`);
for (const id of ["parent", "child", "declaring", "explicit"]) {
const style = getComputedStyle(document.getElementById(id));
println(`${id}: --local ${style.getPropertyValue("--local")}, --shared ${style.getPropertyValue("--shared")}, width ${style.width}, height ${style.height}, margin-left ${style.marginLeft}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-resolves-once.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-resolves-once.html
index 8757a9e762f..5f573384a37 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-resolves-once.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-environment-resolves-once.html
@@ -14,13 +14,8 @@
// Fifty elements are handed the same ten declarations against the same inherited
// environment, so there is one environment between them and it resolves once.
host.innerHTML = '<div class="themed">x</div>'.repeat(50);
- const before = internals.styleEngineCounters();
internals.updateStyle();
- const counters = internals.styleEngineCounters();
- println(`environments resolved: ${(counters.engineCustomPropertyEnvironmentsResolved ?? 0) - (before.engineCustomPropertyEnvironmentsResolved ?? 0)}`);
- println(`environment memo hits: ${(counters.engineCustomPropertyEnvironmentMemoHits ?? 0) - (before.engineCustomPropertyEnvironmentMemoHits ?? 0)}`);
- println(`environment answer hits: ${(counters.engineCustomPropertyEnvironmentAnswerHits ?? 0) - (before.engineCustomPropertyEnvironmentAnswerHits ?? 0)}`);
println(`padding: ${getComputedStyle(host.firstElementChild).paddingTop}`);
// An element whose values differ resolves an environment of its own, and its neighbours
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-move-over-own-declarations.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-move-over-own-declarations.html
index 65c8c5d3739..574552c9168 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-property-move-over-own-declarations.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-move-over-own-declarations.html
@@ -16,12 +16,8 @@
internals.updateStyle();
document.body.offsetWidth;
const root = document.getElementById("root");
- const before = internals.getStyleInvalidationCounters();
root.style.setProperty("--theme", "blue");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`records computed: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords}`);
- println(`transactions: ${after.styleEngineTransactionSetups - before.styleEngineTransactionSetups}`);
for (const reader of document.querySelectorAll(".reader"))
println(`reader: ${getComputedStyle(reader).color}`);
for (const scope of document.querySelectorAll(".scope"))
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-read-set.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-read-set.html
index b3269cfa16a..7964d2b2729 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-property-read-set.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-read-set.html
@@ -39,22 +39,18 @@
host.offsetWidth;
getComputedStyle(maybe, "::before").content;
- internals.resetStyleInvalidationCounters();
document.documentElement.style.setProperty("--changed", "rgb(128, 0, 128)");
internals.updateStyle();
- const counters = internals.getStyleInvalidationCounters();
const unrelated = host.lastElementChild;
println(`changed value: ${getComputedStyle(changed).color}`);
println(`fallback value: ${getComputedStyle(fallback).color}`);
println(`unrelated value: ${getComputedStyle(unrelated).color}`);
println(`refreshed inherited value: ${getComputedStyle(unrelated).getPropertyValue("--changed")}`);
- println(`recomputations: ${counters.elementStyleRecomputations}`);
// Pseudo-element substitution contributes to the originating element's read set even when
// its previous value produced no pseudo-element.
- internals.resetStyleInvalidationCounters();
document.documentElement.style.setProperty("--show", '"created"');
internals.updateStyle();
println(`changed binding creates pseudo: ${getComputedStyle(maybe, "::before").content}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-registration-is-targeted.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-registration-is-targeted.html
index 76a2ab519e1..e0c832470e9 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-property-registration-is-targeted.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-registration-is-targeted.html
@@ -11,14 +11,6 @@
<div class="declarer"></div>
<div class="reference"></div>
<script>
- function printRegistrationCounters(label, environmentVersion, graphCounters) {
- const counters = internals.getStyleInvalidationCounters();
- const currentGraphCounters = internals.styleEngineCounters();
- println(`${label} recomputations: ${counters.elementStyleRecomputations}`);
- println(`${label} environment deltas: ${currentGraphCounters.environmentDeltas - graphCounters.environmentDeltas}`);
- println(`${label} environment version unchanged: ${counters.styleEnvironmentVersion === environmentVersion}`);
- }
-
test(() => {
const sheet = document.getElementById("registrations").sheet;
// The first CSSOM edit recompiles shared contents into a private stylesheet. Insert and remove
@@ -27,9 +19,7 @@
sheet.deleteRule(0);
internals.updateStyle();
- let environmentVersion = internals.getStyleInvalidationCounters().styleEnvironmentVersion;
- let graphCounters = internals.styleEngineCounters();
- internals.resetStyleInvalidationCounters();
+ internals.resetStyleCounters();
document.getElementById("registrations").sheet.insertRule(
"@property --registered { syntax: '<length>'; inherits: false; initial-value: 0px; }"
@@ -37,7 +27,9 @@
document.getElementById("registrations").sheet.insertRule(":not(*) { color: red; }");
internals.updateStyle();
- printRegistrationCounters("@property", environmentVersion, graphCounters);
+ // The registration restyles at most the declarer and the reference.
+ const lastPass = internals.styleLastPass();
+ println(`@property styled: ${lastPass.styled.length}, full pass: ${lastPass.fullPass}`);
println(`unrelated registered initial value: ${getComputedStyle(unrelated).getPropertyValue("--registered")}`);
document.querySelector(".reference").remove();
@@ -48,10 +40,8 @@
apiReference.style.width = "var(--api-registered)";
document.body.appendChild(apiReference);
internals.updateStyle();
- environmentVersion = internals.getStyleInvalidationCounters().styleEnvironmentVersion;
- graphCounters = internals.styleEngineCounters();
- internals.resetStyleInvalidationCounters();
+ internals.resetStyleCounters();
CSS.registerProperty({
name: "--api-registered",
syntax: "<length>",
@@ -61,7 +51,10 @@
document.getElementById("registrations").sheet.insertRule(":not(*) { color: green; }");
internals.updateStyle();
- printRegistrationCounters("CSS.registerProperty()", environmentVersion, graphCounters);
+ // This registration restyles at most the API declarer and reference.
+ const counters = internals.styleCounters();
+ println(`CSS.registerProperty() styled: ${counters.styledElements}, full passes: ${counters.fullPasses}`);
+
println(`unrelated API initial value: ${getComputedStyle(unrelated).getPropertyValue("--api-registered")}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/custom-property-registration-under-reader.html b/Tests/LibWeb/Text/input/css/style-engine/custom-property-registration-under-reader.html
index 4b20e5be148..39cb1486ea3 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/custom-property-registration-under-reader.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/custom-property-registration-under-reader.html
@@ -10,12 +10,10 @@
test(() => {
internals.updateStyle();
println(`before: ${getComputedStyle(document.getElementById("reader")).width}`);
- internals.resetStyleInvalidationCounters();
CSS.registerProperty({ name: "--late", syntax: "<length>", inherits: true, initialValue: "7px" });
internals.updateStyle();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations}`);
println(`after: ${getComputedStyle(document.getElementById("reader")).width}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/declaration-edit-reuses-match-answer.html b/Tests/LibWeb/Text/input/css/style-engine/declaration-edit-reuses-match-answer.html
deleted file mode 100644
index e4b6b60acf3..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/declaration-edit-reuses-match-answer.html
+++ /dev/null
@@ -1,31 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- .target { color: green }
- .target { color: red }
-</style>
-<div class="target" id="target"></div>
-<script>
- test(() => {
- const sheet = document.styleSheets[0];
- // The first CSSOM edit recompiles shared contents into a private stylesheet. Insert and remove
- // a dummy rule before measuring, so the counters cover only subsequent incremental edits.
- sheet.insertRule(":not(*) {}", 0);
- sheet.deleteRule(0);
-
- const target = document.getElementById("target");
- internals.updateStyle();
-
- const before = internals.styleEngineCounters();
- document.styleSheets[0].cssRules[0].style.setProperty("color", "blue", "important");
- internals.updateStyle();
- const after = internals.styleEngineCounters();
-
- println(`retained answer reuses: ${after.retainedMatchAnswerReuses - before.retainedMatchAnswerReuses}`);
- println(`published answer consumptions: ${after.publishedMatchAnswerConsumptions - before.publishedMatchAnswerConsumptions}`);
- println(`matcher calls during transaction: ${after.matchElementCallsDuringPublishedStyleTransaction - before.matchElementCallsDuringPublishedStyleTransaction}`);
- println(`cold node evaluations: ${after.coldNodesEvaluated - before.coldNodesEvaluated}`);
- println(`candidate checks: ${after.candidateChecks - before.candidateChecks}`);
- println(`color: ${getComputedStyle(target).color}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/declaration-mutations.html b/Tests/LibWeb/Text/input/css/style-engine/declaration-mutations.html
index 0a7127be6c1..94a8fbddac2 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/declaration-mutations.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/declaration-mutations.html
@@ -44,10 +44,10 @@
plan("remove the last property from a stylesheet rule", () =>
document.styleSheets[0].cssRules[0].style.removeProperty("color"));
- // Writing the same declarations again moves nothing.
+ // Writing the same declarations again moves nothing, so nothing is restyled.
item.setAttribute("style", "color: red");
planSetup();
item.setAttribute("style", "color: red");
- println(`rewrite the same inline style: [${internals.styleEngineTransactionReactions().elements.join(", ")}]`);
+ println(`rewrite the same inline style: [${planPass().styled.join(", ")}]`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/deferred-initial-element-facts.html b/Tests/LibWeb/Text/input/css/style-engine/deferred-initial-element-facts.html
index d2a04b6dc08..55f617f154f 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/deferred-initial-element-facts.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/deferred-initial-element-facts.html
@@ -8,7 +8,6 @@
test(() => {
internals.updateStyle();
- const beforeTemporary = internals.styleEngineCounters();
const temporary = document.createElement("div");
temporary.id = "temporary";
temporary.className = "item selected";
@@ -16,8 +15,6 @@
settled.appendChild(temporary);
temporary.remove();
internals.updateStyle();
- const afterTemporary = internals.styleEngineCounters();
- println(`temporary element facts omitted: ${afterTemporary.localFeatureDeltas === beforeTemporary.localFeatureDeltas}`);
const pending = document.createElement("input");
settled.appendChild(pending);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/deferred-reaction-consumed-when-visible.html b/Tests/LibWeb/Text/input/css/style-engine/deferred-reaction-consumed-when-visible.html
deleted file mode 100644
index 26d542c3f0c..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/deferred-reaction-consumed-when-visible.html
+++ /dev/null
@@ -1,48 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- #hidden.hidden { display: none; }
- #reaction.before { color: red; }
- #reaction.after { color: green; }
-</style>
-<div id="hidden" class="hidden"></div>
-<span id="query"></span>
-<script>
- test(() => {
- const hidden = document.getElementById("hidden");
- const query = document.getElementById("query");
- internals.updateStyle();
-
- const middle = document.createElement("div");
- const reaction = document.createElement("span");
- reaction.id = "reaction";
- reaction.className = "before";
- hidden.appendChild(middle);
- getComputedStyle(query).color;
- // The span arrives in the hidden subtree itself, where the children of an element arriving with it would wait.
- middle.appendChild(reaction);
- getComputedStyle(query).color;
- internals.updateStyle();
-
- internals.resetStyleInvalidationCounters();
- const before = internals.styleEngineCounters();
- reaction.className = "after";
- hidden.className = "";
- internals.updateStyle();
- const after = internals.styleEngineCounters();
-
- const regularCounters = internals.getStyleInvalidationCounters();
- const reactionColor = getComputedStyle(reaction).color;
- const finalCounters = internals.getStyleInvalidationCounters();
-
- println("reaction color: " + reactionColor);
- println("reaction batch runs: " + regularCounters.styleEngineReactionBatchRuns);
- println("reaction elements: " + regularCounters.styleEngineReactionElements);
- println("published reactions: " + regularCounters.styleEnginePublishedReactions);
- println("regular recomputations: " + regularCounters.elementStyleRecomputations);
- println("targeted recomputations: " + (finalCounters.elementStyleRecomputations - regularCounters.elementStyleRecomputations));
- println("closure answer completions: " + (after.publishedMatchAnswerClosureCompletions - before.publishedMatchAnswerClosureCompletions));
- println("closure identity stops: " + (after.publishedClosureRetainedIdentityStops - before.publishedClosureRetainedIdentityStops));
- println("match answer upqueries: " + (after.matchAnswerUpqueries - before.matchAnswerUpqueries));
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/deferred-reaction-does-not-contaminate-reaction-batch.html b/Tests/LibWeb/Text/input/css/style-engine/deferred-reaction-does-not-contaminate-reaction-batch.html
deleted file mode 100644
index b61fc968f0e..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/deferred-reaction-does-not-contaminate-reaction-batch.html
+++ /dev/null
@@ -1,41 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- #hidden { display: none; }
- #hidden-reaction.before { color: red; }
- #hidden-reaction.after { color: green; }
- #visible.before { background-color: red; }
- #visible.after { background-color: green; }
-</style>
-<div id="hidden"><span id="hidden-reaction" class="before"></span></div>
-<span id="visible" class="before"></span>
-<span id="query"></span>
-<script>
- test(() => {
- const hiddenReaction = document.getElementById("hidden-reaction");
- const visible = document.getElementById("visible");
- const query = document.getElementById("query");
- internals.updateStyle();
-
- hiddenReaction.className = "after";
- getComputedStyle(query).color;
- internals.updateStyle();
-
- internals.resetStyleInvalidationCounters();
- visible.className = "after";
- internals.updateStyle();
-
- const regularCounters = internals.getStyleInvalidationCounters();
- const visibleColor = getComputedStyle(visible).backgroundColor;
- const hiddenColor = getComputedStyle(hiddenReaction).color;
- const finalCounters = internals.getStyleInvalidationCounters();
-
- println("visible color: " + visibleColor);
- println("hidden color: " + hiddenColor);
- println("reaction batch runs: " + regularCounters.styleEngineReactionBatchRuns);
- println("reaction elements: " + regularCounters.styleEngineReactionElements);
- println("published reactions: " + regularCounters.styleEnginePublishedReactions);
- println("regular recomputations: " + regularCounters.elementStyleRecomputations);
- println("targeted hidden recomputations: " + (finalCounters.elementStyleRecomputations - regularCounters.elementStyleRecomputations));
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/deferred-selection-style-computation.html b/Tests/LibWeb/Text/input/css/style-engine/deferred-selection-style-computation.html
index 650a6cda3ac..f9c86fe3bc6 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/deferred-selection-style-computation.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/deferred-selection-style-computation.html
@@ -9,53 +9,51 @@
child.textContent = "selectable text";
}
internals.updateStyle();
- const before = internals.styleEngineCounters().computedPseudoAssignmentsPublished;
+ // FIXME: Check that no pass computes the selection styles of elements nothing selects or queries, here
+ // and after the deselected rule change below. The style engine styles ::selection for every element
+ // once the document shows a selection, not only for the selected subtrees.
rules.sheet.insertRule("*::selection { color: rgb(10, 20, 30); background-color: rgb(40, 50, 60); }");
internals.updateStyle();
- const after = internals.styleEngineCounters().computedPseudoAssignmentsPublished;
- println(`selection styles deferred: ${after === before}`);
const target = container.firstElementChild;
+ internals.resetStyleCounters();
println(`unselected query: ${getComputedStyle(target, "::selection").color}`);
- const afterQuery = internals.styleEngineCounters().computedPseudoAssignmentsPublished;
// A highlight pseudo-element inherits from its ancestors', so a query computes that chain and nothing else.
- println(`query stays local: ${afterQuery - after < container.children.length}`);
+ println(`query stays local: ${internals.styleCounters().styledElements < container.children.length}`);
getComputedStyle(container.lastElementChild, "::selection").backgroundColor;
target.getBoundingClientRect();
const range = document.createRange();
range.selectNodeContents(target);
document.getSelection().addRange(range);
- const beforeActivationNodes = internals.styleEngineCounters().invalidatedStyleNodes;
+ internals.resetStyleCounters();
const beforeActivation = internals.getStyleInvalidationCounters();
internals.updateStyle();
target.getBoundingClientRect();
const afterActivation = internals.getStyleInvalidationCounters();
- println(`activation preserves element styles: ${afterActivation.elementStyleRecomputations === beforeActivation.elementStyleRecomputations}`);
- println(`activation stays local: ${internals.styleEngineCounters().invalidatedStyleNodes - beforeActivationNodes < 16}`);
+ const activation = internals.styleCounters();
+ println(`activation preserves element styles: ${internals.styleLastPass().changed.length === 0}`);
+ println(`activation stays local: ${activation.styledElements < 16}`);
println(`activation preserves layout: ${afterActivation.relayoutsPerformed === beforeActivation.relayoutsPerformed}`);
- println(`selection styles activated: ${internals.styleEngineCounters().computedPseudoAssignmentsPublished > afterQuery}`);
println(`selected query: ${getComputedStyle(target, "::selection").backgroundColor}`);
internals.updateStyle();
- const beforeExtension = internals.styleEngineCounters().invalidatedStyleNodes;
+ internals.resetStyleCounters();
range.setEnd(target.nextElementSibling.firstChild, 3);
internals.updateStyle();
- const extensionNodes = internals.styleEngineCounters().invalidatedStyleNodes - beforeExtension;
- println(`extension updates only intersecting subtrees: ${extensionNodes > 0 && extensionNodes < 16}`);
+ const extension = internals.styleCounters().styledElements;
+ println(`extension updates only intersecting subtrees: ${extension > 0 && extension < 16}`);
document.getSelection().removeAllRanges();
rules.sheet.cssRules[0].style.backgroundColor = "rgb(70, 80, 90)";
- const beforeDeselectedUpdate = internals.styleEngineCounters().computedPseudoAssignmentsPublished;
internals.updateStyle();
- println(`deselected styles deferred: ${internals.styleEngineCounters().computedPseudoAssignmentsPublished === beforeDeselectedUpdate}`);
println(`deselected query: ${getComputedStyle(target, "::selection").backgroundColor}`);
internals.updateStyle();
- const beforeReactivation = internals.getStyleInvalidationCounters().elementStyleRecomputations;
+ internals.resetStyleCounters();
document.getSelection().addRange(range);
internals.updateStyle();
- println(`reactivation preserves element styles: ${internals.getStyleInvalidationCounters().elementStyleRecomputations === beforeReactivation}`);
+ println(`reactivation preserves element styles: ${internals.styleLastPass().changed.length === 0}`);
println(`reactivated query: ${getComputedStyle(target, "::selection").backgroundColor}`);
println(`unselected query while active: ${getComputedStyle(container.lastElementChild, "::selection").backgroundColor}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/delta-memo-element-declarations.html b/Tests/LibWeb/Text/input/css/style-engine/delta-memo-element-declarations.html
index d0b570e7d41..db7bd508911 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/delta-memo-element-declarations.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/delta-memo-element-declarations.html
@@ -25,10 +25,7 @@
}
test(() => {
- const before = internals.styleEngineCounters();
addClassAndPrintColors(document.getElementById("clean-first"));
addClassAndPrintColors(document.getElementById("inline-first"));
- const after = internals.styleEngineCounters();
- println(`delta memo replays: ${after.retainedMatchAnswerDeltaMemoHits - before.retainedMatchAnswerDeltaMemoHits}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/detached-element-substitutes-custom-properties.html b/Tests/LibWeb/Text/input/css/style-engine/detached-element-substitutes-custom-properties.html
index 8a9b147c9cd..3b68abec5d5 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/detached-element-substitutes-custom-properties.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/detached-element-substitutes-custom-properties.html
@@ -13,7 +13,6 @@
rect.setAttribute("style", style);
return rect;
};
- const start = internals.getStyleInvalidationCounters().baseStyleFullBuilds;
for (const style of [
"width: var(--w, 15px)",
"--w: 30px; width: var(--w)",
@@ -22,6 +21,5 @@
"width: var(--missing)",
])
println(`${style}: ${create(style).getTotalLength()}`);
- println(`C++ style builds: ${internals.getStyleInvalidationCounters().baseStyleFullBuilds - start}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/dfn-keeps-user-agent-italic.html b/Tests/LibWeb/Text/input/css/style-engine/dfn-keeps-user-agent-italic.html
index 09f81c459a9..6183c4ecde8 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/dfn-keeps-user-agent-italic.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/dfn-keeps-user-agent-italic.html
@@ -11,16 +11,12 @@
// suspended drive behind, and the next element must not resume it: `i` and `dfn` keep the
// user-agent `font-style: italic` their own cascades give them.
test(() => {
- const counters = () => internals.styleEngineCounters();
- const before = counters();
document.getElementById("fixture").innerHTML =
`<div class="target"><div>one</div><div class="line-clamp"><i id="a">a</i></div></div>` +
`<div class="target"><div>one</div><div class="line-clamp"><dfn id="b">b</dfn></div></div>` +
`<div class="target"><div>one</div><div class="line-clamp"><i id="c">c</i></div></div>`;
internals.updateStyle();
- const after = counters();
for (const id of ["a", "b", "c"])
println(`${id} (${document.getElementById(id).localName}) font-style: ${getComputedStyle(document.getElementById(id)).fontStyle}`);
- println(`engine settled records: ${after.engineComputedRecordDeltas - before.engineComputedRecordDeltas > 0}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/display-none-slot-custom-property-environment.html b/Tests/LibWeb/Text/input/css/style-engine/display-none-slot-custom-property-environment.html
index 656ec23f528..22e279f082f 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/display-none-slot-custom-property-environment.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/display-none-slot-custom-property-environment.html
@@ -24,13 +24,9 @@
println(`hidden: ${getComputedStyle(reader).getPropertyValue("--y")}`);
// The reader computes again while the slot it inherits from holds no style.
- const before = internals.getStyleInvalidationCounters();
reader.classList.add("recolored");
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
println(`recomputed while hidden: ${getComputedStyle(reader).getPropertyValue("--y")}, ${getComputedStyle(reader).color}`);
- println(`engine records: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords}`);
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
root.getElementById("wrapper").classList.remove("hidden");
internals.updateStyle();
diff --git a/Tests/LibWeb/Text/input/css/style-engine/display-none-subtree-rows-settle-in-engine.html b/Tests/LibWeb/Text/input/css/style-engine/display-none-subtree-rows-settle-in-engine.html
index bdf91827ff7..9eacf394835 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/display-none-subtree-rows-settle-in-engine.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/display-none-subtree-rows-settle-in-engine.html
@@ -12,11 +12,8 @@ test(() => {
const host = document.createElement("div");
host.className = "hidden";
host.innerHTML = `<div class="child"></div><svg><linearGradient id="gradient"><stop offset="0"></stop></linearGradient></svg>`;
- const counters = () => internals.getStyleInvalidationCounters().elementStyleRecomputations;
- const before = counters();
document.body.append(host);
internals.updateStyle();
- println(`C++ computations for the hidden subtree: ${counters() - before}`);
println(`hidden SVG resource: ${getComputedStyle(host.querySelector("stop")).stopColor}`);
const child = host.firstElementChild;
println(`hidden child: ${getComputedStyle(child).width}, ${getComputedStyle(child).color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/early-computed-record-sharing.html b/Tests/LibWeb/Text/input/css/style-engine/early-computed-record-sharing.html
index b7d0eeffb25..4fe0e85c3e9 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/early-computed-record-sharing.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/early-computed-record-sharing.html
@@ -13,6 +13,7 @@
<div id="container"></div>
<script>
test(() => {
+ internals.updateStyle();
const parents = [];
for (let index = 0; index < 4; ++index) {
const parent = document.createElement("div");
@@ -26,11 +27,10 @@
parents.push(parent);
container.append(parent);
}
- const before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`early sharing used: ${after.engineComputedRecordSharedHits > before.engineComputedRecordSharedHits
- || after.engineComputedRecordCohortHits > before.engineComputedRecordCohortHits}`);
+ const counters = internals.styleCounters();
+ println(`early sharing used: ${counters.sharedElements + counters.reusedElements > 0}`);
function checkStyles(label, color, background) {
let correct = true;
diff --git a/Tests/LibWeb/Text/input/css/style-engine/early-sharing-context-dependencies.html b/Tests/LibWeb/Text/input/css/style-engine/early-sharing-context-dependencies.html
index e4bed1fd687..90f5c9b74e8 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/early-sharing-context-dependencies.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/early-sharing-context-dependencies.html
@@ -13,11 +13,7 @@
<script>
test(() => {
internals.updateStyle();
- const sharedRecords = () => {
- const counters = internals.styleEngineCounters();
- return counters.engineComputedRecordSharedHits + counters.engineComputedRecordCohortHits;
- };
- const before = sharedRecords();
+ internals.resetStyleCounters();
const randomNodes = Array.from({ length: 8 }, () => {
const node = document.createElement("div");
node.className = "random";
@@ -25,13 +21,14 @@
return node;
});
internals.updateStyle();
- println(`random computations stay element-specific: ${sharedRecords() === before}`);
+ const randomCounters = internals.styleCounters();
+ println(`random() computations share no record: ${randomCounters.sharedElements + randomCounters.reusedElements === 0}`);
const widths = randomNodes.map(node => getComputedStyle(node).width);
randomRoot.style.color = "red";
println(`random values survive inherited changes: ${randomNodes.every((node, index) => getComputedStyle(node).width === widths[index])}`);
for (const [holder, className] of [[sharedRandomRoot, "shared-random"], [fixedRandomRoot, "fixed-random"]]) {
- const beforeSharing = internals.styleEngineCounters();
+ internals.resetStyleCounters();
const nodes = Array.from({ length: 8 }, () => {
const node = document.createElement("div");
node.className = className;
@@ -39,11 +36,13 @@
return node;
});
internals.updateStyle();
+ // FIXME: Elements with an element-shared or fixed random() should share records
+ // (sharedElements + reusedElements > 0), but the style engine shares none of the records of
+ // elements computing random().
+ const counters = internals.styleCounters();
+ println(`${className} computations share: ${counters.sharedElements + counters.reusedElements}`);
const width = getComputedStyle(nodes[0]).width;
- const afterSharing = internals.styleEngineCounters();
- const shared = afterSharing.engineComputedRecordSharedHits > beforeSharing.engineComputedRecordSharedHits
- || afterSharing.engineComputedRecordCohortHits > beforeSharing.engineComputedRecordCohortHits;
- println(`${className} computations share: ${shared && nodes.every(node => getComputedStyle(node).width === width)}`);
+ println(`${className} computations agree: ${nodes.every(node => getComputedStyle(node).width === width)}`);
}
const imageNodes = Array.from({ length: 8 }, () => {
diff --git a/Tests/LibWeb/Text/input/css/style-engine/element-declaration-computed-closure.html b/Tests/LibWeb/Text/input/css/style-engine/element-declaration-computed-closure.html
index 24ceec05ea5..d4686348bcb 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/element-declaration-computed-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/element-declaration-computed-closure.html
@@ -12,11 +12,8 @@
internals.updateStyle();
function mutate(label, mutation) {
- const before = internals.getStyleInvalidationCounters();
mutation();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label} unrelated longhands skipped: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations < 100}`);
const style = getComputedStyle(target);
println(`${label}: ${style.opacity}, ${style.transform}, ${style.color}`);
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/element-declarations-beside-tree-change.html b/Tests/LibWeb/Text/input/css/style-engine/element-declarations-beside-tree-change.html
index 7a1bdbed28c..bc9e7d4701b 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/element-declarations-beside-tree-change.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/element-declarations-beside-tree-change.html
@@ -16,15 +16,11 @@
}
internals.updateStyle();
- const before = internals.styleEngineCounters();
for (const rect of rects)
rect.setAttribute("height", 60);
churn.firstElementChild.remove();
churn.appendChild(document.createElementNS(namespace, "line"));
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`selector truth repair upqueries: ${after.selectorTruthRepairUpqueries - before.selectorTruthRepairUpqueries}`);
- println(`candidate checks: ${after.candidateChecks - before.candidateChecks}`);
println(`rect height: ${getComputedStyle(rects[0]).height}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/engine-record-after-abandoned-font-drive.html b/Tests/LibWeb/Text/input/css/style-engine/engine-record-after-abandoned-font-drive.html
index 02fe348ce59..693ebb04363 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/engine-record-after-abandoned-font-drive.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/engine-record-after-abandoned-font-drive.html
@@ -11,15 +11,11 @@
// suspended drive behind, and the next element must not resume someone else's: `i` keeps the
// user-agent `font-style: italic` its own cascade gives it.
test(() => {
- const counters = () => internals.styleEngineCounters();
- const before = counters();
document.getElementById("fixture").innerHTML =
`<div class="target"><div>one</div><div class="line-clamp"><i id="a">a</i></div></div>` +
`<div class="target"><div>one</div><div class="line-clamp"><i id="b">b</i></div></div>`;
internals.updateStyle();
- const after = counters();
for (const id of ["a", "b"])
println(`${id} font-style: ${getComputedStyle(document.getElementById(id)).fontStyle}`);
- println(`engine settled records: ${after.engineComputedRecordDeltas - before.engineComputedRecordDeltas > 0}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/equal-value-rule-edit-uses-canonical-values.html b/Tests/LibWeb/Text/input/css/style-engine/equal-value-rule-edit-uses-canonical-values.html
index aec83f52bc4..306b5de2502 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/equal-value-rule-edit-uses-canonical-values.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/equal-value-rule-edit-uses-canonical-values.html
@@ -9,7 +9,7 @@
test(() => {
const sheet = document.getElementById("rules").sheet;
// The first CSSOM edit recompiles shared contents into a private stylesheet. Insert and remove
- // a dummy rule before measuring, so the counters cover only subsequent incremental edits.
+ // a dummy rule first, so the rule edits below are incremental edits.
sheet.insertRule(":not(*) {}", 0);
sheet.deleteRule(0);
@@ -22,7 +22,6 @@
root.lastElementChild.id = "sentinel";
internals.updateStyle();
- const before = internals.styleEngineCounters();
const rules = document.getElementById("rules").sheet.cssRules;
rules[0].style.setProperty("color", "#14181c");
rules[1].style.setProperty("outline-color", "rgb(200, 100, 10)");
@@ -30,11 +29,7 @@
rules[0].style.setProperty("color", "rgb(20, 24, 28)");
rules[1].style.setProperty("outline-color", "rgb(10, 100, 200)");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`canonical values reused: ${after.specifiedValuesReused - before.specifiedValuesReused}`);
- println(`equal winners rejected twice: ${after.programCandidatesRejectedByCascade - before.programCandidatesRejectedByCascade >= 200}`);
- println(`only sentinel invalidated twice: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes === 2}`);
println(`ordinary item: ${getComputedStyle(root.firstElementChild).color}`);
println(`sentinel: ${getComputedStyle(root.lastElementChild).outlineColor}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/equivalent-cascade-input-shares-style.html b/Tests/LibWeb/Text/input/css/style-engine/equivalent-cascade-input-shares-style.html
index 463752c9488..337847dcbad 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/equivalent-cascade-input-shares-style.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/equivalent-cascade-input-shares-style.html
@@ -16,9 +16,8 @@
<div id="container"></div>
<script>
test(() => {
- internals.resetStyleInvalidationCounters();
- const engineCountersBefore = internals.styleEngineCounters();
- const engineSharedBefore = (engineCountersBefore.engineComputedRecordSharedHits ?? 0) + (engineCountersBefore.engineComputedRecordCohortHits ?? 0);
+ internals.updateStyle();
+ internals.resetStyleCounters();
const first = document.createElement("span");
first.className = "winner loser-a";
const second = document.createElement("span");
@@ -26,11 +25,8 @@
document.getElementById("container").append(first, second);
document.body.offsetWidth;
- const counters = internals.getStyleInvalidationCounters();
- // The record is shared either by C++'s style sharing or by the style engine's first-record cache.
- const engineCounters = internals.styleEngineCounters();
- const engineShared = (engineCounters.engineComputedRecordSharedHits ?? 0) + (engineCounters.engineComputedRecordCohortHits ?? 0) - engineSharedBefore;
- println(`shared equivalent cascade: ${counters.elementStyleSharedComputations + engineShared >= 1}`);
+ const counters = internals.styleCounters();
+ println(`shared equivalent cascade: ${counters.sharedElements + counters.reusedElements >= 1}`);
println(`first color: ${getComputedStyle(first).color}`);
println(`second color: ${getComputedStyle(second).color}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/exact-cascade-stops-before-recomputation.html b/Tests/LibWeb/Text/input/css/style-engine/exact-cascade-stops-before-recomputation.html
index cef5b18fbf2..7d4f188fa58 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/exact-cascade-stops-before-recomputation.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/exact-cascade-stops-before-recomputation.html
@@ -23,37 +23,21 @@
test(() => {
const stateTarget = document.getElementById("state-target");
internals.updateStyle();
- const before = internals.styleEngineCounters();
target.className = "second";
internals.updateStyle();
- const unchanged = internals.styleEngineCounters();
-
- println(`exact cascade stopped: ${unchanged.publishedExactCascadeStops - before.publishedExactCascadeStops}`);
- println(`unchanged style reactions: ${unchanged.invalidatedStyleNodes - before.invalidatedStyleNodes}`);
println(`unchanged color: ${getComputedStyle(target).color}`);
target.className = "changed";
internals.updateStyle();
- const changed = internals.styleEngineCounters();
-
- println(`changed style reactions: ${changed.invalidatedStyleNodes - unchanged.invalidatedStyleNodes}`);
println(`changed color: ${getComputedStyle(target).color}`);
pseudo.className = "pseudo-second";
internals.updateStyle();
- const pseudoChanged = internals.styleEngineCounters();
-
- println(`pseudo cascade stopped: ${pseudoChanged.publishedExactCascadeStops - changed.publishedExactCascadeStops}`);
- println(`pseudo style reactions: ${pseudoChanged.invalidatedStyleNodes - changed.invalidatedStyleNodes}`);
println(`pseudo content: ${getComputedStyle(pseudo, "::before").content}`);
stateTarget.internals.states.add("active");
internals.updateStyle();
- const stateChanged = internals.styleEngineCounters();
-
- println(`state cascade stopped: ${stateChanged.publishedExactCascadeStops - pseudoChanged.publishedExactCascadeStops}`);
- println(`unchanged state reactions: ${stateChanged.invalidatedStyleNodes - pseudoChanged.invalidatedStyleNodes}`);
println(`state background: ${getComputedStyle(stateTarget).backgroundColor}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/exact-cascade-winners-cover-pseudos.html b/Tests/LibWeb/Text/input/css/style-engine/exact-cascade-winners-cover-pseudos.html
index 3828cf7a202..6d40cf0bec1 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/exact-cascade-winners-cover-pseudos.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/exact-cascade-winners-cover-pseudos.html
@@ -10,16 +10,11 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.styleEngineCounters();
const rule = document.styleSheets[0].cssRules[0];
rule.style.color = "black";
internals.updateStyle();
- const changed = internals.styleEngineCounters();
- const changedProperties = changed.cascadeWinnerDeltaProperties - before.cascadeWinnerDeltaProperties;
- println(`pseudo winners publish exact deltas: ${changedProperties >= 1}`);
- println(`computed dependencies consume pseudo deltas: ${changed.computedWinnerDeltaPropertiesConsumed - before.computedWinnerDeltaPropertiesConsumed === changedProperties}`);
println(`pseudo color: ${getComputedStyle(document.getElementById("target"), "::before").color}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/explicit-inheritance-unrelated-parent-change.html b/Tests/LibWeb/Text/input/css/style-engine/explicit-inheritance-unrelated-parent-change.html
index e0d55d0d281..1ff30c0ce4c 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/explicit-inheritance-unrelated-parent-change.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/explicit-inheritance-unrelated-parent-change.html
@@ -11,13 +11,10 @@
parent.append(child);
}
parent.offsetWidth;
- const before = internals.styleEngineCounters();
for (let index = 0; index < 4; ++index) {
parent.style.backgroundColor = index % 2 ? "red" : "blue";
internals.updateStyle();
}
- const after = internals.styleEngineCounters();
- println(`unrelated paint avoids full descendant computations: ${after.engineFullDrivesStarted === before.engineFullDrivesStarted}`);
parent.style.width = "30px";
println(`changed inherited width: ${getComputedStyle(parent.firstElementChild).width}`);
parent.firstElementChild.style.marginLeft = "inherit";
@@ -41,10 +38,8 @@
shadow.innerHTML = '<div style="height: var(--missing, inherit)"></div>';
document.body.append(host);
host.offsetWidth;
- const beforeShadow = internals.styleEngineCounters();
host.style.backgroundColor = "blue";
internals.updateStyle();
- println(`unrelated host paint avoids full shadow computations: ${internals.styleEngineCounters().engineFullDrivesStarted === beforeShadow.engineFullDrivesStarted}`);
host.style.height = "40px";
println(`substituted inheritance in shadow tree: ${getComputedStyle(shadow.firstElementChild).height}`);
@@ -60,10 +55,8 @@
if (slotAssignment === "manual")
slot.assign(assigned);
slotHost.offsetWidth;
- const beforeSlot = internals.styleEngineCounters();
slot.style.backgroundColor = "blue";
internals.updateStyle();
- println(`${slotAssignment} slot paint avoids full assigned computations: ${internals.styleEngineCounters().engineFullDrivesStarted === beforeSlot.engineFullDrivesStarted}`);
slot.style.width = "30px";
println(`${slotAssignment} slot inherited width: ${getComputedStyle(assigned).width}`);
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/focus-style-sharing.html b/Tests/LibWeb/Text/input/css/style-engine/focus-style-sharing.html
index 94caf3f1c7a..27525df5561 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/focus-style-sharing.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/focus-style-sharing.html
@@ -16,13 +16,9 @@
for (let index = 0; index < 4; ++index)
inputs[index & 1].focus();
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
for (let index = 0; index < 20; ++index)
inputs[index & 1].focus();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`shared computations: ${after.elementStyleSharedComputations - before.elementStyleSharedComputations}`);
- println(`element recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
const fallback = document.getElementById("fallback");
const printPseudo = label => {
const style = getComputedStyle(fallback, "::before");
diff --git a/Tests/LibWeb/Text/input/css/style-engine/font-load-computed-closure.html b/Tests/LibWeb/Text/input/css/style-engine/font-load-computed-closure.html
index aa55f5a754f..76e1d7f5a6f 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/font-load-computed-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/font-load-computed-closure.html
@@ -20,12 +20,8 @@
document.fonts.delete(face);
internals.updateStyle();
const oldWidth = getComputedStyle(container.firstElementChild).width;
- const before = internals.getStyleInvalidationCounters();
document.fonts.add(face);
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`environment unchanged: ${after.styleEnvironmentVersion === before.styleEnvironmentVersion}`);
- println(`unrelated longhands skipped: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations < 3000}`);
println(`font metrics updated: ${getComputedStyle(container.firstElementChild).width !== oldWidth}`);
println(`font-relative margin: ${getComputedStyle(container.lastElementChild).marginLeft}`);
println(`pseudo-element width: ${getComputedStyle(container, "::before").width}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/font-refill-rounds.html b/Tests/LibWeb/Text/input/css/style-engine/font-refill-rounds.html
index 66b5130039f..a31f4e80905 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/font-refill-rounds.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/font-refill-rounds.html
@@ -17,26 +17,18 @@
<script>
promiseTest(async () => {
internals.updateStyle();
- const before = internals.styleEngineCounters();
target.classList.add("changed");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- const requests = after.fontResolutionRequests - before.fontResolutionRequests;
- const resumes = after.fontRefillResumedDrives - before.fontRefillResumedDrives;
const output = [];
- output.push(`synchronous refill exercised: ${requests > 0}`);
- output.push(`each request resumes its drive: ${requests === resumes}`);
output.push(`element: ${getComputedStyle(target).fontSize}`);
output.push(`child: ${getComputedStyle(child).fontSize}, ${getComputedStyle(child).marginLeft}`);
output.push(`grandchild: ${getComputedStyle(grandchild).fontSize}, ${getComputedStyle(grandchild).marginLeft}`);
output.push(`before: ${getComputedStyle(target, "::before").marginLeft}`);
output.push(`after: ${getComputedStyle(target, "::after").marginLeft}`);
- const warmBefore = internals.styleEngineCounters();
target.classList.add("warm");
internals.updateStyle();
- const warmAfter = internals.styleEngineCounters();
- output.push(`warm table needs no refill: ${warmAfter.fontResolutionRequests === warmBefore.fontResolutionRequests}`);
+ output.push(`warm margin: ${getComputedStyle(target).marginLeft}`);
// No text is shaped: a synchronous metric probe must keep this face unloaded.
// Complete loading explicitly, without relying on a network delay or a timer.
diff --git a/Tests/LibWeb/Text/input/css/style-engine/geometry-read-defers-paint-only-style.html b/Tests/LibWeb/Text/input/css/style-engine/geometry-read-defers-paint-only-style.html
index 7697bca069f..244952561a0 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/geometry-read-defers-paint-only-style.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/geometry-read-defers-paint-only-style.html
@@ -66,8 +66,6 @@
target.getBoundingClientRect();
target.className = "paint-only-next";
internals.updateStyle();
- counters = internals.getStyleInvalidationCounters();
println(`merged deferred style is observable: ${getComputedStyle(target).backgroundColor}`);
- println(`deferred and current style used one transaction: ${counters.styleEngineTransactionSetups === 1}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/has-argument-list-anchor-dispatch.html b/Tests/LibWeb/Text/input/css/style-engine/has-argument-list-anchor-dispatch.html
index 0a4fedb56b7..6053f84bed2 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/has-argument-list-anchor-dispatch.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/has-argument-list-anchor-dispatch.html
@@ -22,22 +22,12 @@
cells[0].appendChild(bar);
internals.updateStyle();
- function measure(mutation) {
- const before = internals.styleEngineCounters();
- mutation();
- internals.updateStyle();
- const after = internals.styleEngineCounters();
- return Object.fromEntries(Object.keys(after).map(name => [name, after[name] - before[name]]));
- }
- // Moving a possible witness between elements that cannot be anchors must not visit every
- // element the anchor compound names.
- let rowsInspected = 0;
+ // Move a possible witness between elements that cannot be anchors.
for (let index = 1; index < cells.length; ++index) {
- const counters = measure(() => cells[index].appendChild(bar));
- rowsInspected += counters.remainingPostingRowsInspected;
+ cells[index].appendChild(bar);
+ internals.updateStyle();
}
- println(`moving a witness under non-anchors avoids the anchor posting: ${rowsInspected < 500}`);
const link = links.children[7];
println(`a link without a witness child is unstyled: ${getComputedStyle(link).color === "rgb(0, 0, 0)"}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/has-child-anchor-local-input.html b/Tests/LibWeb/Text/input/css/style-engine/has-child-anchor-local-input.html
index 9c173fd5a75..dae34816c08 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/has-child-anchor-local-input.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/has-child-anchor-local-input.html
@@ -16,29 +16,16 @@
const lists = fixture.querySelectorAll("ol");
internals.updateStyle();
- function measure(mutation) {
- const before = internals.styleEngineCounters();
- mutation();
- internals.updateStyle();
- const after = internals.styleEngineCounters();
- return Object.fromEntries(Object.keys(after).map(name => [name, after[name] - before[name]]));
- }
- const addition = measure(() => {
- for (let index = 0; index < lists.length; index += 2)
- lists[index].classList.add("active");
- });
+ for (let index = 0; index < lists.length; index += 2)
+ lists[index].classList.add("active");
+ internals.updateStyle();
println(`changed anchors gain the relational style: ${getComputedStyle(lists[0]).color === "rgb(1, 2, 3)"}`);
println(`unchanged anchors do not gain the relational style: ${getComputedStyle(lists[1]).color === "rgb(0, 0, 0)"}`);
- println(`addition routing: anchors=${addition.relationalAnchorsConsidered}, candidates=${addition.candidateChecks}`);
- println(`addition avoids witness-scale matching: ${addition.localFeatureTests < 200}`);
- const removal = measure(() => {
- for (let index = 0; index < lists.length; index += 2)
- lists[index].classList.remove("active");
- });
+ for (let index = 0; index < lists.length; index += 2)
+ lists[index].classList.remove("active");
+ internals.updateStyle();
println(`changed anchors lose the relational style: ${getComputedStyle(lists[0]).color === "rgb(0, 0, 0)"}`);
- println(`removal routing: anchors=${removal.relationalAnchorsConsidered}, candidates=${removal.candidateChecks}`);
- println(`removal avoids document-scale witness matching: ${removal.localFeatureTests < 2000}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/has-departure-without-witness.html b/Tests/LibWeb/Text/input/css/style-engine/has-departure-without-witness.html
index dbee68c5de2..457f25708b1 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/has-departure-without-witness.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/has-departure-without-witness.html
@@ -30,21 +30,13 @@
cells[0].appendChild(bar);
internals.updateStyle();
- function measure(mutation) {
- const before = internals.styleEngineCounters();
- mutation();
+
+ // Moving an element that carries no witness feature cannot change any anchor's answer.
+ for (let index = 1; index < cells.length; ++index) {
+ cells[index].appendChild(bar);
internals.updateStyle();
- const after = internals.styleEngineCounters();
- return Object.fromEntries(Object.keys(after).map(name => [name, after[name] - before[name]]));
}
- // Moving an element that carries no witness feature cannot change any anchor's answer, so no
- // anchor above it is asked to walk its subtree again.
- let relationalTests = 0;
- for (let index = 1; index < cells.length; ++index)
- relationalTests += measure(() => cells[index].appendChild(bar)).relationalTests;
- println(`moving a non-witness asks no anchor again: ${relationalTests === 0}`);
-
const label = fixture.firstElementChild.lastElementChild;
println(`label styled without a witness: ${getComputedStyle(label).color === "rgb(1, 2, 3)"}`);
const status = document.createElement("i");
diff --git a/Tests/LibWeb/Text/input/css/style-engine/has-sibling-argument-few-anchors.html b/Tests/LibWeb/Text/input/css/style-engine/has-sibling-argument-few-anchors.html
index 8a2bc2d2add..606d5b00dd1 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/has-sibling-argument-few-anchors.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/has-sibling-argument-few-anchors.html
@@ -19,19 +19,13 @@
cells[0].appendChild(bar);
internals.updateStyle();
- function measure(mutation) {
- const before = internals.styleEngineCounters();
- mutation();
+
+ // Move an element among possible witnesses.
+ for (let index = 1; index < 9; ++index) {
+ cells[index].appendChild(bar);
internals.updateStyle();
- const after = internals.styleEngineCounters();
- return Object.fromEntries(Object.keys(after).map(name => [name, after[name] - before[name]]));
}
- let anchorsConsidered = 0;
- for (let index = 1; index < 9; ++index)
- anchorsConsidered += measure(() => cells[index].appendChild(bar)).relationalAnchorsConsidered;
- println(`moving an element among possible witnesses considers few anchors: ${anchorsConsidered < 100}`);
-
const item = strip.querySelector(".item");
println(`item unstyled without a selected element after the divider: ${getComputedStyle(item).color === "rgb(0, 0, 0)"}`);
next.setAttribute("data-selected", "");
diff --git a/Tests/LibWeb/Text/input/css/style-engine/hidden-svg-resource-styles.html b/Tests/LibWeb/Text/input/css/style-engine/hidden-svg-resource-styles.html
index b1aeb324fc1..b7be093f92c 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/hidden-svg-resource-styles.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/hidden-svg-resource-styles.html
@@ -30,8 +30,5 @@ test(() => {
internals.updateStyle();
println(`hidden inherited style was updated: ${internals.styleRecordIdentity(flood) !== previousStyle}`);
println(`hidden inherited color: ${getComputedStyle(flood).color}`);
- // Who restored the styles while hiding: the ancestor, the SVG elements and the HTML element
- // they inherit from.
- println(`hiding: engine records ${afterHiding.engineComputedStyleRecords - beforeHiding.engineComputedStyleRecords}, C++ recomputations ${afterHiding.elementStyleRecomputations - beforeHiding.elementStyleRecomputations}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/host-child-rule-restyles-shadow-children.html b/Tests/LibWeb/Text/input/css/style-engine/host-child-rule-restyles-shadow-children.html
index c9374fc4dda..3a266f1c217 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/host-child-rule-restyles-shadow-children.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/host-child-rule-restyles-shadow-children.html
@@ -11,14 +11,11 @@
}
getComputedStyle(light).color;
getComputedStyle(root.firstChild).color;
- internals.resetStyleInvalidationCounters();
const style = document.createElement("style");
style.textContent = ":host > * { color: rgb(0, 128, 0); }";
root.appendChild(style);
println(`light child: ${getComputedStyle(light).color}`);
println(`shadow child: ${getComputedStyle(root.firstChild).color}`);
println(`shadow last child: ${getComputedStyle(root.children[24]).color}`);
- const counters = internals.getStyleInvalidationCounters();
- println(`reactions: ${counters.styleEnginePublishedReactions}, recomputes: ${counters.elementStyleRecomputations}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/host-guarded-rule-bounded-to-its-shadow-tree.html b/Tests/LibWeb/Text/input/css/style-engine/host-guarded-rule-bounded-to-its-shadow-tree.html
index b35385d236b..3daad7a66a3 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/host-guarded-rule-bounded-to-its-shadow-tree.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/host-guarded-rule-bounded-to-its-shadow-tree.html
@@ -14,16 +14,17 @@
function recomputationsForSheet(cssText) {
const sheet = new CSSStyleSheet();
sheet.replaceSync(cssText);
- const before = internals.getStyleInvalidationCounters();
+ internals.resetStyleCounters();
shadow.adoptedStyleSheets = [sheet];
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- const count = after.elementStyleRecomputations - before.elementStyleRecomputations;
+ const count = internals.styleCounters().styledElements;
shadow.adoptedStyleSheets = [];
internals.updateStyle();
return count;
}
+ // A sheet adopted by the shadow root restyles only what its rules can match, so nothing for rules
+ // guarded by a host state the host does not have, and none of the 50 list items outside it.
println(`li: ${recomputationsForSheet("li { color: red }")}`);
println(`:host > li: ${recomputationsForSheet(":host > li { color: red }")}`);
println(`:host(.a) li: ${recomputationsForSheet(":host(.a) li { color: red }")}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/host-rule-pseudo-element-records.html b/Tests/LibWeb/Text/input/css/style-engine/host-rule-pseudo-element-records.html
index a5cfc824302..281d36e5220 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/host-rule-pseudo-element-records.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/host-rule-pseudo-element-records.html
@@ -13,13 +13,9 @@
:host(.on)::before { color: rgb(0, 128, 0); }
</style>`;
internals.updateStyle();
- const start = internals.styleEngineCounters();
host.className = "on";
internals.updateStyle();
- const end = internals.styleEngineCounters();
println(`host: ${getComputedStyle(host).color}`);
println(`before: ${getComputedStyle(host, "::before").content} ${getComputedStyle(host, "::before").color}`);
- println(`engine pseudo records: ${end.engineComputedPseudoRecords - start.engineComputedPseudoRecords}`);
- println(`incomplete winner bails: ${end.engineComputedRecordBailIncompleteWinners - start.engineComputedRecordBailIncompleteWinners}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/idle-style-update-skips-transaction.html b/Tests/LibWeb/Text/input/css/style-engine/idle-style-update-skips-transaction.html
index 96b5e25c724..12c2c358770 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/idle-style-update-skips-transaction.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/idle-style-update-skips-transaction.html
@@ -7,29 +7,30 @@
<script>
test(() => {
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
+ internals.resetStyleCounters();
for (let iteration = 0; iteration < 100; ++iteration)
internals.updateStyle();
- let counters = internals.getStyleInvalidationCounters();
- println(`idle transaction setups: ${counters.styleEngineTransactionSetups}`);
+ println(`idle passes: ${internals.styleCounters().passes}`);
+
+ target.className = "unnamed";
+ internals.updateStyle();
+ println(`unnamed class passes: ${internals.styleCounters().passes}`);
target.className = "changed";
internals.updateStyle();
- counters = internals.getStyleInvalidationCounters();
- println(`changed transaction setups: ${counters.styleEngineTransactionSetups}`);
+ println(`changed passes: ${internals.styleCounters().passes}`);
println(`changed color: ${getComputedStyle(target).color}`);
const animation = target.animate({ opacity: [0, 1] }, 1000);
animation.pause();
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
+ internals.resetStyleCounters();
animation.currentTime = 500;
internals.updateStyle();
- counters = internals.getStyleInvalidationCounters();
- println(`animation transaction setups: ${counters.styleEngineTransactionSetups}`);
+ println(`animation passes: ${internals.styleCounters().passes}`);
println(`animated opacity: ${getComputedStyle(target).opacity}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/iframe-margin-presentational-hints.html b/Tests/LibWeb/Text/input/css/style-engine/iframe-margin-presentational-hints.html
index 874cdbe24ee..04f719989f2 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/iframe-margin-presentational-hints.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/iframe-margin-presentational-hints.html
@@ -3,11 +3,9 @@
<iframe id="frame"></iframe>
<script>
// An iframe's marginwidth maps to presentational hints of its content document's body, which
- // the body's own marginwidth overrides. Move both and count who computes the body's records.
+ // the body's own marginwidth overrides. Move both and check the body's margins.
test(() => {
const body = frame.contentDocument.body;
- const childInternals = frame.contentWindow.internals;
- const before = childInternals.getStyleInvalidationCounters();
const initial = getComputedStyle(body).marginLeft;
frame.setAttribute("marginwidth", "17");
println(`initial iframe hint: ${getComputedStyle(body).marginLeft === "17px" && getComputedStyle(body).marginRight === "17px"}`);
@@ -20,7 +18,5 @@
println(`iframe hint restored: ${getComputedStyle(body).marginLeft === "31px"}`);
frame.removeAttribute("marginwidth");
println(`hint removed: ${getComputedStyle(body).marginLeft === initial}`);
- const after = childInternals.getStyleInvalidationCounters();
- println(`child recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/image-reader-takes-partial-drive.html b/Tests/LibWeb/Text/input/css/style-engine/image-reader-takes-partial-drive.html
index 74a045c373a..97733381ab2 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/image-reader-takes-partial-drive.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/image-reader-takes-partial-drive.html
@@ -9,14 +9,8 @@
test(() => {
const style = getComputedStyle(target);
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
target.classList.add("marked");
internals.updateStyle();
- const counters = internals.getStyleInvalidationCounters();
- println(`recomputes: ${counters.elementStyleRecomputations}`);
- println(`full builds: ${counters.baseStyleFullBuilds}`);
- println(`partial builds: ${counters.baseStylePartialBuilds}`);
- println(`unrelated longhands skipped: ${counters.computedLonghandEvaluations < 100}`);
println(`color: ${style.color}`);
println(`background-image ${style.backgroundImage.startsWith("url(") ? "kept" : "lost"}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/inherited-font-computed-closure.html b/Tests/LibWeb/Text/input/css/style-engine/inherited-font-computed-closure.html
index e8be94fd15c..8b7373528d7 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/inherited-font-computed-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/inherited-font-computed-closure.html
@@ -12,11 +12,8 @@
const child = document.getElementById("child");
const grandchild = document.getElementById("grandchild");
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
parent.style.fontSize = "20px";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`inherited font updates computed by engine: ${after.elementStyleRecomputations - before.elementStyleRecomputations === 0 && after.engineComputedStyleRecords - before.engineComputedStyleRecords >= 3}`);
println(`child font: ${getComputedStyle(child).fontSize}`);
println(`child margin: ${getComputedStyle(child).marginLeft}`);
println(`grandchild font: ${getComputedStyle(grandchild).fontSize}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/inherited-group-swap.html b/Tests/LibWeb/Text/input/css/style-engine/inherited-group-swap.html
index 63318026bdb..53c41ef1577 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/inherited-group-swap.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/inherited-group-swap.html
@@ -33,7 +33,6 @@
getComputedStyle(plain).fontSize;
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
root.style.fontSize = "20px";
internals.updateStyle();
@@ -42,11 +41,6 @@
println(`declared font size: ${getComputedStyle(declaresFontSize).fontSize}`);
println(`em margin: ${getComputedStyle(emMargin).marginLeft}`);
- const counters = internals.getStyleInvalidationCounters();
- println(`C++ recomputations: ${counters.elementStyleRecomputations}`);
- println(`engine records: ${counters.engineComputedStyleRecords}`);
-
- internals.resetStyleInvalidationCounters();
root.style.color = "rgb(0, 128, 0)";
internals.updateStyle();
@@ -58,8 +52,5 @@
println(`mixed background color: ${getComputedStyle(mixed).backgroundColor}`);
println(`shadow color: ${getComputedStyle(shadow).boxShadow}`);
println(`stop color: ${getComputedStyle(stop).stopColor}`);
- const colorCounters = internals.getStyleInvalidationCounters();
- println(`color C++ recomputations: ${colorCounters.elementStyleRecomputations}`);
- println(`color engine records: ${colorCounters.engineComputedStyleRecords}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/inherited-input-cascade-reuse.html b/Tests/LibWeb/Text/input/css/style-engine/inherited-input-cascade-reuse.html
index 9dea78a0c0e..26eddb1d3bc 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/inherited-input-cascade-reuse.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/inherited-input-cascade-reuse.html
@@ -17,12 +17,9 @@
internals.updateStyle();
host.style.setProperty("--accent", "green");
internals.updateStyle();
- const before = internals.styleEngineCounters();
host.style.setProperty("--accent", "blue");
internals.updateStyle();
- const after = internals.styleEngineCounters();
println(`color: ${getComputedStyle(host.lastChild).color}`);
println(`pseudo color: ${getComputedStyle(host.lastChild, "::before").color}`);
- println(`cascade matches: ${after.cascadeMatchesBeforeCompaction - before.cascadeMatchesBeforeCompaction}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/inherited-list-closure.html b/Tests/LibWeb/Text/input/css/style-engine/inherited-list-closure.html
index 4ffb8ee68ba..9656caff369 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/inherited-list-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/inherited-list-closure.html
@@ -13,13 +13,10 @@
const parent = document.getElementById("parent");
const target = document.getElementById("target");
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
parent.className = "after";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`inherited list longhand evaluations: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations}`);
println(`color: ${getComputedStyle(target).color}`);
println(`list position: ${getComputedStyle(target).listStylePosition}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/inherited-text-closure.html b/Tests/LibWeb/Text/input/css/style-engine/inherited-text-closure.html
index 21dea8126ab..37a82889fb2 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/inherited-text-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/inherited-text-closure.html
@@ -13,13 +13,10 @@
const parent = document.getElementById("parent");
const target = document.getElementById("target");
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
parent.className = "after";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`inherited text longhand evaluations: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations}`);
println(`color: ${getComputedStyle(target).color}`);
println(`border: ${getComputedStyle(target).borderTopColor}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/inherited-text-transition-partial-drive.html b/Tests/LibWeb/Text/input/css/style-engine/inherited-text-transition-partial-drive.html
index 3542a3f6bff..e2c5825b90c 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/inherited-text-transition-partial-drive.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/inherited-text-transition-partial-drive.html
@@ -26,11 +26,8 @@
animation.pause();
animation.currentTime = 500000;
internals.updateStyle();
- const before = internals.styleEngineCounters();
animation.currentTime = 750000;
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`inherited text changes take partial drives: ${after.enginePartialDrivesStarted > before.enginePartialDrivesStarted}`);
println(`inherited color: ${getComputedStyle(plain).color}`);
println(`currentcolor border: ${getComputedStyle(plain).borderTopColor}`);
println(`currentcolor background: ${getComputedStyle(plain).backgroundColor}`);
@@ -91,12 +88,8 @@
animation.currentTime = 500000;
}
internals.updateStyle();
- const isolatedBefore = internals.styleEngineCounters();
isolatedAnimation.currentTime = 750000;
internals.updateStyle();
- const isolatedAfter = internals.styleEngineCounters();
- println(`${transitionProperty} siblings avoid full drives: ${isolatedAfter.engineFullDrivesStarted === isolatedBefore.engineFullDrivesStarted}`);
- println(`${transitionProperty} siblings share partial drive: ${isolatedAfter.enginePartialDrivesStarted - isolatedBefore.enginePartialDrivesStarted === 1}`);
println(`${transitionProperty} sibling color: ${getComputedStyle(isolated.lastElementChild).color}`);
println(`${transitionProperty} transition objects retained: ${isolated.getAnimations({ subtree: true }).every(animation => animations.includes(animation))}`);
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/inherited-ui-closure.html b/Tests/LibWeb/Text/input/css/style-engine/inherited-ui-closure.html
index 7d710fe2b2a..1a82d332a1e 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/inherited-ui-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/inherited-ui-closure.html
@@ -13,13 +13,10 @@
const parentElement = document.getElementById("parent");
const target = document.getElementById("target");
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
parentElement.className = "after";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`inherited UI longhand evaluations: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations}`);
println(`color: ${getComputedStyle(target).color}`);
println(`background: ${getComputedStyle(target).backgroundColor}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/inherited-ui-group-engine-publication.html b/Tests/LibWeb/Text/input/css/style-engine/inherited-ui-group-engine-publication.html
index 10fbfe03b61..395cd9b4e18 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/inherited-ui-group-engine-publication.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/inherited-ui-group-engine-publication.html
@@ -16,15 +16,11 @@
const dependent = document.getElementById("dependent");
internals.updateStyle();
const oldDependentBackground = getComputedStyle(dependent).backgroundColor;
- internals.resetStyleInvalidationCounters();
parent.className = "dark";
internals.updateStyle();
- const counters = internals.getStyleInvalidationCounters();
println(`child color scheme: ${getComputedStyle(child).colorScheme}`);
println(`dependent background changed: ${getComputedStyle(dependent).backgroundColor !== oldDependentBackground}`);
- println(`materialized gaps: ${counters.styleEngineMaterializedGaps}`);
- println(`engine record publications: ${counters.styleEngineRecordDeltasApplied}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/inline-winners-use-canonical-values.html b/Tests/LibWeb/Text/input/css/style-engine/inline-winners-use-canonical-values.html
index e2432dadf3c..f4ee53e2f5a 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/inline-winners-use-canonical-values.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/inline-winners-use-canonical-values.html
@@ -4,7 +4,6 @@
<script>
test(() => {
const root = document.getElementById("root");
- const before = internals.styleEngineCounters();
for (let index = 0; index < 100; ++index) {
const item = document.createElement("div");
item.style.setProperty("color", "black", "important");
@@ -12,18 +11,9 @@
}
internals.updateStyle();
- const after = internals.styleEngineCounters();
-
- println(`cascade states cover the elements: ${after.cascadeNodeHandlesPublished - before.cascadeNodeHandlesPublished >= 100}`);
- println(`inline values share identities: ${after.specifiedValuesReused - before.specifiedValuesReused >= 99}`);
- const changedProperties = after.cascadeWinnerDeltaProperties - before.cascadeWinnerDeltaProperties;
- println(`computed dependencies consume winner deltas: ${changedProperties >= 100 && after.computedWinnerDeltaPropertiesConsumed - before.computedWinnerDeltaPropertiesConsumed === changedProperties}`);
root.firstElementChild.style.setProperty("color", "#000", "important");
internals.updateStyle();
- const unchanged = internals.styleEngineCounters();
- println(`equal semantic winners stop: ${unchanged.cascadeWinnerDeltaStops > after.cascadeWinnerDeltaStops}`);
- println(`equal winners emit no computed dependency rows: ${unchanged.computedWinnerDeltaPropertiesConsumed === after.computedWinnerDeltaPropertiesConsumed}`);
println(`ordinary item: ${getComputedStyle(root.firstElementChild).color}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/keyframes-input-precision.html b/Tests/LibWeb/Text/input/css/style-engine/keyframes-input-precision.html
index 115d7ac6fef..89012b6127a 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/keyframes-input-precision.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/keyframes-input-precision.html
@@ -12,12 +12,11 @@
internals.updateStyle();
function mutate(label, mutation) {
- const before = internals.getStyleInvalidationCounters();
+ internals.resetStyleCounters();
mutation();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label} environment unchanged: ${after.styleEnvironmentVersion === before.styleEnvironmentVersion}`);
- println(`${label} stays selective: ${after.elementStyleRecomputations - before.elementStyleRecomputations < 8}`);
+ const counters = internals.styleCounters();
+ println(`${label} stays selective: ${counters.styledElements < 8}`);
println(`${label} opacity: ${getComputedStyle(target).opacity}`);
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/layout-style-record-publication.html b/Tests/LibWeb/Text/input/css/style-engine/layout-style-record-publication.html
index 5380b0dfc08..fa58698b6c6 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/layout-style-record-publication.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/layout-style-record-publication.html
@@ -9,11 +9,8 @@
const target = document.getElementById("target");
target.getBoundingClientRect();
internals.updateStyle();
- let before = internals.getStyleInvalidationCounters();
target.style.backgroundColor = "red";
internals.updateStyle();
- let after = internals.getStyleInvalidationCounters();
- println(`paint change publishes once: ${after.layoutStyleRecordPublications - before.layoutStyleRecordPublications === 1}`);
println(`layout follows installed record: ${internals.layoutStyleRecordIdentity(target) === internals.styleRecordIdentity(target)}`);
println(`paint background: ${getComputedStyle(target).backgroundColor}`);
println(`kept box width: ${target.getBoundingClientRect().width}`);
@@ -34,11 +31,8 @@
slot.assign(...children);
host.getBoundingClientRect();
internals.updateStyle();
- before = internals.getStyleInvalidationCounters();
slot.style.color = "green";
internals.updateStyle();
- after = internals.getStyleInvalidationCounters();
- println(`${mode}: each assigned box publishes once: ${after.layoutStyleRecordPublications - before.layoutStyleRecordPublications === 40}`);
println(`${mode}: assigned colors: ${children.every(child => getComputedStyle(child).color === "rgb(0, 128, 0)")}`);
println(`${mode}: layout records follow installed records: ${children.every(child => internals.layoutStyleRecordIdentity(child) === internals.styleRecordIdentity(child))}`);
println(`${mode}: assigned box widths: ${children.every(child => child.getBoundingClientRect().width === 10)}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/local-action-document-scale.html b/Tests/LibWeb/Text/input/css/style-engine/local-action-document-scale.html
index 42da3411c87..87ac8ee6487 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/local-action-document-scale.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/local-action-document-scale.html
@@ -8,38 +8,6 @@
test(() => {
const root = document.getElementById("root");
const target = document.getElementById("target");
- const graphCounterNames = [
- "normalizedUniqueKeys",
- "routedEntryPoints",
- "candidateChecks",
- "localFeatureTests",
- "combinatorSteps",
- "structuralTests",
- "coldNodesEvaluated",
- "selectorTruthAdditions",
- "matchAnswerChanges",
- "matchAnswerUpqueries",
- "remainingPostingRowsCopied",
- "remainingPostingRowsInspected",
- "preparedMatchingBatchCompletenessRowsInspected",
- "preparedMatchingBatchRowsCloned",
- "invalidatedStyleNodes",
- "plannedNodesWithDirectAction",
- "plannedNodesWithSignedDelta",
- "plannedNodesWithOutputChange",
- "plannedNodesWithUpquery",
- "plannedNodesUnattributed",
- ];
- const styleCounterNames = [
- "styleEngineReactionElements",
- "styleEnginePublishedReactions",
- "elementStyleRecomputations",
- "elementComputedStyleChanges",
- ];
-
- function difference(after, before, names) {
- return Object.fromEntries(names.map(name => [name, after[name] - before[name]]));
- }
function toggleActive(active) {
target.classList.toggle("active", active);
@@ -51,15 +19,20 @@
toggleActive(true);
toggleActive(false);
- const graphBefore = internals.styleEngineCounters();
- const styleBefore = internals.getStyleInvalidationCounters();
+ internals.resetStyleCounters();
toggleActive(true);
- const graphAfter = internals.styleEngineCounters();
- const styleAfter = internals.getStyleInvalidationCounters();
+ const counters = internals.styleCounters();
+ const lastPass = internals.styleLastPass();
toggleActive(false);
return {
- graph: difference(graphAfter, graphBefore, graphCounterNames),
- style: difference(styleAfter, styleBefore, styleCounterNames),
+ passes: counters.passes,
+ fullPasses: counters.fullPasses,
+ styled: lastPass.styled,
+ changed: lastPass.changed,
+ hintedElements: counters.hintedElements,
+ hintedSubtrees: counters.hintedSubtrees,
+ invalidationVisits: counters.invalidationVisits,
+ invalidationTests: counters.invalidationTests,
};
}
@@ -75,24 +48,21 @@
internals.updateStyle();
}
+ internals.updateStyle();
const measurements = [];
- // These sizes exercise the same selective planner strategy while increasing the
- // unrelated document population by 16x.
+ // These sizes increase the unrelated document population by 16x.
for (const size of [257, 1025, 4097]) {
growTo(size);
measurements.push(measureAddition());
}
const baseline = JSON.stringify(measurements[0]);
- println(`normalized action rows: ${measurements[0].graph.normalizedUniqueKeys}`);
- println(`one selector reaction: ${measurements[0].graph.selectorTruthAdditions}`);
- println(`one match reaction: ${measurements[0].graph.matchAnswerChanges}`);
- println(`one computed reaction: ${measurements[0].style.elementComputedStyleChanges}`);
- println(`one directly acted node: ${measurements[0].graph.plannedNodesWithDirectAction}`);
- println(`one signed-delta node: ${measurements[0].graph.plannedNodesWithSignedDelta}`);
- println(`one changed-output node: ${measurements[0].graph.plannedNodesWithOutputChange}`);
- println(`no upquery nodes: ${measurements[0].graph.plannedNodesWithUpquery}`);
- println(`no unattributed nodes: ${measurements[0].graph.plannedNodesUnattributed}`);
+ println(`one pass: ${measurements[0].passes}`);
+ println(`no full pass: ${measurements[0].fullPasses}`);
+ println(`styled: ${measurements[0].styled}`);
+ println(`changed: ${measurements[0].changed}`);
+ println(`one hinted element: ${measurements[0].hintedElements}`);
+ println(`no hinted subtree: ${measurements[0].hintedSubtrees}`);
println(`physical work is document-scale invariant: ${measurements.every(measurement => JSON.stringify(measurement) === baseline)}`);
println(`largest document elements: ${root.childElementCount}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/local-feature-mutations.html b/Tests/LibWeb/Text/input/css/style-engine/local-feature-mutations.html
index fa6632c15b7..cb0b6873a7e 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/local-feature-mutations.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/local-feature-mutations.html
@@ -68,11 +68,11 @@
// beside an unclassed anchor is not named.
plan("an attribute above a sibling combinator", () => document.getElementById("sib-guard").setAttribute("data-mode", "light"));
- // Setting an attribute to the value it already has moves nothing, so the journal cancels it.
+ // Setting an attribute to the value it already has moves nothing, so nothing is restyled.
guard.setAttribute("data-mode", "dark");
planSetup();
guard.setAttribute("data-mode", "dark");
- const repeat = internals.styleEngineTransactionReactions();
- println(`rewrite with the same value: [${repeat.elements.join(", ")}]`);
+ const repeat = planPass();
+ println(`rewrite with the same value: [${repeat.styled.join(", ")}]`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/losing-sheet-removal-uses-winner-index.html b/Tests/LibWeb/Text/input/css/style-engine/losing-sheet-removal-uses-winner-index.html
index aeeb5a95969..5a77f8f2357 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/losing-sheet-removal-uses-winner-index.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/losing-sheet-removal-uses-winner-index.html
@@ -20,14 +20,10 @@
Array.from({ length: 100 }, () => ".item { color: red; }").join("\n") +
"\n#sentinel { outline: 0 solid green; }";
internals.updateStyle();
- const before = internals.styleEngineCounters();
losing.remove();
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`losing rules rejected: ${after.programCandidatesRejectedByCascade - before.programCandidatesRejectedByCascade}`);
- println(`only local nodes invalidated: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes < 10}`);
println(`ordinary item: ${getComputedStyle(root.firstElementChild).color}`);
println(`sentinel: ${getComputedStyle(root.lastElementChild).outlineStyle}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/manual-slot-style-propagation.html b/Tests/LibWeb/Text/input/css/style-engine/manual-slot-style-propagation.html
index 56340219dac..16132ffe0b6 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/manual-slot-style-propagation.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/manual-slot-style-propagation.html
@@ -26,20 +26,18 @@
first.assign(...children, text);
internals.updateStyle();
- let before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
first.style.backgroundColor = "red";
internals.updateStyle();
- let after = internals.styleEngineCounters();
- println(`manual slot paint change only reaches slot: ${after.reachedStyleNodes - before.reachedStyleNodes === 1}`);
+ println(`manual slot paint change only reaches slot: ${internals.styleCounters().styledElements === 1}`);
println(`child background: ${getComputedStyle(children[0]).backgroundColor}`);
println(`text remains assigned: ${first.assignedNodes().includes(text)}`);
internals.updateStyle();
- before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
second.assign(children[0]);
internals.updateStyle();
- after = internals.styleEngineCounters();
- println(`manual reassignment only reaches moved subtree: ${after.reachedStyleNodes - before.reachedStyleNodes <= 2}`);
+ println(`manual reassignment only reaches moved subtree: ${internals.styleCounters().styledElements <= 2}`);
println(`moved child assigned to second: ${children[0].assignedSlot === second}`);
println(`remaining child stays assigned to first: ${children[1].assignedSlot === first}`);
println(`moved child color: ${getComputedStyle(children[0]).color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/marker-font-admission.html b/Tests/LibWeb/Text/input/css/style-engine/marker-font-admission.html
index 1068bf98a5c..8c867f21ece 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/marker-font-admission.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/marker-font-admission.html
@@ -10,16 +10,10 @@
for (let index = 0; index < 20; ++index)
host.appendChild(document.createElement("li"));
internals.updateStyle();
- const before = internals.styleEngineCounters();
- const recomputationsBefore = internals.getStyleInvalidationCounters().elementStyleRecomputations;
host.style.fontSize = "18px";
internals.updateStyle();
host.style.fontFamily = "serif";
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`engine answered: ${after.engineComputedRecordDeltas > before.engineComputedRecordDeltas}`);
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - recomputationsBefore}`);
- println(`discarded records: ${after.engineComputedRecordsAbandoned - before.engineComputedRecordsAbandoned}`);
println(`font size: ${getComputedStyle(host.lastChild).fontSize}`);
println(`font family: ${getComputedStyle(host.lastChild).fontFamily}`);
println(`marker numerals: ${getComputedStyle(host.lastChild, "::marker").fontVariantNumeric}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/missing-marker-record-admission.html b/Tests/LibWeb/Text/input/css/style-engine/missing-marker-record-admission.html
index cc867fa3d23..c1565f99090 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/missing-marker-record-admission.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/missing-marker-record-admission.html
@@ -9,17 +9,12 @@
test(() => {
const host = document.getElementById("host");
internals.updateStyle();
- // Once the first item's C++ computation retains the display winner, later items
- // should reject the missing marker cascade before deriving and discarding a record.
- const before = internals.styleEngineCounters();
for (let index = 0; index < 12; ++index) {
const item = document.createElement("li");
item.className = "item";
host.appendChild(item);
internals.updateStyle();
}
- const after = internals.styleEngineCounters();
- println(`discarded engine records: ${after.engineComputedRecordsAbandoned - before.engineComputedRecordsAbandoned}`);
host.className = "visible";
internals.updateStyle();
println(`display: ${getComputedStyle(host.lastElementChild).display}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/monospace-wait-resumes-pseudo-settlement.html b/Tests/LibWeb/Text/input/css/style-engine/monospace-wait-resumes-pseudo-settlement.html
index d65aa11f2cb..290df85c0aa 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/monospace-wait-resumes-pseudo-settlement.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/monospace-wait-resumes-pseudo-settlement.html
@@ -16,16 +16,9 @@
const target = document.createElement("span");
target.id = "target";
target.style.cssText = "--width: 10cqw; width: var(--width)";
- const start = internals.styleEngineCounters();
- const startRecomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
document.getElementById("ex").appendChild(target);
internals.updateStyle();
- const end = internals.styleEngineCounters();
- const counter = name => (end[name] ?? 0) - (start[name] ?? 0);
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - startRecomputations}`);
println(`before: ${getComputedStyle(target, "::before").content}`);
println(`after: ${getComputedStyle(target, "::after").fontFamily}`);
- println(`engine pseudo records: ${counter("engineComputedPseudoRecords")}`);
- println(`font refill rounds: ${counter("fontRefillRounds")}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/multi-longhand-computed-closure.html b/Tests/LibWeb/Text/input/css/style-engine/multi-longhand-computed-closure.html
index edaf03c870f..0926b837886 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/multi-longhand-computed-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/multi-longhand-computed-closure.html
@@ -15,13 +15,8 @@
internals.updateStyle();
function mutate(label, mutation) {
- const before = internals.getStyleInvalidationCounters();
mutation();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label} full builds: ${after.baseStyleFullBuilds - before.baseStyleFullBuilds}`);
- println(`${label} partial builds: ${after.baseStylePartialBuilds - before.baseStylePartialBuilds}`);
- println(`${label} unrelated longhands skipped: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations < 800}`);
const style = getComputedStyle(container.firstElementChild);
println(`${label} color: ${style.color} opacity: ${style.opacity} text-decoration-line: ${style.textDecorationLine}`);
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/narrow-rule-removal-refreshes-losing-matches.html b/Tests/LibWeb/Text/input/css/style-engine/narrow-rule-removal-refreshes-losing-matches.html
index 82586096a07..263cf94b8cd 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/narrow-rule-removal-refreshes-losing-matches.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/narrow-rule-removal-refreshes-losing-matches.html
@@ -37,15 +37,12 @@
child.internals.updateStyle();
println(`initial winner: ${child.getComputedStyle(winner).color}`);
println(`initial loser: ${child.getComputedStyle(loser).color}`);
- const before = child.internals.styleEngineCounters();
iframe.style.width = "300px";
document.body.offsetWidth;
await animationFrame();
child.document.body.offsetWidth;
child.internals.updateStyle();
- const after = child.internals.styleEngineCounters();
- println(`both matches refreshed: ${after.selectorTruthRefreshes - before.selectorTruthRefreshes === 2}`);
println(`inactive winner: ${child.getComputedStyle(winner).color}`);
println(`inactive loser: ${child.getComputedStyle(loser).color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/nested-list-marker-engine-style.html b/Tests/LibWeb/Text/input/css/style-engine/nested-list-marker-engine-style.html
index c39f1a293c5..c8e255c8baf 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/nested-list-marker-engine-style.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/nested-list-marker-engine-style.html
@@ -10,17 +10,14 @@
<div id="host"></div>
<script>
// The marker of a list-item ::before takes the element's ::marker style, which the element holds
- // none of: the style engine derives it for the tree builder's read.
+ // none of.
test(() => {
const host = document.getElementById("host");
document.body.offsetWidth;
- const drives = () => internals.getStyleInvalidationCounters().computedLonghandDrivesStarted;
- const before = drives();
const item = document.createElement("div");
item.className = "item";
host.appendChild(item);
document.body.offsetWidth;
- println(`C++ style computations: ${drives() - before}`);
println(`marker color: ${getComputedStyle(item, "::marker").color}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/parent-dispatch-matching.html b/Tests/LibWeb/Text/input/css/style-engine/parent-dispatch-matching.html
index 98ead418b84..a18e7a73b66 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/parent-dispatch-matching.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/parent-dispatch-matching.html
@@ -19,13 +19,9 @@
test(() => {
internals.updateStyle();
- const before = internals.styleEngineCounters();
container.classList.add("changed");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- const candidateChecks = after.candidateChecks - before.candidateChecks;
- println(`parent dispatch bounds candidate checks: ${candidateChecks < 20000}`);
println(`first target: ${getComputedStyle(container.firstElementChild).color}`);
println(`last target: ${getComputedStyle(container.lastElementChild).color}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/partial-drive-box-type-adjustments.html b/Tests/LibWeb/Text/input/css/style-engine/partial-drive-box-type-adjustments.html
index 81436be1059..89a7fbaeba9 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/partial-drive-box-type-adjustments.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/partial-drive-box-type-adjustments.html
@@ -8,12 +8,8 @@
<script>
test(() => {
function mutate(label, target) {
- const before = internals.styleEngineCounters();
target.classList.toggle("padded");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`${label} avoids full drives: ${after.engineFullDrivesStarted === before.engineFullDrivesStarted}`);
- println(`${label} takes partial drive: ${after.enginePartialDrivesStarted > before.enginePartialDrivesStarted}`);
println(`${label} display: ${getComputedStyle(target).display}`);
println(`${label} padding: ${getComputedStyle(target).paddingLeft}`);
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/partial-drive-sharing-across-parents.html b/Tests/LibWeb/Text/input/css/style-engine/partial-drive-sharing-across-parents.html
index e72e393bf3f..aac356aee86 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/partial-drive-sharing-across-parents.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/partial-drive-sharing-across-parents.html
@@ -21,11 +21,8 @@
internals.updateStyle();
host.className = "warm";
internals.updateStyle();
- const before = internals.styleEngineCounters();
host.className = "changed";
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`shared across different parent padding: ${after.engineComputedRecordCohortHits - before.engineComputedRecordCohortHits >= 3}`);
println(`updated backgrounds: ${Array.from(host.querySelectorAll(".item")).every(item => getComputedStyle(item).backgroundColor === "rgb(0, 0, 255)")}`);
for (const className of ["inherit", "substitute"]) {
host.className = `changed ${className}`;
diff --git a/Tests/LibWeb/Text/input/css/style-engine/paused-transition-restyle-preserves-descendant-records.html b/Tests/LibWeb/Text/input/css/style-engine/paused-transition-restyle-preserves-descendant-records.html
index f35766dfb9e..3483a4a4790 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/paused-transition-restyle-preserves-descendant-records.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/paused-transition-restyle-preserves-descendant-records.html
@@ -30,14 +30,11 @@
}
internals.updateStyle();
println(`paused child color: ${getComputedStyle(parents[0].firstElementChild).color}`);
- const before = internals.getStyleInvalidationCounters();
for (let index = 0; index < 4; ++index) {
for (const parent of parents)
parent.classList.toggle("padded");
internals.updateStyle();
}
- const after = internals.getStyleInvalidationCounters();
- println(`padding only updates parent records: ${after.styleEngineRecordDeltasApplied - before.styleEngineRecordDeltasApplied === parents.length * 4}`);
println(`paused child color after padding: ${getComputedStyle(parents[0].lastElementChild).color}`);
parents[0].style.color = "rgb(200, 200, 200)";
internals.updateStyle();
diff --git a/Tests/LibWeb/Text/input/css/style-engine/persistent-style-sharing-cssom-revision.html b/Tests/LibWeb/Text/input/css/style-engine/persistent-style-sharing-cssom-revision.html
index 88f128cce97..0e3a7d9f379 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/persistent-style-sharing-cssom-revision.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/persistent-style-sharing-cssom-revision.html
@@ -10,16 +10,16 @@
const first = container.firstElementChild;
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
+ internals.resetStyleCounters();
const second = document.createElement("span");
second.className = "shared";
container.append(second);
internals.updateStyle();
- let counters = internals.getStyleInvalidationCounters();
- // The engine shares a first record it derived earlier the way the C++ computation shares.
- const sharedByEngine = () => (internals.styleEngineCounters().engineComputedRecordSharedHits ?? 0) >= 1;
- println(`shared across transactions: ${counters.elementStyleSharedComputations >= 1 || sharedByEngine()}`);
+ const counters = internals.styleCounters();
+ // FIXME: The arriving span should take the record of the one styled in an earlier pass
+ // (shared or reused >= 1), but the style engine shares records only within a pass.
+ println(`shared or reused across transactions: ${counters.sharedElements + counters.reusedElements}`);
println(`initial colors: ${getComputedStyle(first).color}, ${getComputedStyle(second).color}`);
document.getElementById("sheet").sheet.cssRules[0].style.color = "green";
diff --git a/Tests/LibWeb/Text/input/css/style-engine/phase-clocks-and-work-counters.html b/Tests/LibWeb/Text/input/css/style-engine/phase-clocks-and-work-counters.html
deleted file mode 100644
index 2a89c376628..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/phase-clocks-and-work-counters.html
+++ /dev/null
@@ -1,78 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- .before { margin-left: 10px }
- .after { margin-left: 30px }
- .fresh:has(> span) { opacity: 0.5 }
- .fresh { color: rgb(12, 34, 56); padding: 7px }
-</style>
-<div id="target" class="before"></div>
-<script>
- test(() => {
- const messages = [];
- const report = message => messages.push(message);
- const rustPhases = ["commitMicroseconds", "routingPlanningMicroseconds", "prepareMicroseconds", "matchingCascadeMicroseconds",
- "computationPublicationMicroseconds", "emitMicroseconds", "transactionRemainderMicroseconds"];
- const cppPhases = ["styleUpdateSubmissionMicroseconds", "styleUpdateBridgeMicroseconds",
- "styleUpdateApplyMicroseconds", "styleUpdateRemainderMicroseconds"];
- const snapshot = () => ({ rust: internals.styleEngineCounters(), cpp: internals.getStyleInvalidationCounters() });
- const delta = (after, before, key) => after[key] - before[key];
- function checkClocks(label, before, after) {
- for (const [lane, phases, whole] of [["rust", rustPhases, "transactionMicroseconds"],
- ["cpp", cppPhases, "styleUpdateMicroseconds"]]) {
- const values = phases.map(key => delta(after[lane], before[lane], key));
- const total = delta(after[lane], before[lane], whole);
- const additive = values.every(value => Number.isSafeInteger(value) && value >= 0)
- && values.reduce((sum, value) => sum + value, 0) === total;
- if (!additive)
- report(`${label} ${lane} intervals: ${JSON.stringify(values)}, whole: ${total}`);
- report(`${label} ${lane} additive: ${additive}`);
- }
- }
- internals.updateStyle();
- let before = snapshot();
- target.className = "after";
- internals.updateStyle();
- let after = snapshot();
- checkClocks("partial", before, after);
- report(`changed margin: ${getComputedStyle(target).marginLeft}`);
- // Partial drives now borrow their base; only installation of a new result copies slots.
- for (const key of ["reachedStyleNodes", "enginePartialDrivesStarted", "enginePartialLonghandEvaluations",
- "enginePhysicalLonghandEvaluations", "engineDriveCopiedTableSlots"])
- report(`${key}: ${delta(after.rust, before.rust, key) > 0}`);
-
- before = snapshot();
- const parent = document.createElement("div");
- for (let i = 0; i < 3; ++i) {
- const child = document.createElement("div");
- child.className = "fresh";
- parent.appendChild(child);
- }
- document.body.appendChild(parent);
- internals.updateStyle();
- after = snapshot();
- checkClocks("arrival", before, after);
- report(`new color: ${getComputedStyle(parent.firstChild).color}`);
- for (const key of ["coldNodesEvaluated", "candidateChecks", "engineFullDrivesStarted", "styleRecordsInterned", "styleRecordsReused"])
- report(`${key}: ${delta(after.rust, before.rust, key) > 0}`);
-
- // A quiescent update and a canceled mutation exercise paths that emit no work.
- before = snapshot();
- internals.updateStyle();
- after = snapshot();
- checkClocks("quiescent", before, after);
- before = after;
- target.className = "before";
- target.className = "after";
- internals.updateStyle();
- after = snapshot();
- checkClocks("canceled", before, after);
- before = after;
- target.className = "before";
- internals.styleEngineTransactionReactions();
- after = snapshot();
- checkClocks("diagnostic", before, after);
- for (const message of messages)
- println(message);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/placeholder-restyle-during-transition.html b/Tests/LibWeb/Text/input/css/style-engine/placeholder-restyle-during-transition.html
index 366b51f2c22..54df35ef6fd 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/placeholder-restyle-during-transition.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/placeholder-restyle-during-transition.html
@@ -15,21 +15,17 @@
<input id="target" placeholder="Placeholder Text">
<script>
// The placeholder's backing element is restyled through what it inherits from its host while its
- // transition runs: the engine settles its record, and the host's transition step keeps the
- // transition running against the record it held.
+ // transition runs, and the transition keeps running.
test(() => {
const target = document.getElementById("target");
const placeholderStyle = () => getComputedStyle(target, "::placeholder");
- const recomputations = () => internals.getStyleInvalidationCounters().elementStyleRecomputations;
println(`initial: opacity ${placeholderStyle().opacity}, font-size ${placeholderStyle().fontSize}`);
target.classList.add("fade");
println(`fading: opacity is above 0.9? ${parseFloat(placeholderStyle().opacity) > 0.9}`);
- const before = recomputations();
target.style.fontSize = "20px";
println(`restyled: font-size ${placeholderStyle().fontSize}`);
- println(`restyled: C++ recomputations ${recomputations() - before}`);
println(`restyled: opacity is above 0.9? ${parseFloat(placeholderStyle().opacity) > 0.9}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/placeholder-rule-flip-restyles-backing-element.html b/Tests/LibWeb/Text/input/css/style-engine/placeholder-rule-flip-restyles-backing-element.html
index 722500a4c69..01016ec2f78 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/placeholder-rule-flip-restyles-backing-element.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/placeholder-rule-flip-restyles-backing-element.html
@@ -8,13 +8,11 @@
<script>
test(() => {
internals.updateStyle();
- const recomputations = () => internals.getStyleInvalidationCounters().elementStyleRecomputations;
for (const step of [1, 2]) {
- const before = recomputations();
// Only the host's ::placeholder rules flip: the element backing it restyles as its own row.
field.classList.toggle("flag");
internals.updateStyle();
- println(`step ${step}: ${getComputedStyle(field, "::placeholder").color}, C++ recomputations ${recomputations() - before}`);
+ println(`step ${step}: ${getComputedStyle(field, "::placeholder").color}`);
}
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/plan.js b/Tests/LibWeb/Text/input/css/style-engine/plan.js
index 28ca7e99ec8..30301fe3e07 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/plan.js
+++ b/Tests/LibWeb/Text/input/css/style-engine/plan.js
@@ -1,28 +1,30 @@
// Shared harness for the StyleEngine mutation-surface tests.
//
// Every way the engine's inputs can move should be provable twice over: that the mutation reaches
-// the engine at all, and that its reaction batch is no wider than it has to be. The plan names
-// exactly the elements whose semantic output changed before any consumer materializes the result.
+// the engine at all, and that the elements it changes are exactly the ones whose style it moves.
+// The plan names the elements whose records the style pass after the mutation changed.
-// Settle everything before the mutation under test, so the batch describes that mutation and no
-// other. Forcing layout is not enough: layout that is already clean does not flush style, and
-// whether it happens to be clean depends on what else the page has been doing. Asking for the
-// reactions afterwards takes the transaction the settle left behind, so the next one starts empty.
+// Settle everything before the mutation under test, so the pass after it describes that mutation
+// and no other. Forcing layout is not enough: layout that is already clean does not flush style,
+// and whether it happens to be clean depends on what else the page has been doing. Resetting the
+// counters forgets the last pass, so a mutation that restyles nothing reports nothing.
function planSetup() {
internals.updateStyle();
- internals.styleEngineTransactionReactions();
+ internals.resetStyleCounters();
}
-// Run `mutate`, then report the elements whose semantic output changed.
+// Run the style pass for the mutations since planSetup(), and report it as { fullPass, styled,
+// changed }.
+function planPass() {
+ internals.updateStyle();
+ return internals.styleLastPass();
+}
+
+// Run `mutate`, then report the elements whose records changed.
function plan(name, mutate) {
planSetup();
mutate();
- const result = internals.styleEngineTransactionReactions();
- if (result.wholeDocument) {
- println(`${name}: WHOLE DOCUMENT`);
- return;
- }
- println(`${name}: [${result.elements.join(", ")}]`);
+ println(`${name}: [${planPass().changed.join(", ")}]`);
}
function make(tagName, id, options = {}) {
diff --git a/Tests/LibWeb/Text/input/css/style-engine/post-layout-size-query-reaction.html b/Tests/LibWeb/Text/input/css/style-engine/post-layout-size-query-reaction.html
deleted file mode 100644
index d410dbdedcf..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/post-layout-size-query-reaction.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- #container { container-type: inline-size; width: 100px; }
- @container (min-width: 200px) {
- #dependent { color: rgb(1, 2, 3); }
- }
-</style>
-<div id="container"><span id="dependent"></span></div>
-<script>
- test(() => {
- const container = document.getElementById("container");
- const dependent = document.getElementById("dependent");
- document.body.offsetWidth;
-
- internals.resetStyleInvalidationCounters();
- container.style.width = "300px";
- document.body.offsetWidth;
- const layoutCounters = internals.getStyleInvalidationCounters();
-
- const color = getComputedStyle(dependent).color;
- const readCounters = internals.getStyleInvalidationCounters();
-
- println("dependent color: " + color);
- // Record verification can materialize a style that a later reaction would compute.
- println("layout recomputations within budget: " + (layoutCounters.elementStyleRecomputations <= 2));
- println("size-query scan visits: " + layoutCounters.sizeQueryContainerScanVisits);
- println("read recomputations: " + (readCounters.elementStyleRecomputations - layoutCounters.elementStyleRecomputations));
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/presentation-attribute-shorthand-substitution.html b/Tests/LibWeb/Text/input/css/style-engine/presentation-attribute-shorthand-substitution.html
index 2805cf7dbc2..30abb6b464c 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/presentation-attribute-shorthand-substitution.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/presentation-attribute-shorthand-substitution.html
@@ -5,13 +5,11 @@
</svg>
<script>
// A presentation attribute naming a shorthand written with var() declares each longhand it pends, as a
- // declaration block does. Count who computed the element's record.
+ // declaration block does.
test(() => {
const text = document.getElementById("text");
text.style.setProperty("--caps", "all-small-caps");
- const recomputationsBefore = internals.getStyleInvalidationCounters().elementStyleRecomputations;
internals.updateStyle();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - recomputationsBefore}`);
println(`font-variant-caps: ${getComputedStyle(text).fontVariantCaps}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/private-pseudo-read-leaves-no-cached-record.html b/Tests/LibWeb/Text/input/css/style-engine/private-pseudo-read-leaves-no-cached-record.html
index 348f0d48516..742b5c9aa0d 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/private-pseudo-read-leaves-no-cached-record.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/private-pseudo-read-leaves-no-cached-record.html
@@ -12,21 +12,7 @@
test(() => {
internals.updateStyle();
const [first, second] = document.querySelectorAll(".item");
- const read = (element) => {
- const before = internals.styleEngineCounters();
- const color = getComputedStyle(element, "::before").color;
- const after = internals.styleEngineCounters();
- return {
- color,
- drives: after.engineFullDrivesStarted - before.engineFullDrivesStarted,
- hits: after.engineComputedRecordCohortHits - before.engineComputedRecordCohortHits,
- };
- };
- const firstRead = read(first);
- const secondRead = read(second);
- println(`first ::before color: ${firstRead.color}`);
- println(`second ::before color: ${secondRead.color}`);
- println(`first read derived a record: ${firstRead.drives > 0}`);
- println(`second read derived its own: ${secondRead.drives === firstRead.drives && secondRead.hits === firstRead.hits}`);
+ println(`first ::before color: ${getComputedStyle(first, "::before").color}`);
+ println(`second ::before color: ${getComputedStyle(second, "::before").color}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-attr-beside-unread-attributes.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-attr-beside-unread-attributes.html
index 1bcde277a20..647318a5972 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/pseudo-attr-beside-unread-attributes.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-attr-beside-unread-attributes.html
@@ -11,13 +11,8 @@
// of every record cache.
const target = document.getElementById("target");
internals.updateStyle();
- const start = internals.styleEngineCounters();
- const startRecomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
target.setAttribute("data-label", "two");
internals.updateStyle();
- const end = internals.styleEngineCounters();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - startRecomputations}`);
println(`before: ${getComputedStyle(target, "::before").content}`);
- println(`engine pseudo records: ${end.engineComputedPseudoRecords - start.engineComputedPseudoRecords}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-css-animations-settled-by-engine.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-css-animations-settled-by-engine.html
index 814d9119ef9..54146694b52 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/pseudo-css-animations-settled-by-engine.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-css-animations-settled-by-engine.html
@@ -15,8 +15,6 @@
// engine settled, and a record settled beneath a running animation keeps it composing.
const target = document.getElementById("target");
internals.updateStyle();
- const builds = () => internals.getStyleInvalidationCounters().baseStyleFullBuilds;
- const start = builds();
const report = label => {
internals.updateStyle();
const style = getComputedStyle(target, "::before");
@@ -31,6 +29,5 @@
report("another added");
target.className = "";
report("removed");
- println(`C++ style builds: ${builds() - start}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-read-beyond-its-element.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-read-beyond-its-element.html
index 177a54f6cd9..711b4699bcf 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-read-beyond-its-element.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-read-beyond-its-element.html
@@ -24,10 +24,8 @@
];
for (const [name, pseudo, target] of cases) {
const element = target();
- const start = internals.styleEngineCounters();
const value = getComputedStyle(element, pseudo).getPropertyValue("--own");
- const end = internals.styleEngineCounters();
- println(`${name} ${pseudo}: --own ${value}, demands left to the host ${end.pseudoRecordDemandsLeftToHost - start.pseudoRecordDemandsLeftToHost}`);
+ println(`${name} ${pseudo}: --own ${value}`);
}
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-reads-past-synthetic-kinds.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-reads-past-synthetic-kinds.html
index 4132a6cbc75..981f274f518 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-reads-past-synthetic-kinds.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-reads-past-synthetic-kinds.html
@@ -19,12 +19,8 @@
// is empty.
function read(element, pseudo) {
internals.updateStyle();
- const start = internals.styleEngineCounters();
const color = getComputedStyle(element, pseudo).color;
- const end = internals.styleEngineCounters();
- const drove = end.engineFullDrivesStarted - start.engineFullDrivesStarted > 0;
- const leftToHost = end.pseudoRecordDemandsLeftToHost - start.pseudoRecordDemandsLeftToHost;
- println(`${element.id}${pseudo}: ${color}, engine drove it: ${drove}, left to the host: ${leftToHost}`);
+ println(`${element.id}${pseudo}: ${color}`);
}
test(() => {
for (const pseudo of ["::placeholder", "::file-selector-button", "::view-transition-group(name)", "::view-transition-image-pair(name)", "::view-transition-old(name)", "::view-transition-new(name)"])
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-transition-starts-in-a-later-pass.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-transition-starts-in-a-later-pass.html
new file mode 100644
index 00000000000..47f1b5e296e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-element-transition-starts-in-a-later-pass.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<style>
+ #container { container-type: inline-size; width: 100px; }
+ #container.wide { width: 300px; }
+ #target { color: rgb(255, 0, 0); }
+ #target.moved { color: rgb(0, 0, 255); }
+ #target::before { content: "x"; color: rgb(255, 0, 0); }
+ #target.moved::before { color: rgb(0, 0, 255); }
+ @container (min-width: 200px) {
+ #target { transition: color 1000s steps(2, start); }
+ #target::before { transition: color 1000s steps(2, start); }
+ }
+</style>
+<div id="container"><div id="target"></div></div>
+<script>
+ test(() => {
+ // The size container only answers after layout, so the transitions are declared by a later pass of the update
+ // that moved the color, and decide against the style the update started from.
+ internals.updateStyle();
+ container.className = "wide";
+ target.className = "moved";
+ target.offsetWidth;
+ println(`element: ${getComputedStyle(target).color}`);
+ println(`::before: ${getComputedStyle(target, "::before").color}`);
+ const transitions = target.getAnimations({ subtree: true }).map(animation => `${animation.effect.pseudoElement ?? "element"} ${animation.transitionProperty}`);
+ println(`transitions: ${transitions.join(", ")}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-keyed-cascade-state.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-keyed-cascade-state.html
index 9b98c5a39d0..2ecb8586b7b 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/pseudo-keyed-cascade-state.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-keyed-cascade-state.html
@@ -24,17 +24,13 @@
test(() => {
internals.updateStyle();
getComputedStyle(target, "::before").width;
- const graphBefore = internals.styleEngineCounters();
target.classList.add("pseudo-flip");
internals.updateStyle();
- const graphAfterPseudo = internals.styleEngineCounters();
const pseudoStyle = getComputedStyle(target, "::before");
println(`pseudo content changed: ${pseudoStyle.content}`);
println(`pseudo color changed: ${pseudoStyle.color}`);
- println(`element cascade stopped: ${graphAfterPseudo.cascadeWinnerDeltaStops - graphBefore.cascadeWinnerDeltaStops >= 1}`);
- println(`pseudo delta consumed: ${graphAfterPseudo.computedWinnerDeltaPropertiesConsumed - graphBefore.computedWinnerDeltaPropertiesConsumed >= 2}`);
target.classList.add("element-flip");
internals.updateStyle();
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-only-flip-keeps-element-winners.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-only-flip-keeps-element-winners.html
index 74cf410d211..c4400cc9bce 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/pseudo-only-flip-keeps-element-winners.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-only-flip-keeps-element-winners.html
@@ -18,12 +18,9 @@
<script>
test(() => {
internals.updateStyle();
- const before = internals.styleEngineCounters().cascadeMatchesBeforeCompaction;
for (const child of container.children)
child.classList.add("flip");
internals.updateStyle();
- const matches = internals.styleEngineCounters().cascadeMatchesBeforeCompaction - before;
- println(`cascade matches: ${matches}`);
const span = container.firstElementChild.firstElementChild;
println(`::before color: ${getComputedStyle(span, "::before").color}`);
println(`padding: ${getComputedStyle(container.lastElementChild.firstElementChild).paddingLeft}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-records-beside-container-unit-substitution.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-records-beside-container-unit-substitution.html
index 950acfa0928..8b37307ba4a 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/pseudo-records-beside-container-unit-substitution.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-records-beside-container-unit-substitution.html
@@ -13,15 +13,10 @@
// container unit and so stays out of every record cache.
const target = document.getElementById("target");
internals.updateStyle();
- const start = internals.styleEngineCounters();
- const startRecomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
target.className = "changed";
internals.updateStyle();
- const end = internals.styleEngineCounters();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - startRecomputations}`);
const before = getComputedStyle(target, "::before");
println(`before: ${before.content} ${before.color}`);
println(`marker: ${getComputedStyle(target, "::marker").color}`);
- println(`engine pseudo records: ${end.engineComputedPseudoRecords - start.engineComputedPseudoRecords}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-records-of-display-none-element.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-records-of-display-none-element.html
index c3c05f93151..4367cfdec69 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/pseudo-records-of-display-none-element.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-records-of-display-none-element.html
@@ -13,15 +13,9 @@
// engine's, display:none as the element is.
const target = document.getElementById("target");
internals.updateStyle();
- const start = internals.styleEngineCounters();
- const startRecomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
target.className = "changed";
internals.updateStyle();
- const end = internals.styleEngineCounters();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - startRecomputations}`);
const before = getComputedStyle(target, "::before");
println(`before: ${before.content} ${before.color}`);
- println(`engine pseudo records: ${end.engineComputedPseudoRecords - start.engineComputedPseudoRecords}`);
- println(`parent bails: ${end.engineComputedRecordBailRecordParent - start.engineComputedRecordBailRecordParent}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-transition-records-beside-host-record.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-transition-records-beside-host-record.html
index 7ecc2dc1c12..d0d15523e27 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/pseudo-transition-records-beside-host-record.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-transition-records-beside-host-record.html
@@ -12,16 +12,10 @@
// where the host installs the record the engine settled.
const target = document.getElementById("target");
internals.updateStyle();
- const start = internals.styleEngineCounters();
- const startRecomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
target.className = "changed";
internals.updateStyle();
- const end = internals.styleEngineCounters();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - startRecomputations}`);
const transitions = target.getAnimations({ subtree: true }).map(animation => `${animation.transitionProperty} ${animation.effect.pseudoElement}`);
println(`transitions: ${transitions.join(",")}`);
println(`before: ${getComputedStyle(target, "::before").color}`);
- println(`engine pseudo records: ${end.engineComputedPseudoRecords - start.engineComputedPseudoRecords}`);
- println(`property bails: ${end.engineComputedRecordBailProperty - start.engineComputedRecordBailProperty}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/pseudo-winner-stop-kinds.html b/Tests/LibWeb/Text/input/css/style-engine/pseudo-winner-stop-kinds.html
index 05556880a91..6269f5f7bde 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/pseudo-winner-stop-kinds.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/pseudo-winner-stop-kinds.html
@@ -27,12 +27,9 @@
internals.updateStyle();
println(`initial marker: ${getComputedStyle(markerTarget, "::marker").color}`);
println(`initial backdrop: ${getComputedStyle(backdropTarget, "::backdrop").color}`);
- const before = internals.styleEngineCounters();
markerTarget.classList.add("flip");
internals.updateStyle();
- const markerChanged = internals.styleEngineCounters();
- println(`marker exact cascade stops: ${markerChanged.publishedExactCascadeStops - before.publishedExactCascadeStops}`);
backdropTarget.classList.add("flip");
internals.updateStyle();
diff --git a/Tests/LibWeb/Text/input/css/style-engine/registered-custom-property-external-inputs.html b/Tests/LibWeb/Text/input/css/style-engine/registered-custom-property-external-inputs.html
index 8ba52540b57..2e8d7f2360c 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/registered-custom-property-external-inputs.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/registered-custom-property-external-inputs.html
@@ -21,13 +21,9 @@
// computes it against each, and a change of any reaches the element.
promiseTest(async () => {
internals.updateStyle();
- const before = Object.assign({}, internals.styleEngineCounters());
for (const element of [first, second])
element.classList.add("on");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`environment refusals: ${after.engineCustomPropertyEnvironmentBails - before.engineCustomPropertyEnvironmentBails}`);
- println(`environments the engine resolved: ${after.engineCustomPropertyEnvironmentsResolved - before.engineCustomPropertyEnvironmentsResolved}`);
const describe = element => {
const style = getComputedStyle(element);
return `--position ${style.getPropertyValue("--position")}, --container-length ${style.getPropertyValue("--container-length")}, width ${style.width}, z-index ${style.zIndex}`;
diff --git a/Tests/LibWeb/Text/input/css/style-engine/removing-stylesheet-preserves-descendant-animation-overlay.html b/Tests/LibWeb/Text/input/css/style-engine/removing-stylesheet-preserves-descendant-animation-overlay.html
index 5f7ecedb87f..f68d1b1e495 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/removing-stylesheet-preserves-descendant-animation-overlay.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/removing-stylesheet-preserves-descendant-animation-overlay.html
@@ -39,7 +39,6 @@
target.offsetWidth;
const fontLoadPromise = document.fonts.load("16px SlowAhem", "X").catch(() => {});
println(`font status before removal: ${document.fonts.status}`);
- println(`live overlays before removal: ${internals.styleEngineCounters().liveAnimationOverlayRecords}`);
await new Promise(requestAnimationFrame);
container.remove();
diff --git a/Tests/LibWeb/Text/input/css/style-engine/removing-stylesheet-preserves-non-layout-descendant-record.html b/Tests/LibWeb/Text/input/css/style-engine/removing-stylesheet-preserves-non-layout-descendant-record.html
index ffcf2cc8e84..9e120c7ba4d 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/removing-stylesheet-preserves-non-layout-descendant-record.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/removing-stylesheet-preserves-non-layout-descendant-record.html
@@ -23,17 +23,6 @@
});
const churnTarget = document.getElementById("churn-target");
- let churnIndex = 1;
- const churnOnce = () => {
- churnTarget.dataset.color = `rgb(${churnIndex & 255}, ${(churnIndex >> 8) & 255}, ${(churnIndex >> 16) & 255})`;
- ++churnIndex;
- internals.updateStyle();
- };
-
- const sweepKey = () => {
- const counters = internals.styleEngineCounters();
- return `${counters.computedGroupsRetained}:${counters.computedGroupsReachable}`;
- };
const container = document.createElement("div");
const link = document.createElement("link");
@@ -77,29 +66,7 @@
const pseudoColor = getComputedStyle(pseudoTarget, "::before").color;
const fontLoadPromise = document.fonts.load("16px SlowAhem", "X").catch(() => {});
- let sweepInterval = 0;
- let sweeps = 0;
- let iterationsSinceSweep = 0;
- let lastSweepKey = sweepKey();
- for (let count = 0; count < 20000; ++count) {
- churnOnce();
- ++iterationsSinceSweep;
- const currentSweepKey = sweepKey();
- if (currentSweepKey !== lastSweepKey) {
- ++sweeps;
- sweepInterval = iterationsSinceSweep;
- iterationsSinceSweep = 0;
- lastSweepKey = currentSweepKey;
- if (sweeps === 2)
- break;
- }
- }
- for (let count = 1; count < sweepInterval; ++count)
- churnOnce();
-
println(`font status before removal: ${document.fonts.status}`);
- println(`live overlays before removal: ${internals.styleEngineCounters().liveAnimationOverlayRecords}`);
- println(`prepared style-record activity before removal: ${sweeps === 2}`);
println(`later link has style record before removal: ${internals.styleRecordIdentity(laterLink) !== 0}`);
println(`later link has layout before removal: ${internals.layoutNodeIdentity(laterLink) !== 0}`);
println(`non-layout pseudo-element has computed style before removal: ${pseudoColor === "rgb(7, 8, 9)"}`);
@@ -107,7 +74,7 @@
println(`shadow link has layout before removal: ${internals.layoutNodeIdentity(shadowLaterLink) !== 0}`);
await new Promise(requestAnimationFrame);
- churnTarget.dataset.color = `rgb(${churnIndex & 255}, ${(churnIndex >> 8) & 255}, ${(churnIndex >> 16) & 255})`;
+ churnTarget.dataset.color = "rgb(1, 2, 3)";
container.remove();
println("PASS (did not crash)");
diff --git a/Tests/LibWeb/Text/input/css/style-engine/resources/style-update-fixture.js b/Tests/LibWeb/Text/input/css/style-engine/resources/style-update-fixture.js
index 9436234d5d8..64b841964ca 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/resources/style-update-fixture.js
+++ b/Tests/LibWeb/Text/input/css/style-engine/resources/style-update-fixture.js
@@ -1,10 +1,5 @@
// Shared by the small correctness test and Meta/style-update-capture.py.
function createStyleUpdateFixture(elementCount, scenario, seed, measure = false) {
- const snapshot = () => ({
- rust: internals.styleEngineCounters(),
- cpp: internals.getStyleInvalidationCounters(),
- ffi: internals.styleFfiCounters(),
- });
const now = () => (measure ? performance.now() * 1000 : null);
const elapsed = start => (measure ? now() - start : null);
const check = (node, property, expected) => {
@@ -15,15 +10,13 @@ function createStyleUpdateFixture(elementCount, scenario, seed, measure = false)
};
const observe = checks => checks.map(([node, property, expected]) => check(node, property, expected));
const interval = (name, kind, mutate, checks) => {
- const before = snapshot();
const start = now();
mutate();
const mutationMicroseconds = elapsed(start);
const observationStart = now();
const observations = observe(checks());
const observationMicroseconds = elapsed(observationStart);
- const after = snapshot();
- return { name, kind, before, after, mutationMicroseconds, observationMicroseconds, observations };
+ return { name, kind, mutationMicroseconds, observationMicroseconds, observations };
};
if (!Number.isInteger(elementCount) || elementCount < 100 || !["connected", "detached"].includes(scenario))
throw new Error("Invalid fixture configuration");
@@ -173,7 +166,6 @@ function createStyleUpdateFixture(elementCount, scenario, seed, measure = false)
let nextStep = 0;
return {
setup,
- snapshot,
step(index) {
if (index !== nextStep++) throw new Error("Fixture mutations must run exactly once in order");
const [name, mutate, checks] = steps[index];
diff --git a/Tests/LibWeb/Text/input/css/style-engine/reuse-exact-planning-facts.html b/Tests/LibWeb/Text/input/css/style-engine/reuse-exact-planning-facts.html
deleted file mode 100644
index a8aae6b7e3a..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/reuse-exact-planning-facts.html
+++ /dev/null
@@ -1,40 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- .changed {
- --tone: rgb(1, 2, 3);
- }
-
- .container:has(.witness) > .target {
- color: var(--tone, rgb(4, 5, 6));
- }
-</style>
-<div id="container" class="container">
- <div class="witness"></div>
-</div>
-<script>
- const container = document.getElementById("container");
- for (let i = 0; i < 256; ++i) {
- const target = document.createElement("div");
- target.className = "target";
- container.appendChild(target);
- }
-
- test(() => {
- internals.updateStyle();
-
- const before = internals.styleEngineCounters();
- container.classList.add("changed");
- internals.updateStyle();
- const after = internals.styleEngineCounters();
-
- const batchRows = after.coldMatchingBatchRows - before.coldMatchingBatchRows;
- const completeRowsInspected = after.preparedMatchingBatchCompletenessRowsInspected - before.preparedMatchingBatchCompletenessRowsInspected;
- const completeRowsCloned = after.preparedMatchingBatchRowsCloned - before.preparedMatchingBatchRowsCloned;
- println(`no duplicate fact batch: ${batchRows === 0}`);
- println(`no complete fact-store scan: ${completeRowsInspected === 0}`);
- println(`no complete fact-store clone: ${completeRowsCloned === 0}`);
- println(`first target: ${getComputedStyle(container.children[1]).color}`);
- println(`last target: ${getComputedStyle(container.lastElementChild).color}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/reuse-originating-element-matches.html b/Tests/LibWeb/Text/input/css/style-engine/reuse-originating-element-matches.html
index e6ee4ca3d54..20f937ed87f 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/reuse-originating-element-matches.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/reuse-originating-element-matches.html
@@ -18,14 +18,9 @@
test(() => {
internals.updateStyle();
- const before = internals.styleEngineCounters();
target.classList.add("changed");
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`cold node evaluations: ${after.coldNodesEvaluated - before.coldNodesEvaluated}`);
- println(`candidate checks: ${after.candidateChecks - before.candidateChecks}`);
- println(`rule matches emitted: ${after.ruleMatchesEmitted - before.ruleMatchesEmitted}`);
println(`element: ${getComputedStyle(target).color}`);
println(`before: ${getComputedStyle(target, "::before").color}`);
println(`after: ${getComputedStyle(target, "::after").color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/root-font-inputs-through-fixed-ancestors.html b/Tests/LibWeb/Text/input/css/style-engine/root-font-inputs-through-fixed-ancestors.html
index 811a0f1b5e2..89c39b2de6a 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/root-font-inputs-through-fixed-ancestors.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/root-font-inputs-through-fixed-ancestors.html
@@ -30,7 +30,6 @@
return `${style.marginLeft}/${style.marginRight}, pseudo ${pseudo.marginLeft}/${pseudo.marginRight}`;
};
println(`initial: ${values(target)}`);
- const before = child.internals.styleEngineCounters();
root.classList.add("changed");
const added = child.document.createElement("span");
added.className = "target";
@@ -61,9 +60,5 @@
root.classList.add("transitioning");
root.style.fontSize = "30px";
println(`transitioning root: ${values(target)}`);
- const after = child.internals.styleEngineCounters();
- println(`root font preparation exercised: ${after.rootFontInputsPrepared > before.rootFontInputsPrepared}`);
- println(`root font fallback exercised: ${after.rootFontInputsUnprovenFallbacks > before.rootFontInputsUnprovenFallbacks}`);
- println(`engine computation exercised: ${after.engineComputedRecordDeltas > before.engineComputedRecordDeltas}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/rootless-style-update-holds-install-feedback.html b/Tests/LibWeb/Text/input/css/style-engine/rootless-style-update-holds-install-feedback.html
index 706b29874a7..d89f35f64c6 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/rootless-style-update-holds-install-feedback.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/rootless-style-update-holds-install-feedback.html
@@ -15,13 +15,10 @@
root.remove();
await nextFrame();
await nextFrame();
- internals.resetStyleInvalidationCounters();
await nextFrame();
await nextFrame();
await nextFrame();
- const setups = internals.getStyleInvalidationCounters().styleEngineTransactionSetups;
document.appendChild(root);
- println(`transaction setups without a root: ${setups}`);
// What the rootless updates held back goes with the first transaction that has a root again.
hidden.style.color = "blue";
println(`child color with the root back: ${getComputedStyle(child).color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/rule-mutations.html b/Tests/LibWeb/Text/input/css/style-engine/rule-mutations.html
index 0f114540191..8c4f249ac8f 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/rule-mutations.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/rule-mutations.html
@@ -97,9 +97,6 @@
// Writing the same declaration again moves nothing, and neither does a rule inserted and
// deleted before anything is observed.
- // FIXME: The second of these reaches `other`. A rule that arrived and left in one transaction
- // never decided anything, but its two sides are journalled under different rule
- // identities and so do not cancel.
plan("rewrite a rule's declaration with the same value", () => {
sheet.cssRules[0].style.color = "teal";
sheet.cssRules[0].style.color = "teal";
diff --git a/Tests/LibWeb/Text/input/css/style-engine/sampled-custom-property-child.html b/Tests/LibWeb/Text/input/css/style-engine/sampled-custom-property-child.html
index c8021704460..31d3b1bf549 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/sampled-custom-property-child.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/sampled-custom-property-child.html
@@ -14,16 +14,14 @@
</style>
<div id="parent"><div id="child">x</div></div>
<script>
- // A child inherits the custom properties its parent's animations sample. Count who computed the child's
- // record once a rule it matches moves.
+ // A child inherits the custom properties its parent's animations sample, also once a rule it
+ // matches moves.
asyncTest(async done => {
await document.getAnimations()[0].ready;
const child = document.getElementById("child");
println(`color: ${getComputedStyle(child).color}`);
child.className = "moved";
- const recomputationsBefore = internals.getStyleInvalidationCounters().elementStyleRecomputations;
internals.updateStyle();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - recomputationsBefore}`);
println(`background-color: ${getComputedStyle(child).backgroundColor}`);
done();
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/selection-observability-with-environment-change.html b/Tests/LibWeb/Text/input/css/style-engine/selection-observability-with-environment-change.html
index 53d088e2ee9..fb9829c1f6e 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/selection-observability-with-environment-change.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/selection-observability-with-environment-change.html
@@ -8,16 +8,12 @@
<script>
// A selection makes ::selection styles observable in the update that also moves the document's
// style environment (its supported color schemes). Every element in the selection is told its
- // pseudo-element inputs may have changed: count who computes their records.
+ // pseudo-element inputs may have changed.
test(() => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
getSelection().selectAllChildren(document.body);
scheme.content = "light dark";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`engine computed records: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords > 0}`);
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
const styled = getComputedStyle(document.getElementById("styled"), "::selection");
println(`styled ::selection: ${styled.color} on ${styled.backgroundColor}`);
const inner = getComputedStyle(document.getElementById("inner"), "::selection");
diff --git a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-updates-signature.html b/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-updates-signature.html
deleted file mode 100644
index 31feb87afbf..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-updates-signature.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- #target { color: blue }
- #target.active { color: red }
-</style>
-<div id="target"></div>
-<script>
- test(() => {
- const target = document.getElementById("target");
- internals.updateStyle();
-
- const before = internals.styleEngineCounters();
- const styleBefore = internals.getStyleInvalidationCounters();
- target.classList.add("active");
- internals.updateStyle();
- println(`active color: ${getComputedStyle(target).color}`);
- target.classList.remove("active");
- internals.updateStyle();
- const after = internals.styleEngineCounters();
- const styleAfter = internals.getStyleInvalidationCounters();
-
- println(`selector truth additions: ${after.selectorTruthAdditions - before.selectorTruthAdditions}`);
- println(`selector truth removals: ${after.selectorTruthRemovals - before.selectorTruthRemovals}`);
- println(`selector truth cancellations: ${after.selectorTruthCancellations - before.selectorTruthCancellations}`);
- println(`selector truth refreshes: ${after.selectorTruthRefreshes - before.selectorTruthRefreshes}`);
- println(`match answer changes: ${after.matchAnswerChanges - before.matchAnswerChanges}`);
- println(`match answer upqueries: ${after.matchAnswerUpqueries - before.matchAnswerUpqueries}`);
- println(`delta patches: ${after.retainedMatchAnswerDeltaPatches - before.retainedMatchAnswerDeltaPatches}`);
- println(`patch upqueries: ${after.retainedMatchAnswerPatches - before.retainedMatchAnswerPatches}`);
- println(`answer reuses: ${after.retainedMatchAnswerReuses - before.retainedMatchAnswerReuses}`);
- println(`cold node evaluations: ${after.coldNodesEvaluated - before.coldNodesEvaluated}`);
- println(`invalidated nodes: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes}`);
- println(`computed style changes: ${styleAfter.elementComputedStyleChanges - styleBefore.elementComputedStyleChanges}`);
- println(`inactive color: ${getComputedStyle(target).color}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/shadow-host-pseudo-element-beside-animated-record.html b/Tests/LibWeb/Text/input/css/style-engine/shadow-host-pseudo-element-beside-animated-record.html
index 1059d628dbd..ac3e449a79f 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/shadow-host-pseudo-element-beside-animated-record.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/shadow-host-pseudo-element-beside-animated-record.html
@@ -18,11 +18,8 @@
const host = document.getElementById("host");
host.attachShadow({ mode: "open" }).innerHTML = "<slot></slot>";
internals.updateStyle();
- const before = Object.assign({}, internals.styleEngineCounters());
host.getAnimations()[0].currentTime = 500000;
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`environment refusals: ${after.engineCustomPropertyEnvironmentBails - before.engineCustomPropertyEnvironmentBails}`);
println(`::before color: ${getComputedStyle(host, "::before").color}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/shared-image-declaration-context.html b/Tests/LibWeb/Text/input/css/style-engine/shared-image-declaration-context.html
index 5786e596256..e2d735f9286 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/shared-image-declaration-context.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/shared-image-declaration-context.html
@@ -9,12 +9,7 @@
<script>
test(() => {
internals.updateStyle();
- // The engine computes these records itself now; C++ shares the ones it computes.
- const settledWithoutRecomputation = () => {
- const counters = internals.getStyleInvalidationCounters();
- return counters.elementStyleSharedComputations + counters.engineComputedStyleRecords;
- };
- const before = settledWithoutRecomputation();
+ internals.resetStyleCounters();
const nodes = [];
for (const className of ["local", "imported"]) {
for (let index = 0; index < 8; ++index) {
@@ -25,8 +20,8 @@
}
}
internals.updateStyle();
- const after = settledWithoutRecomputation();
- println(`image styles share within each declaration context: ${after - before >= 14}`);
+ const counters = internals.styleCounters();
+ println(`image styles share within each declaration context: ${counters.sharedElements + counters.reusedElements >= 14}`);
function checkImages(label) {
const correct = nodes.every(node => {
diff --git a/Tests/LibWeb/Text/input/css/style-engine/shared-selector-program-routes-once.html b/Tests/LibWeb/Text/input/css/style-engine/shared-selector-program-routes-once.html
deleted file mode 100644
index 85422587d24..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/shared-selector-program-routes-once.html
+++ /dev/null
@@ -1,26 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<div id="root"></div>
-<script>
- test(() => {
- const root = document.getElementById("root");
- for (let index = 0; index < 100; ++index) {
- const item = document.createElement("div");
- item.className = "item";
- root.appendChild(item);
- }
-
- internals.updateStyle();
- const before = internals.styleEngineCounters();
- const sheet = document.createElement("style");
- sheet.textContent =
- Array.from({ length: 100 }, () => ".missing .item { outline-color: red; }").join("\n");
- document.head.appendChild(sheet);
- internals.updateStyle();
- const after = internals.styleEngineCounters();
-
- println(`rules compiled: ${after.styleRulesCompiled - before.styleRulesCompiled}`);
- println(`selector candidates tested: ${after.sheetChangeCandidatesRejected - before.sheetChangeCandidatesRejected}`);
- println(`only local nodes invalidated: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes < 10}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/slot-assigned-nodes-published-once-per-arrival.html b/Tests/LibWeb/Text/input/css/style-engine/slot-assigned-nodes-published-once-per-arrival.html
deleted file mode 100644
index 15a0da82898..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/slot-assigned-nodes-published-once-per-arrival.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<div id="host"></div>
-<script>
- test(() => {
- host.attachShadow({ mode: "open" }).innerHTML = "<slot></slot>";
- internals.updateStyle();
- const before = internals.styleEngineCounters().slotAssignedNodeListsPublished;
- for (let i = 0; i < 20; ++i)
- host.append(" ", document.createElement("span"));
- internals.updateStyle();
- const after = internals.styleEngineCounters().slotAssignedNodeListsPublished;
- println(`slot lists published: ${after - before}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/slot-inherited-group-updates.html b/Tests/LibWeb/Text/input/css/style-engine/slot-inherited-group-updates.html
index 626c1b82093..b0b08681190 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/slot-inherited-group-updates.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/slot-inherited-group-updates.html
@@ -17,15 +17,8 @@
if (mode === "manual")
slot.assign(...children);
internals.updateStyle();
- const before = internals.styleEngineCounters();
slot.style.color = "rgb(12, 34, 56)";
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`${mode}: inherited color avoids full drives: ${after.engineFullDrivesStarted === before.engineFullDrivesStarted}`);
- println(`${mode}: shared inherited groups are computed at most twice: ${after.inheritedGroupSwapComputations - before.inheritedGroupSwapComputations <= 2}`);
- println(`${mode}: siblings reuse inherited group results: ${after.inheritedGroupSwapReuses - before.inheritedGroupSwapReuses >= 78}`);
- println(`${mode}: inherited updates reuse cascades: ${after.retainedMatchAnswerReuses - before.retainedMatchAnswerReuses + after.deferredCascadeCompletions - before.deferredCascadeCompletions >= 80}`);
- println(`${mode}: cascade completion is bounded: ${after.cascadeMatchesBeforeCompaction - before.cascadeMatchesBeforeCompaction <= 16}`);
println(`${mode}: assigned colors: ${children.every(child => getComputedStyle(child).color === "rgb(12, 34, 56)")}`);
println(`${mode}: descendant colors: ${children.every(child => getComputedStyle(child.firstElementChild).color === "rgb(12, 34, 56)")}`);
println(`${mode}: currentColor borders: ${children.every(child => getComputedStyle(child).borderTopColor === "rgb(12, 34, 56)")}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/slot-partial-variable-environment-move.html b/Tests/LibWeb/Text/input/css/style-engine/slot-partial-variable-environment-move.html
index be807afd70a..2aa1e5b6dbd 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/slot-partial-variable-environment-move.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/slot-partial-variable-environment-move.html
@@ -17,13 +17,10 @@
}
host.append(moved);
moved.offsetWidth;
- const before = internals.styleEngineCounters();
for (let index = 0; index < 4; ++index) {
moved.slot = index % 2 ? "a" : "b";
internals.updateStyle();
}
- const after = internals.styleEngineCounters();
- println(`changed variables use partial descendant drives: ${after.engineFullDrivesStarted - before.engineFullDrivesStarted <= 4}`);
moved.slot = "b";
println(`changed width: ${getComputedStyle(moved.firstElementChild).width}`);
println(`changed shorthand: ${getComputedStyle(moved.firstElementChild).paddingTop}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/slot-reassignment-keeps-unmoved-siblings.html b/Tests/LibWeb/Text/input/css/style-engine/slot-reassignment-keeps-unmoved-siblings.html
index c55481762e9..f8c93dcfce1 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/slot-reassignment-keeps-unmoved-siblings.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/slot-reassignment-keeps-unmoved-siblings.html
@@ -23,11 +23,10 @@
const unmoved = host.children[11];
function moveTo(slot) {
internals.updateStyle();
- const before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
moved.slot = slot;
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`move to ${slot}: only moved subtree reached: ${after.reachedStyleNodes - before.reachedStyleNodes <= 2}`);
+ println(`move to ${slot}: only moved subtree reached: ${internals.styleCounters().styledElements <= 2}`);
println(`moved color: ${getComputedStyle(moved).color}`);
println(`child color: ${getComputedStyle(moved.firstElementChild).color}`);
println(`unmoved color: ${getComputedStyle(unmoved).color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/slot-style-propagation.html b/Tests/LibWeb/Text/input/css/style-engine/slot-style-propagation.html
index 2a8c6492510..801df00bf64 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/slot-style-propagation.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/slot-style-propagation.html
@@ -25,18 +25,16 @@
const childShadow = host.firstElementChild.attachShadow({ mode: "open" });
childShadow.innerHTML = "<span>shadow child</span>";
internals.updateStyle();
- let before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
slot.style.backgroundColor = "red";
internals.updateStyle();
- let after = internals.styleEngineCounters();
- println(`background change only reaches slot: ${after.reachedStyleNodes - before.reachedStyleNodes === 1}`);
+ println(`background change only reaches slot: ${internals.styleCounters().styledElements === 1}`);
println(`child background: ${getComputedStyle(host.firstElementChild).backgroundColor}`);
- before = internals.styleEngineCounters();
+ internals.resetStyleCounters();
slot.style.color = "green";
internals.updateStyle();
- after = internals.styleEngineCounters();
- println(`inherited color avoids full drives: ${after.engineFullDrivesStarted === before.engineFullDrivesStarted}`);
+ println(`inherited color avoids full passes: ${internals.styleCounters().fullPasses === 0}`);
println(`inherited color: ${getComputedStyle(host.firstElementChild).color}`);
println(`last child color: ${getComputedStyle(host.lastElementChild).color}`);
println(`shadow descendant color: ${getComputedStyle(childShadow.firstElementChild).color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/slot-variable-environment-move.html b/Tests/LibWeb/Text/input/css/style-engine/slot-variable-environment-move.html
index 1bff58e38a2..c5d6535d04b 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/slot-variable-environment-move.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/slot-variable-environment-move.html
@@ -19,13 +19,10 @@
}
host.append(moved);
moved.offsetWidth;
- const before = internals.styleEngineCounters();
for (let index = 0; index < 4; ++index) {
moved.slot = index % 2 ? "a" : "b";
internals.updateStyle();
}
- const after = internals.styleEngineCounters();
- println(`unchanged variable inputs avoid descendant full drives: ${after.engineFullDrivesStarted - before.engineFullDrivesStarted <= 4}`);
println(`unchanged width: ${getComputedStyle(moved.firstElementChild).width}`);
println(`unused value follows slot: ${getComputedStyle(moved.lastElementChild).getPropertyValue("--unused")}`);
a.style.setProperty("--effect-opacity", "0.25");
@@ -34,10 +31,8 @@
opacity.pause();
opacity.currentTime = 250000;
internals.updateStyle();
- const beforeAnimationMove = internals.styleEngineCounters();
moved.slot = "b";
internals.updateStyle();
- println(`animated environment move avoids full drives: ${internals.styleEngineCounters().engineFullDrivesStarted - beforeAnimationMove.engineFullDrivesStarted <= 1}`);
println(`animated width after environment move: ${getComputedStyle(moved.firstElementChild).width}`);
println(`animation after environment move: ${getComputedStyle(moved.firstElementChild).opacity}`);
b.style.setProperty("--width", "20px");
diff --git a/Tests/LibWeb/Text/input/css/style-engine/slotted-shadow-host-context-order.html b/Tests/LibWeb/Text/input/css/style-engine/slotted-shadow-host-context-order.html
index 000f85aee7d..c6ec9405574 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/slotted-shadow-host-context-order.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/slotted-shadow-host-context-order.html
@@ -19,13 +19,10 @@
<script>
// A slotted shadow host is weighed in the tree it is slotted into before its own shadow tree, though both
// trees are as deeply encapsulated: the slot's tree wins normal declarations, the host's own important ones.
- // Count who computed the host's record and its :host::before.
test(() => {
const inner = document.getElementById("inner");
inner.className = "a b c";
- const recomputationsBefore = internals.getStyleInvalidationCounters().elementStyleRecomputations;
internals.updateStyle();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - recomputationsBefore}`);
println(`color: ${getComputedStyle(inner).color}`);
println(`background-color: ${getComputedStyle(inner).backgroundColor}`);
println(`::before color: ${getComputedStyle(inner, "::before").color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/style-input-record-survives-unrelated-sheet.html b/Tests/LibWeb/Text/input/css/style-engine/style-input-record-survives-unrelated-sheet.html
index 126abd1dfdf..2076efd43a0 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/style-input-record-survives-unrelated-sheet.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/style-input-record-survives-unrelated-sheet.html
@@ -24,12 +24,8 @@
};
insertSheet("* { outline-width: 1px }");
- internals.resetStyleInvalidationCounters();
insertSheet("* { outline-width: 2px }");
- const counters = internals.getStyleInvalidationCounters();
- println(`input changed by parent style: ${counters.elementStyleInputChangedByParentStyle}`);
- println(`input changed by parent custom properties: ${counters.elementStyleInputChangedByParentCustomProperties}`);
println(`item color: ${getComputedStyle(host.firstElementChild.firstElementChild).color}`);
println(`wrap padding: ${getComputedStyle(host.firstElementChild).paddingTop}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/style-query-gated-rule-waits-for-moving-container.html b/Tests/LibWeb/Text/input/css/style-engine/style-query-gated-rule-waits-for-moving-container.html
index 706bc27fe85..1e4a5946740 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/style-query-gated-rule-waits-for-moving-container.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/style-query-gated-rule-waits-for-moving-container.html
@@ -17,14 +17,12 @@
<script>
test(() => {
internals.updateStyle();
- const recomputations = () => internals.getStyleInvalidationCounters().elementStyleRecomputations;
// The target's winners are published while its container's answer moves, so its gated
// rule waits for the container, and is decided again once the container settles.
for (const step of [1, 2, 3]) {
- const before = recomputations();
container.classList.toggle("on");
internals.updateStyle();
- println(`step ${step}: ${getComputedStyle(target).color}, C++ recomputations ${recomputations() - before}`);
+ println(`step ${step}: ${getComputedStyle(target).color}`);
}
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/style-read-consumes-complete-reaction-batch.html b/Tests/LibWeb/Text/input/css/style-engine/style-read-consumes-complete-reaction-batch.html
deleted file mode 100644
index f73e8165840..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/style-read-consumes-complete-reaction-batch.html
+++ /dev/null
@@ -1,34 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- #target:checked + #reaction { color: green; }
-</style>
-<input id="target" type="checkbox">
-<span id="reaction"></span>
-<span id="query"></span>
-<script>
- test(() => {
- const target = document.getElementById("target");
- const query = document.getElementById("query");
- const reaction = document.getElementById("reaction");
- internals.updateStyle();
-
- internals.resetStyleInvalidationCounters();
- target.checked = true;
- getComputedStyle(query).color;
-
- const readCounters = internals.getStyleInvalidationCounters();
-
- internals.updateStyle();
- const reactionColor = getComputedStyle(reaction).color;
- const finalCounters = internals.getStyleInvalidationCounters();
-
- println("style read reaction batch runs: " + readCounters.styleEngineReactionBatchRuns);
- println("style read reaction elements: " + readCounters.styleEngineReactionElements);
- println("style read published reactions: " + readCounters.styleEnginePublishedReactions);
- println("style read recomputations: " + readCounters.elementStyleRecomputations);
- println("reaction color: " + reactionColor);
- println("subsequent update reaction batch runs: " + (finalCounters.styleEngineReactionBatchRuns - readCounters.styleEngineReactionBatchRuns));
- println("subsequent update recomputations: " + (finalCounters.elementStyleRecomputations - readCounters.elementStyleRecomputations));
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/style-read-consumes-inheritance-reactions.html b/Tests/LibWeb/Text/input/css/style-engine/style-read-consumes-inheritance-reactions.html
deleted file mode 100644
index 65ea407051b..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/style-read-consumes-inheritance-reactions.html
+++ /dev/null
@@ -1,36 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- #parent.before { color: red; }
- #parent.after { color: green; }
-</style>
-<div id="parent" class="before">
- <span id="read-child"></span>
- <span id="sibling"></span>
-</div>
-<script>
- test(() => {
- const parent = document.getElementById("parent");
- const readChild = document.getElementById("read-child");
- const sibling = document.getElementById("sibling");
- internals.updateStyle();
-
- internals.resetStyleInvalidationCounters();
- parent.className = "after";
- const readChildColor = getComputedStyle(readChild).color;
- const readCounters = internals.getStyleInvalidationCounters();
-
- internals.updateStyle();
- const siblingColor = getComputedStyle(sibling).color;
- const finalCounters = internals.getStyleInvalidationCounters();
-
- println("read child color: " + readChildColor);
- println("sibling color: " + siblingColor);
- println("style read reaction batch runs: " + readCounters.styleEngineReactionBatchRuns);
- println("style read reaction elements: " + readCounters.styleEngineReactionElements);
- println("style read published reactions: " + readCounters.styleEnginePublishedReactions);
- println("style read recomputations: " + readCounters.elementStyleRecomputations);
- println("subsequent update reaction batch runs: " + (finalCounters.styleEngineReactionBatchRuns - readCounters.styleEngineReactionBatchRuns));
- println("subsequent update recomputations: " + (finalCounters.elementStyleRecomputations - readCounters.elementStyleRecomputations));
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/style-sharing-donor-after-hidden-subtree.html b/Tests/LibWeb/Text/input/css/style-engine/style-sharing-donor-after-hidden-subtree.html
index c39d798c8c9..3036d89114c 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/style-sharing-donor-after-hidden-subtree.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/style-sharing-donor-after-hidden-subtree.html
@@ -18,11 +18,8 @@
document.documentElement.style.fontSize = "17px";
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
container.style.display = "block";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`partial builds: ${after.baseStylePartialBuilds - before.baseStylePartialBuilds}`);
for (const rect of [first, second]) {
const style = getComputedStyle(rect);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/style-sharing-donor-first-build.html b/Tests/LibWeb/Text/input/css/style-engine/style-sharing-donor-first-build.html
index ebd960d6bd9..321cb6d8c5d 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/style-sharing-donor-first-build.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/style-sharing-donor-first-build.html
@@ -9,25 +9,14 @@
return font;
}
- // The first records the engine computes and those it takes from an earlier node alike.
- function engineSharedRecords() {
- const engine = internals.styleEngineCounters();
- return (engine.engineComputedRecordSharedHits ?? 0) + (engine.engineComputedRecordCohortHits ?? 0);
- }
-
function measure(label, color) {
container.replaceChildren(makeFont("red"));
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
- const sharedBefore = engineSharedRecords();
const font = makeFont(color);
container.append(font);
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label}: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations} C++ longhand evaluations`);
- println(`${label}: takes the donor's record: ${engineSharedRecords() > sharedBefore}`);
println(`${label}: color ${getComputedStyle(font).color}`);
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/style-sharing-previous-style-identity.html b/Tests/LibWeb/Text/input/css/style-engine/style-sharing-previous-style-identity.html
index f9c525a3e61..5473e82fb7f 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/style-sharing-previous-style-identity.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/style-sharing-previous-style-identity.html
@@ -14,14 +14,11 @@
getComputedStyle(first).color;
getComputedStyle(second).color;
- const before = internals.getStyleInvalidationCounters();
first.className = "shared";
second.className = "shared";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
println(getComputedStyle(first).color);
println(getComputedStyle(second).color);
- println(`shared computations: ${after.elementStyleSharedComputations - before.elementStyleSharedComputations}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/style-update-fixture.html b/Tests/LibWeb/Text/input/css/style-engine/style-update-fixture.html
index 2ef01da778c..7480940ce73 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/style-update-fixture.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/style-update-fixture.html
@@ -6,20 +6,10 @@
const messages = [];
for (const scenario of ["connected", "detached"]) {
const fixture = createStyleUpdateFixture(300, scenario, 1);
- const samples = [fixture.setup];
for (let index = 0; index < 12; ++index) {
const sample = fixture.step(index);
- samples.push(sample);
- if (sample.after.rust.reachedStyleNodes <= sample.before.rust.reachedStyleNodes)
- throw new Error(`${scenario}: ${sample.name} reached no style nodes`);
messages.push(`${scenario}: ${sample.name}: PASS`);
}
- for (const key of ["coldNodesEvaluated", "engineFullDrivesStarted", "enginePartialDrivesStarted",
- "enginePhysicalLonghandEvaluations", "styleRecordsInterned"]) {
- if (!samples.some(sample => sample.after.rust[key] > sample.before.rust[key]))
- throw new Error(`${scenario}: missing coverage for ${key}`);
- }
- messages.push(`${scenario}: coverage: PASS`);
fixture.dispose();
}
for (const message of messages)
diff --git a/Tests/LibWeb/Text/input/css/style-engine/substituted-revert-keywords-in-longhands.html b/Tests/LibWeb/Text/input/css/style-engine/substituted-revert-keywords-in-longhands.html
index e1c98e50392..4d87cf21c68 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/substituted-revert-keywords-in-longhands.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/substituted-revert-keywords-in-longhands.html
@@ -14,8 +14,7 @@
<div id="parent"></div>
<script>
// Each element substitutes a revert keyword into a longhand, written or through a shorthand. Each
- // line prints how often the style engine refused the element's record for its substitution, how
- // many elements C++ computed instead, and what the reverted longhands computed to.
+ // line prints what the reverted longhands computed to.
const cases = [
["inline", "font-size: var(--missing, revert); margin-left: var(--missing, revert-layer); background-color: var(--missing, revert-layer)"],
["background-color", "background-color: var(--missing, revert-layer)"],
@@ -32,14 +31,10 @@
element.id = id;
if (inlineStyle)
element.setAttribute("style", inlineStyle);
- const before = Object.assign({}, internals.styleEngineCounters());
- internals.resetStyleInvalidationCounters();
parent.appendChild(element);
internals.updateStyle();
- const after = internals.styleEngineCounters();
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
const style = getComputedStyle(element);
- println(`${id}: substitution refusals ${after.engineComputedRecordBailSubstitution - before.engineComputedRecordBailSubstitution}, C++ recomputations ${recomputations}, color=${style.color} font-size=${style.fontSize} margin-left=${style.marginLeft} background-color=${style.backgroundColor}`);
+ println(`${id}: color=${style.color} font-size=${style.fontSize} margin-left=${style.marginLeft} background-color=${style.backgroundColor}`);
}
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/substituted-state-admission.html b/Tests/LibWeb/Text/input/css/style-engine/substituted-state-admission.html
index d34748eb249..dc598d08eef 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/substituted-state-admission.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/substituted-state-admission.html
@@ -9,15 +9,12 @@
test(() => {
const host = document.getElementById("host");
internals.updateStyle();
- const before = internals.styleEngineCounters();
for (let index = 0; index < 12; ++index) {
const item = document.createElement("div");
item.className = "item";
host.appendChild(item);
internals.updateStyle();
}
- const after = internals.styleEngineCounters();
- println(`substitution memo hits: ${after.engineComputedRecordSubstitutionMemoHits - before.engineComputedRecordSubstitutionMemoHits}`);
println(`width: ${getComputedStyle(host.lastChild).width}`);
host.style.setProperty("--width", "20px");
internals.updateStyle();
diff --git a/Tests/LibWeb/Text/input/css/style-engine/substitution-cache-cssom-replacement.html b/Tests/LibWeb/Text/input/css/style-engine/substitution-cache-cssom-replacement.html
index 2bd6ed14c21..91511ca04b5 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/substitution-cache-cssom-replacement.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/substitution-cache-cssom-replacement.html
@@ -13,7 +13,6 @@
const distinct = document.getElementById("distinct");
const declaration = document.styleSheets[0].cssRules[1].style;
let allValuesUpdated = true;
- const countersBefore = internals.styleEngineCounters();
for (let index = 0; index < 256; ++index) {
declaration.setProperty("width", `calc(var(--base) + ${index}px)`);
@@ -25,11 +24,6 @@
}
}
- const countersAfter = internals.styleEngineCounters();
- const usedSubstitutions = countersAfter.engineComputedRecordSubstitutions > countersBefore.engineComputedRecordSubstitutions;
- const reusedSubstitutions = countersAfter.engineComputedRecordSubstitutionMemoHits > countersBefore.engineComputedRecordSubstitutionMemoHits;
- println(`engine substitutions used: ${usedSubstitutions}`);
- println(`memo reused substitutions: ${reusedSubstitutions}`);
println(`replaced declarations use their own written value: ${allValuesUpdated}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/substitution-declaration-cache.html b/Tests/LibWeb/Text/input/css/style-engine/substitution-declaration-cache.html
index 43c98f49382..b02b55747fd 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/substitution-declaration-cache.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/substitution-declaration-cache.html
@@ -13,15 +13,6 @@
<script>
test(() => {
internals.updateStyle();
- let last = internals.styleEngineCounters();
- const substitutions = () => {
- const counters = internals.styleEngineCounters();
- const resolved = (counters.engineComputedRecordSubstitutions ?? 0) - (last.engineComputedRecordSubstitutions ?? 0);
- const memoHits = (counters.engineComputedRecordSubstitutionMemoHits ?? 0) - (last.engineComputedRecordSubstitutionMemoHits ?? 0);
- const result = `${resolved} resolved, memoized: ${memoHits > 0}`;
- last = counters;
- return result;
- };
const host = document.getElementById("host");
for (let index = 0; index < 50; ++index) {
@@ -33,21 +24,15 @@
host.appendChild(item);
}
internals.updateStyle();
- // One declaration under one environment substitutes once; later substitutions take it
- // from the memo. Record donors can avoid some of those substitutions entirely.
- println(`shared environment: ${substitutions()}`);
println(`shared value: ${getComputedStyle(host.lastElementChild).paddingLeft}`);
host.lastElementChild.style.zIndex = 100;
internals.updateStyle();
- println(`later transaction: ${substitutions()}`);
println(`later transaction value: ${getComputedStyle(host.lastElementChild).paddingLeft}`);
- // A moved environment substitutes the declaration again, once, and every item takes the
- // new value from the memo.
+ // A moved environment gives every item the new value.
document.styleSheets[0].cssRules[0].style.setProperty("--spacing", "9px");
internals.updateStyle();
- println(`moved environment: ${substitutions()}`);
println(`moved value: ${getComputedStyle(host.firstElementChild).paddingLeft}`);
println(`moved neighbour: ${getComputedStyle(host.lastElementChild).paddingLeft}`);
});
diff --git a/Tests/LibWeb/Text/input/css/style-engine/substitution-shorthand-cssom-replacement.html b/Tests/LibWeb/Text/input/css/style-engine/substitution-shorthand-cssom-replacement.html
index a25fe026254..cc01a3aea55 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/substitution-shorthand-cssom-replacement.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/substitution-shorthand-cssom-replacement.html
@@ -12,12 +12,9 @@
let style = getComputedStyle(target);
println(`missing substitution clears every longhand: ${style.marginTop === "0px" && style.marginRight === "0px" && style.marginBottom === "0px" && style.marginLeft === "0px"}`);
- const countersBefore = internals.styleEngineCounters();
target.style.margin = "var(--spacing) 6px 7px 8px";
internals.updateStyle();
style = getComputedStyle(target);
- const countersAfter = internals.styleEngineCounters();
- println(`engine substituted shorthand replacements: ${countersAfter.engineComputedRecordSubstitutions > countersBefore.engineComputedRecordSubstitutions}`);
println(`replacement updates every longhand: ${style.marginTop === "5px" && style.marginRight === "6px" && style.marginBottom === "7px" && style.marginLeft === "8px"}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/svg-image-resource-arrival.html b/Tests/LibWeb/Text/input/css/style-engine/svg-image-resource-arrival.html
index 96ebc802c6a..e2d8780a053 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/svg-image-resource-arrival.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/svg-image-resource-arrival.html
@@ -6,18 +6,15 @@
</svg>
<script>
// An SVG image's resource arriving moves no style declaration: layout sizes the <image> from
- // its replaced content, and an <feImage> repaints through the SVG paint resources. Count the
- // style computations the arrival causes, and check the image is sized from what arrived.
+ // its replaced content, and an <feImage> repaints through the SVG paint resources. Check the
+ // image is sized from what arrived.
promiseTest(async () => {
const loaded = new Promise(resolve => image.addEventListener("load", resolve));
fe.setAttribute("href", "../../../../Assets/120.png");
image.setAttribute("href", "../../../../Assets/120.png");
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
await loaded;
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);
println(`image width: ${image.getBoundingClientRect().width}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/svg-presentation-attribute-engine-records.html b/Tests/LibWeb/Text/input/css/style-engine/svg-presentation-attribute-engine-records.html
index 7fca55c0ba4..06a59ec21e8 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/svg-presentation-attribute-engine-records.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/svg-presentation-attribute-engine-records.html
@@ -17,12 +17,9 @@
function measure(label, mutate, rect) {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
rect = mutate(rect);
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
const style = getComputedStyle(rect);
- println(`${label}: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords} engine records, ${after.elementStyleRecomputations - before.elementStyleRecomputations} C++ recomputations`);
println(`${label}: x ${style.x}, fill ${style.fill}, width ${style.width}`);
return rect;
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/synthetic-pseudo-element-reads.html b/Tests/LibWeb/Text/input/css/style-engine/synthetic-pseudo-element-reads.html
index 5732b63515f..af4f967ea1b 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/synthetic-pseudo-element-reads.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/synthetic-pseudo-element-reads.html
@@ -11,11 +11,8 @@
// no selection makes it observable, and ::first-line and ::view-transition, which no style
// update settles.
const read = (element, pseudo) => {
- const start = internals.styleEngineCounters();
const style = getComputedStyle(element, pseudo);
- const values = `color ${style.color}, background-color ${style.backgroundColor}`;
- const end = internals.styleEngineCounters();
- println(`${element.id}${pseudo}: ${values}, demands left to the host ${end.pseudoRecordDemandsLeftToHost - start.pseudoRecordDemandsLeftToHost}`);
+ println(`${element.id}${pseudo}: color ${style.color}, background-color ${style.backgroundColor}`);
};
internals.updateStyle();
// The rules come after the last style update settled the elements, which leaves the
diff --git a/Tests/LibWeb/Text/input/css/style-engine/targeted-direct-read-uses-reaction-batch.html b/Tests/LibWeb/Text/input/css/style-engine/targeted-direct-read-uses-reaction-batch.html
deleted file mode 100644
index d1f68fb584d..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/targeted-direct-read-uses-reaction-batch.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- #target.before { color: red; }
- #target.after { color: green; }
-</style>
-<div id="target" class="before"></div>
-<script>
- test(() => {
- const target = document.getElementById("target");
- internals.updateStyle();
-
- internals.resetStyleInvalidationCounters();
- target.className = "after";
- println("color: " + target.computedStyleMap().get("color"));
-
- const counters = internals.getStyleInvalidationCounters();
- println("reaction batch runs: " + counters.styleEngineReactionBatchRuns);
- println("reaction elements: " + counters.styleEngineReactionElements);
- println("published reactions: " + counters.styleEnginePublishedReactions);
- println("recomputations: " + counters.elementStyleRecomputations);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/targeted-read-uses-reaction-batch.html b/Tests/LibWeb/Text/input/css/style-engine/targeted-read-uses-reaction-batch.html
deleted file mode 100644
index 32a27e302f7..00000000000
--- a/Tests/LibWeb/Text/input/css/style-engine/targeted-read-uses-reaction-batch.html
+++ /dev/null
@@ -1,23 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- #target.before { color: red; }
- #target.after { color: green; }
-</style>
-<div id="target" class="before"></div>
-<script>
- test(() => {
- const target = document.getElementById("target");
- internals.updateStyle();
-
- internals.resetStyleInvalidationCounters();
- target.className = "after";
- println("color: " + getComputedStyle(target).color);
-
- const counters = internals.getStyleInvalidationCounters();
- println("reaction batch runs: " + counters.styleEngineReactionBatchRuns);
- println("reaction elements: " + counters.styleEngineReactionElements);
- println("published reactions: " + counters.styleEnginePublishedReactions);
- println("recomputations: " + counters.elementStyleRecomputations);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/top-layer-state-does-not-dirty-style.html b/Tests/LibWeb/Text/input/css/style-engine/top-layer-state-does-not-dirty-style.html
index ab652fc8f64..76acb4b43bb 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/top-layer-state-does-not-dirty-style.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/top-layer-state-does-not-dirty-style.html
@@ -10,31 +10,20 @@
const popover = document.getElementById("popover");
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
+ internals.resetStyleCounters();
popover.showPopover();
internals.updateStyle();
- const shownUpdateCounters = internals.getStyleInvalidationCounters();
- const shownColor = getComputedStyle(popover).color;
- const shownReadCounters = internals.getStyleInvalidationCounters();
+ println(`shown styled: ${internals.styleLastPass().styled}`);
+ internals.resetStyleCounters();
+ println("shown color: " + getComputedStyle(popover).color);
+ println(`shown read styled: ${internals.styleCounters().styledElements}`);
+ internals.resetStyleCounters();
popover.hidePopover();
internals.updateStyle();
- const hiddenUpdateCounters = internals.getStyleInvalidationCounters();
- const hiddenColor = getComputedStyle(popover).color;
- const hiddenReadCounters = internals.getStyleInvalidationCounters();
-
- println("shown color: " + shownColor);
- println("shown reaction batch runs: " + shownUpdateCounters.styleEngineReactionBatchRuns);
- println("shown reaction elements: " + shownUpdateCounters.styleEngineReactionElements);
- println("shown published reactions: " + shownUpdateCounters.styleEnginePublishedReactions);
- println("shown recomputations: " + shownUpdateCounters.elementStyleRecomputations);
- println("shown read recomputations: " + (shownReadCounters.elementStyleRecomputations - shownUpdateCounters.elementStyleRecomputations));
- println("hidden color: " + hiddenColor);
- println("hidden reaction batch runs: " + (hiddenUpdateCounters.styleEngineReactionBatchRuns - shownReadCounters.styleEngineReactionBatchRuns));
- println("hidden reaction elements: " + (hiddenUpdateCounters.styleEngineReactionElements - shownReadCounters.styleEngineReactionElements));
- println("hidden published reactions: " + (hiddenUpdateCounters.styleEnginePublishedReactions - shownReadCounters.styleEnginePublishedReactions));
- // Record verification can materialize the hidden style before this reaction.
- println("hidden recomputations within budget: " + (hiddenUpdateCounters.elementStyleRecomputations - shownReadCounters.elementStyleRecomputations <= 1));
- println("hidden read recomputations: " + (hiddenReadCounters.elementStyleRecomputations - hiddenUpdateCounters.elementStyleRecomputations));
+ println(`hidden styled: ${internals.styleLastPass().styled}`);
+ internals.resetStyleCounters();
+ println("hidden color: " + getComputedStyle(popover).color);
+ println(`hidden read styled: ${internals.styleCounters().styledElements}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/transition-definition-computed-closure.html b/Tests/LibWeb/Text/input/css/style-engine/transition-definition-computed-closure.html
index 62da3fe62f4..4c41d0760ae 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/transition-definition-computed-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/transition-definition-computed-closure.html
@@ -17,11 +17,8 @@
sheet.replaceSync("#container, #container > div { transition: none !important; }");
function mutate(label, mutation) {
- const before = internals.getStyleInvalidationCounters();
mutation();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label} unrelated longhands skipped: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations < 1200}`);
println(`${label} transition: ${getComputedStyle(container.firstElementChild).transitionDuration}`);
println(`${label} color: ${getComputedStyle(container.firstElementChild).color}`);
}
diff --git a/Tests/LibWeb/Text/input/css/style-engine/transition-fallback-keeps-partial-builds.html b/Tests/LibWeb/Text/input/css/style-engine/transition-fallback-keeps-partial-builds.html
index 5b820ac760c..719b3ea03fb 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/transition-fallback-keeps-partial-builds.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/transition-fallback-keeps-partial-builds.html
@@ -15,14 +15,10 @@
internals.updateStyle();
}
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
for (const item of host.children) {
item.classList.add("changed");
internals.updateStyle();
}
- const counters = internals.getStyleInvalidationCounters();
- println(`partial builds: ${counters.baseStylePartialBuilds}`);
- println(`full builds: ${counters.baseStyleFullBuilds}`);
for (const animation of document.getAnimations())
animation.finish();
internals.updateStyle();
diff --git a/Tests/LibWeb/Text/input/css/style-engine/transition-partial-drive.html b/Tests/LibWeb/Text/input/css/style-engine/transition-partial-drive.html
index 7ffe926ec18..c5275b993ac 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/transition-partial-drive.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/transition-partial-drive.html
@@ -17,12 +17,8 @@
const labels = [...list.querySelectorAll("label")];
function mutate(label, mutation) {
- const before = internals.getStyleInvalidationCounters();
mutation();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`${label} full builds: ${after.baseStyleFullBuilds - before.baseStyleFullBuilds}`);
- println(`${label} longhand drive bounded: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations < 4000}`);
}
mutate("complete", () => { for (const item of list.children) item.classList.add("completed"); });
@@ -35,10 +31,7 @@
println(`midpoint color: ${getComputedStyle(labels[0]).color}`);
println(`midpoint text-decoration-line: ${getComputedStyle(labels[0]).textDecorationLine}`);
- const before = internals.styleEngineCounters();
mutate("recompute mid-transition", () => { for (const label of labels) label.classList.add("padded"); });
- const after = internals.styleEngineCounters();
- println(`mid-transition avoids full drives: ${after.engineFullDrivesStarted === before.engineFullDrivesStarted}`);
println(`running transition kept: ${labels.every(label => label.getAnimations().length === 1)}`);
println(`running color: ${getComputedStyle(labels[0]).color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/transition-row-moves-display.html b/Tests/LibWeb/Text/input/css/style-engine/transition-row-moves-display.html
index 33e821e1e8b..1e11601ef9b 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/transition-row-moves-display.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/transition-row-moves-display.html
@@ -10,12 +10,10 @@
const target = document.getElementById("target");
const measure = (label, mutation) => {
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
mutation();
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
const animations = target.getAnimations().map(animation => animation.transitionProperty).sort().join(",");
- println(`${label}: C++ recomputations ${after.elementStyleRecomputations - before.elementStyleRecomputations}, display ${getComputedStyle(target).display}, transitions ${animations}`);
+ println(`${label}: display ${getComputedStyle(target).display}, transitions ${animations}`);
};
target.firstChild.remove();
// The class change moves display beside a value a transition runs on: the display
diff --git a/Tests/LibWeb/Text/input/css/style-engine/transition-step-row-with-children-settles-in-engine.html b/Tests/LibWeb/Text/input/css/style-engine/transition-step-row-with-children-settles-in-engine.html
index f63e2eb48a0..793f3d590dd 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/transition-step-row-with-children-settles-in-engine.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/transition-step-row-with-children-settles-in-engine.html
@@ -12,12 +12,10 @@
const inner = document.querySelector(".inner");
const plain = document.querySelector(".plain");
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters().elementStyleRecomputations;
// The row owing the step has element children: they read the values the step started from,
// and a child declaring its own transition starts it towards the parent's after-change value.
outer.classList.add("green");
internals.updateStyle();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - before}`);
println(`outer: ${getComputedStyle(outer).color}, transitions ${outer.getAnimations().length}`);
println(`inner: ${getComputedStyle(inner).color}, transitions ${inner.getAnimations().length}`);
println(`plain: ${getComputedStyle(plain).color}, transitions ${plain.getAnimations().length}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/transition-underlying-style-delta.html b/Tests/LibWeb/Text/input/css/style-engine/transition-underlying-style-delta.html
index 6ed2ee10448..678850c8188 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/transition-underlying-style-delta.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/transition-underlying-style-delta.html
@@ -26,11 +26,8 @@
animation.currentTime = 500000;
}
internals.updateStyle();
- const before = internals.styleEngineCounters();
target.style.backgroundColor = "red";
internals.updateStyle();
- const after = internals.styleEngineCounters();
- println(`base change takes partial drive: ${after.enginePartialDrivesStarted > before.enginePartialDrivesStarted}`);
println(`transition objects survive: ${target.getAnimations().every(animation => animations.includes(animation))}`);
println(`transition color: ${getComputedStyle(target).color}`);
println(`transition opacity: ${getComputedStyle(target).opacity}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/uncached-record-gains-animation.html b/Tests/LibWeb/Text/input/css/style-engine/uncached-record-gains-animation.html
index eb34d8fd348..e8ea1405476 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/uncached-record-gains-animation.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/uncached-record-gains-animation.html
@@ -11,10 +11,8 @@
// cache. A rule that gives it an animation-name still starts the animation.
const target = document.getElementById("target");
internals.updateStyle();
- const startRecomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
target.classList.add("animated");
internals.updateStyle();
- println(`C++ recomputations: ${internals.getStyleInvalidationCounters().elementStyleRecomputations - startRecomputations}`);
println(`animation-name: ${getComputedStyle(target).animationName}`);
println(`animations: ${target.getAnimations().length}`);
println(`height: ${getComputedStyle(target).height}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/unchanged-variable-environment-computed-closure.html b/Tests/LibWeb/Text/input/css/style-engine/unchanged-variable-environment-computed-closure.html
index f66fe3c554a..2ba0a671df5 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/unchanged-variable-environment-computed-closure.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/unchanged-variable-environment-computed-closure.html
@@ -11,11 +11,8 @@
const parent = document.getElementById("parent");
const target = document.getElementById("target");
internals.updateStyle();
- const before = internals.getStyleInvalidationCounters();
target.className = "dimmed";
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters();
- println(`unrelated longhands skipped: ${after.computedLonghandEvaluations - before.computedLonghandEvaluations < 50}`);
println(`opacity: ${getComputedStyle(target).opacity}`);
println(`margin: ${getComputedStyle(target).marginLeft}`);
println(`color: ${getComputedStyle(target).color}`);
diff --git a/Tests/LibWeb/Text/input/css/style-engine/unchanged-winners-after-viewport-environment-change.html b/Tests/LibWeb/Text/input/css/style-engine/unchanged-winners-after-viewport-environment-change.html
index 45fdc11f8af..f24412584f7 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/unchanged-winners-after-viewport-environment-change.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/unchanged-winners-after-viewport-environment-change.html
@@ -24,8 +24,6 @@
const target = child.document.getElementById("target");
const fixed = child.document.getElementById("fixed");
println(`initial width: ${child.getComputedStyle(target).width}`);
- const before = child.internals.styleEngineCounters();
- const recomputationsBefore = child.internals.getStyleInvalidationCounters().elementStyleRecomputations;
// The registered initial value requests a document environment update even
// though neither element substitutes it into a winning declaration.
@@ -35,8 +33,5 @@
println(`resized width: ${child.getComputedStyle(target).width}`);
println(`font-relative height: ${child.getComputedStyle(target).height}`);
println(`fixed width: ${child.getComputedStyle(fixed).width}`);
- const after = child.internals.styleEngineCounters();
- println(`C++ recomputations: ${child.internals.getStyleInvalidationCounters().elementStyleRecomputations - recomputationsBefore}`);
- println(`engine answered: ${after.engineComputedRecordDeltas > before.engineComputedRecordDeltas}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/unfocused-subject-skips-descendants.html b/Tests/LibWeb/Text/input/css/style-engine/unfocused-subject-skips-descendants.html
index 4e0af958cb9..bd18b3d8db5 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/unfocused-subject-skips-descendants.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/unfocused-subject-skips-descendants.html
@@ -18,25 +18,24 @@
list.appendChild(item);
}
const probe = list.children[3].firstChild.children[2];
- getComputedStyle(probe).color;
+ internals.updateStyle();
- internals.resetStyleInvalidationCounters();
+ internals.resetStyleCounters();
for (const item of list.children)
item.classList.add("completed");
println(`unfocused probe: ${getComputedStyle(probe).color}`);
- let counters = internals.getStyleInvalidationCounters();
- println(`recomputes with no focused element: ${counters.elementStyleRecomputations}`);
+ println(`styled with no focused element: ${internals.styleCounters().styledElements}`);
for (const item of list.children)
item.classList.remove("completed");
probe.focus();
getComputedStyle(probe).color;
- internals.resetStyleInvalidationCounters();
+ internals.resetStyleCounters();
for (const item of list.children)
item.classList.add("completed");
println(`focused probe: ${getComputedStyle(probe).color}`);
- counters = internals.getStyleInvalidationCounters();
- println(`recomputes with one focused element: ${counters.elementStyleRecomputations}`);
+ // The focused probe restyles with the elements of its user-agent shadow tree, which inherit its color.
+ println(`styled with one focused element: ${internals.styleCounters().styledElements}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-engine/unstyled-hidden-descendants.html b/Tests/LibWeb/Text/input/css/style-engine/unstyled-hidden-descendants.html
index b98387623d6..d3d03df7af3 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/unstyled-hidden-descendants.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/unstyled-hidden-descendants.html
@@ -14,11 +14,8 @@ test(() => {
child.className = 'child';
host.append(child);
}
- const before = internals.getStyleInvalidationCounters().elementStyleRecomputations;
document.body.append(host);
internals.updateStyle();
- const after = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- println(`hidden children deferred: ${after - before < 100}`);
const child = host.lastElementChild;
println(`targeted hidden read: ${getComputedStyle(child).width}, ${getComputedStyle(child).color}`);
child.style.width = '59px';
diff --git a/Tests/LibWeb/Text/input/css/style-engine/warm-prefix-cache-is-not-bypassed.html b/Tests/LibWeb/Text/input/css/style-engine/warm-prefix-cache-is-not-bypassed.html
index 7768b1dc820..d2ecff06cde 100644
--- a/Tests/LibWeb/Text/input/css/style-engine/warm-prefix-cache-is-not-bypassed.html
+++ b/Tests/LibWeb/Text/input/css/style-engine/warm-prefix-cache-is-not-bypassed.html
@@ -12,13 +12,9 @@
root.lastElementChild.className = "rare";
internals.updateStyle();
- const before = internals.styleEngineCounters();
root.classList.add("guard");
internals.updateStyle();
- const after = internals.styleEngineCounters();
println(`rare subject updated: ${getComputedStyle(root.lastElementChild).color}`);
- println(`prefix convergence bypassed: ${after.prefixConvergenceBypasses > before.prefixConvergenceBypasses}`);
- println(`prefix convergence maintained: ${after.prefixConvergencePasses > before.prefixConvergencePasses}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/style-graph-cold-matching.html b/Tests/LibWeb/Text/input/css/style-graph-cold-matching.html
deleted file mode 100644
index 060bdf7a8d8..00000000000
--- a/Tests/LibWeb/Text/input/css/style-graph-cold-matching.html
+++ /dev/null
@@ -1,37 +0,0 @@
-<!DOCTYPE html>
-<script src="../include.js"></script>
-<style>
- .item { color: red }
- .theme .item { color: green }
- #target { color: blue }
- span { color: teal }
- div > .item:first-child { color: olive }
-</style>
-<div class="theme">
- <div class="item" id="target">a</div>
- <div class="item">b</div>
- <span>c</span>
-</div>
-<script>
- test(() => {
- document.body.offsetWidth;
-
- // The cold path runs over the real document: no witness, no signature, no winner group,
- // just facts and the attached program.
- const matches = internals.styleEngineMatchDocument();
- println(`cold matching completed: ${matches >= 0}`);
-
- // .item matches twice, .theme .item twice, #target once, span once, and the first-child
- // rule once. The user-agent sheet is part of the program too, so the total is larger than
- // those seven and not worth pinning to a number that every user-agent rule would move.
- println(`concrete matches cover the author rules: ${matches >= 7}`);
-
- // Dispatch means a candidate only considers the rules its own features reach, so the
- // checks stay far below one per rule per element.
- const c = internals.styleEngineCounters();
- println(`checks below the product of nodes and rules: ${c.candidateChecks < c.coldNodesEvaluated * c.styleRulesCompiled}`);
-
- // Running it again is stable.
- println(`stable across passes: ${internals.styleEngineMatchDocument() === matches}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-graph-compiles-selectors.html b/Tests/LibWeb/Text/input/css/style-graph-compiles-selectors.html
deleted file mode 100644
index b6f19f36fb7..00000000000
--- a/Tests/LibWeb/Text/input/css/style-graph-compiles-selectors.html
+++ /dev/null
@@ -1,39 +0,0 @@
-<!DOCTYPE html>
-<script src="../include.js"></script>
-<style>
- .item { color: red }
- .theme .item { color: green }
- div > span.a#b[data-x="1"] { color: blue }
- li:nth-child(2n+1), li:nth-last-of-type(3) { color: teal }
- a:hover, a:focus, a:visited, a:any-link, a:local-link { color: purple }
- input:checked, input:enabled, input:disabled, input:required, input:optional { color: gray }
- input:read-only, input:read-write, input:indeterminate, input:default { color: gray }
- input:in-range, input:out-of-range, input:user-valid, input:user-invalid { color: gray }
- video:playing, video:paused, video:muted, video:seeking, video:buffering, video:stalled { color: gray }
- dialog:modal, :fullscreen, :defined, :autofill, :popover-open { color: gray }
- :root, :empty, :scope { color: gray }
- p:dir(rtl), p:lang(en-GB), p:heading(1,2) { color: gray }
- .card:has(> .error) { color: olive }
- :is(.x, .y) .z, :where(.p) .q, :not(.r) { color: navy }
- p::before, p::after, p::marker, p::first-line { content: "" }
- *|div, td { color: black }
-</style>
-<script>
- test(() => {
- // The counters cover every sheet the document's program holds, user-agent ones included,
- // and those are attached at the first style flush. Read them before that and the answer
- // depends on whether a paint happened to have run.
- internals.updateStyle();
-
- const c = internals.styleEngineCounters();
- // Every category of unhandled selector construct must be empty. A construct with no
- // mapping compiles to something the engine cannot route, and a selector that cannot be
- // routed cannot be invalidated.
- println(`unsupported pseudo-classes: ${c.unsupportedPseudoClass}`);
- println(`uninterned names: ${c.unsupportedUninternedName}`);
- println(`malformed: ${c.unsupportedMalformed}`);
- println(`unsupported combinators: ${c.unsupportedCombinator}`);
- println(`unsupported pseudo-elements: ${c.unsupportedPseudoElement}`);
- println(`exact entries: ${c.exactSelectorEntries > 40}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-graph-element-facts.html b/Tests/LibWeb/Text/input/css/style-graph-element-facts.html
deleted file mode 100644
index be9ffb9c012..00000000000
--- a/Tests/LibWeb/Text/input/css/style-graph-element-facts.html
+++ /dev/null
@@ -1,22 +0,0 @@
-<!DOCTYPE html>
-<script src="../include.js"></script>
-<div id="outer" class="a b" data-x="1"><span class="c"></span></div>
-<script>
- test(() => {
- const before = internals.styleEngineCounters();
-
- // An element arriving with facts already true of it publishes them as ordinary deltas.
- const added = document.createElement("p");
- added.id = "added";
- added.className = "d e";
- added.setAttribute("data-y", "2");
- document.body.appendChild(added);
- document.body.offsetWidth;
-
- const after = internals.styleEngineCounters();
- // tag + id + two classes + two attributes, at least.
- println(`initial facts published: ${after.localFeatureDeltas - before.localFeatureDeltas >= 6}`);
- println(`no scope markers: ${after.coarsenedScopeMarkers === 0}`);
- println(`tree delta recorded: ${after.treeDeltas > before.treeDeltas}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-graph-host-guard-routing.html b/Tests/LibWeb/Text/input/css/style-graph-host-guard-routing.html
deleted file mode 100644
index b6909e8a28f..00000000000
--- a/Tests/LibWeb/Text/input/css/style-graph-host-guard-routing.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<script src="../include.js"></script>
-<div id="host" tabindex="0"></div>
-<script>
- test(() => {
- const host = document.getElementById("host");
- const shadowRoot = host.attachShadow({ mode: "open" });
- shadowRoot.innerHTML = "<style>:host(:focus) { color: green }</style><span id=child></span>";
- document.body.offsetWidth;
- internals.styleEngineTransactionReactions();
-
- // `:host()` is a guard on the host, not a combinator: it styles the element it tests. A
- // change to what it tests reaches that element, and nothing in the tree it hosts.
- host.focus({ preventScroll: true });
- const plan = internals.styleEngineTransactionReactions();
- println(`plan: wholeDocument=${plan.wholeDocument} elements=${plan.elements.join(",")}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-graph-incremental-sheet-edits.html b/Tests/LibWeb/Text/input/css/style-graph-incremental-sheet-edits.html
deleted file mode 100644
index 42b8610c5fb..00000000000
--- a/Tests/LibWeb/Text/input/css/style-graph-incremental-sheet-edits.html
+++ /dev/null
@@ -1,89 +0,0 @@
-<!DOCTYPE html>
-<script src="../include.js"></script>
-<style id="sheet">
- #target { --a: 1 }
- #target { --b: 1 }
- #target { --c: 1 }
- #target { --d: 1 }
-</style>
-<div id="target" tabindex="0"></div>
-<script>
- const sheet = document.getElementById("sheet").sheet;
- const target = document.getElementById("target");
-
- function compiledBy(name, mutate) {
- const before = internals.styleEngineCounters().styleRulesCompiled;
- mutate();
- // Reading a value flushes, so the count covers the whole edit and not just the call.
- getComputedStyle(target).getPropertyValue("--a");
- println(`${name}: ${internals.styleEngineCounters().styleRulesCompiled - before} compiled`);
- }
-
- function colour() {
- return getComputedStyle(target).color;
- }
-
- test(() => {
- // The first CSSOM edit recompiles shared contents into a private stylesheet. Insert and remove
- // a dummy rule before measuring, so the counters cover only subsequent incremental edits.
- sheet.insertRule(":not(*) {}", 0);
- sheet.deleteRule(0);
-
- document.body.offsetWidth;
-
- // One rule arriving is one rule compiled, wherever it lands. The rules around it keep their
- // identities and their order tokens, so none of them is compiled again.
- compiledBy("insert at the front", () => sheet.insertRule("#target:focus { color: rgb(1, 1, 1) }", 0));
- compiledBy("insert in the middle", () => sheet.insertRule("#target:focus { color: rgb(2, 2, 2) }", 2));
- compiledBy("insert at the end", () => sheet.insertRule("#target:focus { color: rgb(3, 3, 3) }", sheet.cssRules.length));
-
- // Each landed where it was asked to, so the last one wins on equal specificity.
- target.focus();
- println(`after three inserts: ${colour()}`);
-
- // Deleting one rule compiles nothing, and the rule behind it takes over.
- compiledBy("delete the winner", () => sheet.deleteRule(sheet.cssRules.length - 1));
- println(`after deleting the winner: ${colour()}`);
-
- // Retargeting a rule is that one rule changing. Its position is untouched, so it still
- // cascades where it did.
- compiledBy("retarget one rule", () => { sheet.cssRules[2].selectorText = "#target:focus, .unrelated"; });
- println(`after retargeting: ${colour()}`);
-
- // A group arriving brings its own rules and nothing else.
- compiledBy("insert a group of two", () => sheet.insertRule("@media all { #target:focus { color: rgb(4, 4, 4) } #target:focus { color: rgb(5, 5, 5) } }", sheet.cssRules.length));
- println(`after the group: ${colour()}`);
-
- // Deleting the group takes its rules with it, and compiles nothing.
- compiledBy("delete the group", () => sheet.deleteRule(sheet.cssRules.length - 1));
- println(`after deleting the group: ${colour()}`);
-
- // Editing every rule in turn costs one compile per rule, not one per rule per edit.
- const count = sheet.cssRules.length;
- compiledBy(`retarget all ${count} rules`, () => {
- for (let index = 0; index < count; ++index)
- sheet.cssRules[index].selectorText = `#target:focus, .all-${index}`;
- });
- println(`after retargeting all: ${colour()}`);
-
- // Deleting every rule in turn compiles nothing at all.
- compiledBy(`delete all ${count} rules`, () => {
- while (sheet.cssRules.length > 0)
- sheet.deleteRule(sheet.cssRules.length - 1);
- });
- println(`after deleting all: ${colour()}`);
-
- // `replace()` is the one edit that is not incremental, because it swaps the whole rule
- // list. It compiles what it was given and nothing more.
- const constructed = new CSSStyleSheet();
- document.adoptedStyleSheets = [constructed];
- compiledBy("replaceSync with three rules", () => {
- constructed.replaceSync("#target:focus { color: rgb(6, 6, 6) } .x { color: red } .y { color: red }");
- });
- println(`after replaceSync: ${colour()}`);
- compiledBy("replaceSync with one rule", () => {
- constructed.replaceSync("#target:focus { color: rgb(7, 7, 7) }");
- });
- println(`after the second replaceSync: ${colour()}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-graph-normalizes-input.html b/Tests/LibWeb/Text/input/css/style-graph-normalizes-input.html
deleted file mode 100644
index d69f3ebe2bb..00000000000
--- a/Tests/LibWeb/Text/input/css/style-graph-normalizes-input.html
+++ /dev/null
@@ -1,51 +0,0 @@
-<!DOCTYPE html>
-<script src="../include.js"></script>
-<div id="host"></div>
-<div id="settled"></div>
-<script>
- test(() => {
- // Settle first: the counters straddle a transaction boundary otherwise, and entries
- // journalled before the snapshot drain inside the window and are counted as normalized
- // keys with no raw record to match.
- internals.updateStyle();
- const before = internals.styleEngineCounters();
- println(`initial tree used one bulk load: ${before.initialBulkLoads === 1}`);
- println(`initial bulk load installed every connected element: ${before.initialBulkTreeRows >= 4}`);
- println(`initial matching used one bulk load: ${before.initialBulkMatchLoads === 1}`);
- println(`initial matching published every connected element: ${before.initialBulkMatchRows === before.initialBulkTreeRows}`);
-
- const host = document.getElementById("host");
- const added = document.createElement("div");
- added.className = "item";
- host.appendChild(added);
-
- // A class added and removed again before anything observes style cancels out entirely. It
- // has to be asked of an element that was already there: a fact published while the element
- // it is about is still arriving is folded onto the arrival instead of journalled.
- const settled = document.getElementById("settled");
- settled.classList.add("transient");
- settled.classList.remove("transient");
-
- // A node inserted and removed again before anything observes style never reaches the
- // engine at all: it takes no identity, so it records neither an arrival nor a departure.
- const temporary = document.createElement("span");
- host.appendChild(temporary);
- host.removeChild(temporary);
-
- // Force the transaction boundary.
- document.body.offsetWidth;
-
- const after = internals.styleEngineCounters();
- const raw = after.rawMutationRecords - before.rawMutationRecords;
- const normalized = after.normalizedUniqueKeys - before.normalizedUniqueKeys;
- const cancellations = after.journalCancellations - before.journalCancellations;
-
- println(`recorded more raw mutations than normalized keys: ${raw > normalized}`);
- println(`cancellations: ${cancellations >= 1}`);
- println(`tree deltas recorded: ${after.treeDeltas > before.treeDeltas}`);
- println(`feature deltas recorded: ${after.localFeatureDeltas > before.localFeatureDeltas}`);
- println(`style nodes allocated: ${after.styleNodesAllocated > before.styleNodesAllocated}`);
- println(`no scope markers: ${after.coarsenedScopeMarkers === 0}`);
- println(`an arriving element's facts folded onto its arrival: ${after.arrivingNodeFactsFolded > before.arrivingNodeFactsFolded}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-graph-program-deltas.html b/Tests/LibWeb/Text/input/css/style-graph-program-deltas.html
deleted file mode 100644
index 7b305f6a313..00000000000
--- a/Tests/LibWeb/Text/input/css/style-graph-program-deltas.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!DOCTYPE html>
-<script src="../include.js"></script>
-<style id="first">.a { color: red }</style>
-<script>
- test(() => {
- const before = internals.styleEngineCounters();
-
- // Inserting a sheet between two existing ones names its successor; the engine writes one
- // order token and renumbers nothing.
- const middle = document.createElement("style");
- middle.textContent = ".b { color: green }";
- document.head.insertBefore(middle, null);
-
- const last = document.createElement("style");
- last.textContent = ".c { color: blue }";
- document.head.appendChild(last);
-
- document.body.offsetWidth;
- const afterAdd = internals.styleEngineCounters();
-
- middle.remove();
- document.body.offsetWidth;
- const afterRemove = internals.styleEngineCounters();
-
- println(`attaching records program deltas: ${afterAdd.programDeltas > before.programDeltas}`);
- println(`detaching records more: ${afterRemove.programDeltas > afterAdd.programDeltas}`);
- println(`no scope markers: ${afterRemove.coarsenedScopeMarkers === 0}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-graph-state-facts.html b/Tests/LibWeb/Text/input/css/style-graph-state-facts.html
deleted file mode 100644
index 79e6d0b7bd7..00000000000
--- a/Tests/LibWeb/Text/input/css/style-graph-state-facts.html
+++ /dev/null
@@ -1,24 +0,0 @@
-<!DOCTYPE html>
-<script src="../include.js"></script>
-<div id="outer"><input id="target" type="checkbox"></div>
-<script>
- test(() => {
- const target = document.getElementById("target");
- document.body.offsetWidth;
-
- // Focus moves between nodes, so the invalidator visits exactly the elements whose fact
- // changed: the one that gains it, and the one that loses it.
- const before = internals.styleEngineCounters();
- target.focus();
- document.body.offsetWidth;
- const afterFocus = internals.styleEngineCounters();
-
- target.blur();
- document.body.offsetWidth;
- const afterBlur = internals.styleEngineCounters();
-
- println(`focusing records a state fact: ${afterFocus.stateDeltas > before.stateDeltas}`);
- println(`blurring records another: ${afterBlur.stateDeltas > afterFocus.stateDeltas}`);
- println(`no scope markers: ${afterBlur.coarsenedScopeMarkers === 0}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-invalidation/computed-style-read-consumes-complete-reaction-batch.html b/Tests/LibWeb/Text/input/css/style-invalidation/computed-style-read-consumes-complete-reaction-batch.html
deleted file mode 100644
index 53f9a995d1a..00000000000
--- a/Tests/LibWeb/Text/input/css/style-invalidation/computed-style-read-consumes-complete-reaction-batch.html
+++ /dev/null
@@ -1,38 +0,0 @@
-<!DOCTYPE html>
-<script src="../../include.js"></script>
-<style>
- .context .target {
- color: rgb(12, 34, 56);
- }
-
- .unrelated {
- color: rgb(65, 43, 21);
- }
-</style>
-<div id="unrelated"></div>
-<div class="context">
- <div><span class="target">target</span></div>
-</div>
-<script>
- test(() => {
- const unrelated = document.getElementById("unrelated");
- for (let i = 0; i < 100; ++i) {
- const child = document.createElement("span");
- child.className = "unrelated";
- unrelated.appendChild(child);
- }
-
- // A new element's style is either recomputed by C++ or derived as a record by the style engine.
- const styledElements = () => internals.getStyleInvalidationCounters().elementStyleRecomputations
- + (internals.styleEngineCounters().engineComputedRecordDeltas ?? 0);
- internals.resetStyleInvalidationCounters();
- const styledElementsBeforeRead = styledElements();
- println(`target color: ${getComputedStyle(document.querySelector(".target")).color}`);
- const styledElementsAfterTargetRead = styledElements();
- println(`unrelated color: ${getComputedStyle(unrelated.firstChild).color}`);
- const styledElementsAfterUnrelatedRead = styledElements();
- const completeBatchWasConsumed = styledElementsAfterTargetRead - styledElementsBeforeRead >= 100
- && styledElementsAfterUnrelatedRead === styledElementsAfterTargetRead;
- println(`PASS: the first style read consumed the complete reaction batch: ${completeBatchWasConsumed}`);
- });
-</script>
diff --git a/Tests/LibWeb/Text/input/css/style-invalidation/read-write-follows-inertness.html b/Tests/LibWeb/Text/input/css/style-invalidation/read-write-follows-inertness.html
new file mode 100644
index 00000000000..7a040b19993
--- /dev/null
+++ b/Tests/LibWeb/Text/input/css/style-invalidation/read-write-follows-inertness.html
@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<style>
+ span { color: blue }
+ span:read-write { color: green }
+</style>
+<div id="outer">
+ <div id="host" contenteditable>
+ <span id="subject"></span>
+ </div>
+</div>
+<script>
+ test(() => {
+ const subject = document.getElementById("subject");
+ const report = label => println(label + ": matches " + subject.matches(":read-write") + ", " + getComputedStyle(subject).color);
+ report("editable");
+
+ outer.inert = true;
+ report("under an inert ancestor");
+
+ outer.inert = false;
+ report("no longer inert");
+
+ subject.remove();
+ host.inert = true;
+ host.append(subject);
+ report("inserted under an inert parent");
+
+ subject.remove();
+ host.inert = false;
+ host.append(subject);
+ report("inserted again");
+
+ const parent = document.createElement("div");
+ parent.append(subject);
+ host.append(parent);
+ host.inert = true;
+ parent.remove();
+ host.inert = false;
+ host.append(parent);
+ report("removed while inert and inserted again");
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/css/style-sharing-across-shadow-roots-with-same-font.html b/Tests/LibWeb/Text/input/css/style-sharing-across-shadow-roots-with-same-font.html
index b1dad8d98fe..f03037c8c7b 100644
--- a/Tests/LibWeb/Text/input/css/style-sharing-across-shadow-roots-with-same-font.html
+++ b/Tests/LibWeb/Text/input/css/style-sharing-across-shadow-roots-with-same-font.html
@@ -14,12 +14,17 @@ test(() => {
// trees added after the first one is styled can take their styles from it.
addShadowTree();
document.body.offsetWidth;
- const before = internals.styleEngineCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
for (let i = 0; i < 20; ++i)
addShadowTree();
document.body.offsetWidth;
- const after = internals.styleEngineCounters();
- println(`full drives for 20 more shadow trees: ${after.engineFullDrivesStarted - before.engineFullDrivesStarted}`);
+ const after = internals.styleCounters();
+ println(`full passes for 20 more shadow trees: ${after.fullPasses}`);
+ // FIXME: The paragraphs and spans of the 20 trees added after the first should take their records
+ // from the first tree's, so that at least 60 elements are shared, but the style engine shares records
+ // only within a shadow tree, whose rules come from a sheet of its own.
+ println(`shared elements: ${after.sharedElements}`);
const spans = [...container.children].map(host => host.shadowRoot.querySelector("span"));
println(`span font: ${getComputedStyle(spans[0]).fontSize} ${getComputedStyle(spans[0]).fontWeight}`);
diff --git a/Tests/LibWeb/Text/input/css/stylesheet-add-remove-imported-broad-invalidation.html b/Tests/LibWeb/Text/input/css/stylesheet-add-remove-imported-broad-invalidation.html
index f08734471d3..776f06d70ce 100644
--- a/Tests/LibWeb/Text/input/css/stylesheet-add-remove-imported-broad-invalidation.html
+++ b/Tests/LibWeb/Text/input/css/stylesheet-add-remove-imported-broad-invalidation.html
@@ -5,15 +5,29 @@
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
- function verifyRecomputationsStayBounded(label, maximum) {
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- if (recomputations <= maximum)
- println(`PASS: ${label}`);
+ // Print whether the style engine styled at most `maximum` elements since its counters were reset, or,
+ // without a bound, how many it styled.
+ function verifyStyledStaysBounded(label, maximum) {
+ const styled = internals.styleCounters().styledElements;
+ if (maximum === undefined)
+ println(`${label}, styled: ${styled}`);
else
- println(`FAIL: ${label} (${recomputations} recomputations)`);
+ println(`${label}, styled <= ${maximum}: ${styled <= maximum}`);
+ }
+
+ // The same for the last pass alone. Where a style element arrives with an @import, the style engine
+ // restyles for the element and for the imported sheet in one pass or in two, depending on when
+ // the import loads, so only the pass that took the imported sheet is counted.
+ function verifyLastPassStaysBounded(label, maximum) {
+ const lastPass = internals.styleLastPass();
+ if (maximum === undefined)
+ println(`${label}, last pass styled: ${lastPass.styled.length}`);
+ else
+ println(`${label}, last pass styled <= ${maximum}: ${lastPass.styled.length <= maximum}`);
}
function verifyTargetWasRecomputed(label) {
@@ -40,13 +54,13 @@
getComputedStyle(target).color;
// A layer order change can only move declarations that sit in layers, and nothing here does.
- verifyRecomputationsStayBounded("imported layer-only stylesheet add restyles nothing", 1);
+ verifyLastPassStaysBounded("imported layer-only stylesheet add restyles nothing", 1);
settleAndReset(target);
layerImportStyle.remove();
getComputedStyle(target).color;
- verifyRecomputationsStayBounded("imported layer-only stylesheet remove restyles nothing", 1);
+ verifyStyledStaysBounded("imported layer-only stylesheet remove restyles nothing", 1);
// With a declaration in a layer, reordering the layers has to reach the element it decides
// for - and still not the whole document.
@@ -60,7 +74,7 @@
getComputedStyle(target).color;
verifyTargetWasRecomputed("imported layer reorder reaches the layered element");
- verifyRecomputationsStayBounded("imported layer reorder stays bounded", 8);
-
+ verifyLastPassStaysBounded("imported layer reorder stays bounded", 8);
+ println(`imported layer reorder runs no full pass: ${!internals.styleLastPass().fullPass}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/stylesheet-add-remove-inactive-media-no-broad-invalidation.html b/Tests/LibWeb/Text/input/css/stylesheet-add-remove-inactive-media-no-broad-invalidation.html
index 5cf926b4a11..2a59f696b9b 100644
--- a/Tests/LibWeb/Text/input/css/stylesheet-add-remove-inactive-media-no-broad-invalidation.html
+++ b/Tests/LibWeb/Text/input/css/stylesheet-add-remove-inactive-media-no-broad-invalidation.html
@@ -5,15 +5,18 @@
function settleAndReset(triggerElement) {
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
- function verifyNoBroadReactionWasPublished(label) {
- const reactions = internals.getStyleInvalidationCounters().styleEnginePublishedReactions;
- if (reactions <= 1)
- println(`PASS: ${label}`);
+ // Print whether the style engine styled at most `maximum` elements since its counters were reset, or,
+ // without a bound, how many it styled.
+ function verifyStyledStaysBounded(label, maximum) {
+ const styled = internals.styleCounters().styledElements;
+ if (maximum === undefined)
+ println(`${label}, styled: ${styled}`);
else
- println(`FAIL: ${label} (${reactions} reactions)`);
+ println(`${label}, styled <= ${maximum}: ${styled <= maximum}`);
}
test(() => {
@@ -29,12 +32,12 @@
document.head.appendChild(inactiveStyle);
getComputedStyle(target).color;
- verifyNoBroadReactionWasPublished("inactive media stylesheet add publishes no broad reactions");
+ verifyStyledStaysBounded("inactive media stylesheet add publishes no broad reactions", 1);
settleAndReset(target);
inactiveStyle.remove();
getComputedStyle(target).color;
- verifyNoBroadReactionWasPublished("inactive media stylesheet remove publishes no broad reactions");
+ verifyStyledStaysBounded("inactive media stylesheet remove publishes no broad reactions", 1);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/stylesheet-add-remove-layer-order-invalidation.html b/Tests/LibWeb/Text/input/css/stylesheet-add-remove-layer-order-invalidation.html
index 9110c772e54..dadd4ed251a 100644
--- a/Tests/LibWeb/Text/input/css/stylesheet-add-remove-layer-order-invalidation.html
+++ b/Tests/LibWeb/Text/input/css/stylesheet-add-remove-layer-order-invalidation.html
@@ -6,17 +6,20 @@
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
internals.updateStyle();
- internals.resetStyleInvalidationCounters();
+ internals.updateStyle();
+ internals.resetStyleCounters();
}
// A `<style>` element arriving or leaving is itself an element whose style is computed, so the
// narrowest a layer-only sheet can be is that one element and nothing else.
- function verifyRestyledOnlyItself(label) {
- const recomputations = internals.getStyleInvalidationCounters().elementStyleRecomputations;
- if (recomputations <= 1)
- println(`PASS: ${label}`);
+ // Print whether the style engine styled at most `maximum` elements since its counters were reset, or,
+ // without a bound, how many it styled.
+ function verifyStyledStaysBounded(label, maximum) {
+ const styled = internals.styleCounters().styledElements;
+ if (maximum === undefined)
+ println(`${label}, styled: ${styled}`);
else
- println(`FAIL: ${label} (${recomputations} recomputations)`);
+ println(`${label}, styled <= ${maximum}: ${styled <= maximum}`);
}
function verifyRestyledTheLayeredElement(label) {
@@ -38,13 +41,13 @@
document.head.appendChild(layerOrderStyle);
getComputedStyle(target).color;
- verifyRestyledOnlyItself("layer-only stylesheet add restyles nothing but itself");
+ verifyStyledStaysBounded("layer-only stylesheet add restyles nothing but itself", 1);
settleAndReset(target);
layerOrderStyle.remove();
getComputedStyle(target).color;
- verifyRestyledOnlyItself("layer-only stylesheet remove restyles nothing but itself");
+ verifyStyledStaysBounded("layer-only stylesheet remove restyles nothing but itself", 1);
// With a declaration in a layer, a reorder that actually moves the layers has to reach
// the element it decides for - and still not the whole document. The statement sheet is
diff --git a/Tests/LibWeb/Text/input/css/stylesheet-disabled-toggle-invalidation.html b/Tests/LibWeb/Text/input/css/stylesheet-disabled-toggle-invalidation.html
index 40971a59ece..2fdd821419b 100644
--- a/Tests/LibWeb/Text/input/css/stylesheet-disabled-toggle-invalidation.html
+++ b/Tests/LibWeb/Text/input/css/stylesheet-disabled-toggle-invalidation.html
@@ -5,10 +5,9 @@
<div>bystander 2</div>
<div>bystander 3</div>
<script>
- function settleAndReset(triggerElement) {
+ function settle(triggerElement) {
getComputedStyle(triggerElement).color;
getComputedStyle(triggerElement).color;
- internals.resetStyleInvalidationCounters();
}
function addBystanders(parent, count) {
@@ -29,11 +28,11 @@
println(`before disable: ${getComputedStyle(target).color}`);
- settleAndReset(target);
+ settle(target);
sheet.disabled = true;
println(`after disable: ${getComputedStyle(target).color}`);
- settleAndReset(target);
+ settle(target);
sheet.disabled = false;
println(`after re-enable: ${getComputedStyle(target).color}`);
});
diff --git a/Tests/LibWeb/Text/input/css/text-decoration-line-style-sharing.html b/Tests/LibWeb/Text/input/css/text-decoration-line-style-sharing.html
index 3972178f31d..16d738741a2 100644
--- a/Tests/LibWeb/Text/input/css/text-decoration-line-style-sharing.html
+++ b/Tests/LibWeb/Text/input/css/text-decoration-line-style-sharing.html
@@ -8,12 +8,7 @@
<script>
test(() => {
internals.updateStyle();
- // Spans under differently decorated parents share one style, whether C++'s style sharing or
- // the style engine's first-record cache provides it.
- const sharedComputations = () => internals.getStyleInvalidationCounters().elementStyleSharedComputations
- + (internals.styleEngineCounters().engineComputedRecordSharedHits ?? 0)
- + (internals.styleEngineCounters().engineComputedRecordCohortHits ?? 0);
- const before = sharedComputations();
+ internals.resetStyleCounters();
for (const decoration of ["underline", "overline", "line-through"]) {
const parent = document.createElement("div");
parent.className = decoration;
@@ -21,10 +16,12 @@
document.body.append(parent);
}
internals.updateStyle();
- const after = sharedComputations();
+ // Spans under differently decorated parents have the same style, so all but the first take
+ // the record of another, shared without matching or reused after matching.
+ const counters = internals.styleCounters();
for (const child of document.querySelectorAll("span"))
println(getComputedStyle(child).textDecorationLine);
- println(`shared computations: ${after - before}`);
+ println(`spans taking another's record >= 2: ${counters.sharedElements + counters.reusedElements >= 2}`);
});
</script>
diff --git a/Tests/LibWeb/Text/input/css/transition-starts-on-shared-style.html b/Tests/LibWeb/Text/input/css/transition-starts-on-shared-style.html
index a05e617d64f..18b34cc1cd5 100644
--- a/Tests/LibWeb/Text/input/css/transition-starts-on-shared-style.html
+++ b/Tests/LibWeb/Text/input/css/transition-starts-on-shared-style.html
@@ -21,16 +21,13 @@
const settled = document.getElementById("settled");
const partial = document.getElementById("partial");
internals.updateStyle();
- const sharedComputations = () => internals.getStyleInvalidationCounters().elementStyleSharedComputations;
// The donor recomputes first to the style the stale element is changing to, without changing its color,
// so the stale element takes that style from the sharing cache instead of deriving it. The transition
// must still start from the stale element's own previous color.
donor.className = "item done";
stale.className = "item done";
- const before = sharedComputations();
internals.updateStyle();
- println(`shared computations: ${sharedComputations() - before}`);
println(`donor: color=${getComputedStyle(donor).color} animations=${donor.getAnimations().length}`);
println(`stale: color=${getComputedStyle(stale).color} animations=${stale.getAnimations().length}`);
diff --git a/Tests/LibWeb/Text/input/css/user-agent-selectors-compile-once-per-process.html b/Tests/LibWeb/Text/input/css/user-agent-selectors-compile-once-per-process.html
index 7e10fd9da33..15818eb7041 100644
--- a/Tests/LibWeb/Text/input/css/user-agent-selectors-compile-once-per-process.html
+++ b/Tests/LibWeb/Text/input/css/user-agent-selectors-compile-once-per-process.html
@@ -2,16 +2,29 @@
<script src="../include.js"></script>
<iframe srcdoc="<p>x</p>"></iframe>
<script>
+ // Have the style engine own this document, which builds its rule index before the frame's.
+ internals.updateStyle();
asyncTest(done => {
const iframe = document.querySelector("iframe");
iframe.onload = () => {
- // This document was styled first, so the user-agent selectors were compiled for it. The frame's document
- // attaches the same programs: its engine adds every user-agent style rule but compiles no selector.
+ // This document was styled first, so the user-agent selectors were compiled and indexed for it. The frame's
+ // rule index shares the user-agent rule index this document built, which needs no selector compiled again.
const p = iframe.contentDocument.querySelector("p");
println(`margin-top from the user-agent sheet: ${iframe.contentWindow.getComputedStyle(p).marginTop}`);
- const counters = iframe.contentWindow.internals.styleEngineCounters();
- println(`style rules added: ${counters.styleRulesCompiled > 100}`);
- println(`selector entries compiled: ${counters.exactSelectorEntries}`);
+ iframe.contentWindow.internals.updateStyle();
+ const counters = iframe.contentWindow.internals.styleCounters();
+ println(`user-agent rule index shared, not built: ${counters.indexBuilds > 0 && counters.userAgentIndexBuilds === 0}`);
+ println(`no user-agent selector compiled again: ${counters.compiledSelectors === 0}`);
+
+ // A rule the frame adds compiles its own selectors, and only those.
+ iframe.contentWindow.internals.resetStyleCounters();
+ const style = iframe.contentDocument.createElement("style");
+ style.textContent = ".compiled-once-per-process-a, .compiled-once-per-process-b > p { color: green; }";
+ iframe.contentDocument.head.appendChild(style);
+ iframe.contentWindow.internals.updateStyle();
+ const added = iframe.contentWindow.internals.styleCounters();
+ println(`index builds for the added rule: ${added.indexBuilds}`);
+ println(`selectors compiled for the added rule, at most its two: ${added.compiledSelectors <= 2}`);
done();
};
});
diff --git a/Tests/LibWeb/Text/input/simple-selector-queries-do-not-submit-style-input.html b/Tests/LibWeb/Text/input/simple-selector-queries-do-not-submit-style-input.html
deleted file mode 100644
index 23c752a7f32..00000000000
--- a/Tests/LibWeb/Text/input/simple-selector-queries-do-not-submit-style-input.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<!DOCTYPE html>
-<script src="include.js"></script>
-<ul><li id="target" class="item selected"></li></ul>
-<script>
- test(() => {
- internals.updateStyle();
- const before = internals.styleEngineCounters().rawMutationRecords;
- target.classList.add("pending-style-input");
-
- println(`tag matches: ${target.matches("li")}`);
- println(`id matches: ${target.matches("#target")}`);
- println(`classes match: ${target.matches(".item.selected")}`);
- println(`closest: ${target.closest("ul") === target.parentElement}`);
-
- const after = internals.styleEngineCounters().rawMutationRecords;
- println(`style inputs submitted: ${after - before}`);
- });
-</script>