diff --git a/moli-renderer-v8/src/css_style.rs b/moli-renderer-v8/src/css_style.rs index 4dd063f0050..a8680ca92bd 100644 --- a/moli-renderer-v8/src/css_style.rs +++ b/moli-renderer-v8/src/css_style.rs @@ -1,3 +1,5 @@ +pub(crate) mod value_dependencies; + use crate::webidl; use cssparser::{ParseError, Parser, SourcePosition, ToCss, Token, TokenSerializationType}; diff --git a/moli-renderer-v8/src/css_style/value_dependencies.rs b/moli-renderer-v8/src/css_style/value_dependencies.rs new file mode 100644 index 00000000000..c6b58a7b61e --- /dev/null +++ b/moli-renderer-v8/src/css_style/value_dependencies.rs @@ -0,0 +1,84 @@ +use cssparser::{Parser, Token}; + +pub(crate) enum ValueDependency<'a> { + Variable(&'a str), + Dimension(&'a str), + Percentage, + Identifier(&'a str), + Function(&'a str), +} + +/// Inspect a CSS value, including the active branch of var(). A missing +/// variable is reported as None so the scanner can visit its fallback. +pub(crate) fn value_has_dependency( + value: &str, + inspect: &mut impl FnMut(ValueDependency<'_>) -> Option, +) -> bool { + tokens_have_dependency(&mut Parser::new(value), inspect, 0) +} + +pub(crate) fn is_container_unit(unit: &str) -> bool { + ["cqw", "cqh", "cqi", "cqb", "cqmin", "cqmax"] + .iter() + .any(|known| unit.eq_ignore_ascii_case(known)) +} + +fn tokens_have_dependency( + input: &mut Parser<'_>, + inspect: &mut impl FnMut(ValueDependency<'_>) -> Option, + depth: usize, +) -> bool { + if depth >= 64 { + return true; + } + let mut depends = false; + while let Ok(token) = input.next().cloned() { + depends |= match token { + Token::Dimension { unit, .. } => inspect(ValueDependency::Dimension(&unit)), + Token::Percentage { .. } => inspect(ValueDependency::Percentage), + Token::Ident(name) => inspect(ValueDependency::Identifier(&name)), + Token::Function(name) if name.eq_ignore_ascii_case("var") => Some( + input + .parse_nested_block(|arguments| { + let name = arguments.expect_ident_cloned()?; + if let Some(result) = inspect(ValueDependency::Variable(&name)) { + while arguments.next().is_ok() {} + return Ok::<_, cssparser::ParseError<()>>(result); + } + if arguments.try_parse(Parser::expect_comma).is_ok() { + return Ok(tokens_have_dependency(arguments, inspect, depth + 1)); + } + Ok(false) + }) + .unwrap_or(true), + ), + Token::Function(name) => { + let own_dependency = inspect(ValueDependency::Function(&name)).unwrap_or(false); + let nested = input + .parse_nested_block(|nested| { + Ok::<_, cssparser::ParseError<()>>(tokens_have_dependency( + nested, + inspect, + depth + 1, + )) + }) + .unwrap_or(true); + Some(own_dependency || nested) + } + Token::ParenthesisBlock | Token::SquareBracketBlock | Token::CurlyBracketBlock => Some( + input + .parse_nested_block(|nested| { + Ok::<_, cssparser::ParseError<()>>(tokens_have_dependency( + nested, + inspect, + depth + 1, + )) + }) + .unwrap_or(true), + ), + _ => None, + } + .unwrap_or(false); + } + depends +} diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration.rs index 810a8fd4d9d..b7b49a40933 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles/declaration.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration.rs @@ -49,11 +49,11 @@ pub(crate) use values::{ style_property_value, }; pub(super) use values::{ - computed_style_applies, native_value_uses_container_geometry, property_uses_container_geometry, - style_css_text_for_computed, style_property_count_with_context, - style_property_index_exists_with_context, style_property_name_at_with_context, - style_property_names_with_context, style_property_priority, - style_property_value_for_pseudo_with_context, style_property_value_with_context, + computed_style_applies, property_uses_container_geometry, style_css_text_for_computed, + style_property_count_with_context, style_property_index_exists_with_context, + style_property_name_at_with_context, style_property_names_with_context, + style_property_priority, style_property_value_for_pseudo_with_context, + style_property_value_with_context, }; fn normalize_css_integer_token(value: &str) -> Option { diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs index fc60365fa9a..b46ace71a1a 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs @@ -360,9 +360,7 @@ use self::specified_values::*; mod computed_properties; use self::computed_properties::*; mod layout_dependencies; -pub(in crate::native_bridge::element::styles) use self::layout_dependencies::{ - native_value_uses_container_geometry, property_uses_container_geometry, -}; +pub(in crate::native_bridge::element::styles) use self::layout_dependencies::property_uses_container_geometry; mod custom_functions; use self::custom_functions::*; mod computed_values; diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/layout_dependencies.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/layout_dependencies.rs index b27d6c06f72..a4ba8a66e1b 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/layout_dependencies.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/layout_dependencies.rs @@ -1,3 +1,7 @@ +use crate::css_style::value_dependencies::{ + ValueDependency, is_container_unit, value_has_dependency, +}; + use super::*; /// Dependencies of the renderer's existing numeric/custom-function CSSOM @@ -81,7 +85,7 @@ impl ContainerGeometryDependencies<'_> { .is_some_and(|parent| self.property(parent, property, depth + 1)) } Some(_) => false, - None => self.value(handle, &value, depth + 1), + None => self.value(handle, &value, &mut Vec::new(), depth + 1), }); self.visiting.pop(); result @@ -91,107 +95,30 @@ impl ContainerGeometryDependencies<'_> { ComputedStyleRead::new(self.runtime, handle).raw_primary_property(property) } - fn value(&mut self, handle: DomHandle, value: &str, depth: usize) -> bool { - container_geometry_in_tokens( - &mut Parser::new(value), - &|name| self.raw_property(handle, name), - &mut Vec::new(), - depth, - ) - } -} - -pub(in crate::native_bridge::element::styles) fn native_value_uses_container_geometry( - value: &str, - style: &ComputedValues, -) -> bool { - container_geometry_in_tokens( - &mut Parser::new(value), - &|name| { - let name = style::Atom::from(name.strip_prefix("--")?); - style - .custom_properties() - .get_for_cssom(&name) - .map(style_traits::ToCss::to_css_string) - }, - &mut Vec::new(), - 0, - ) -} - -fn container_geometry_in_tokens( - input: &mut Parser<'_>, - variable: &impl Fn(&str) -> Option, - visiting: &mut Vec, - depth: usize, -) -> bool { - if depth >= 64 { - return true; - } - let mut depends = false; - while let Ok(token) = input.next().cloned() { - match token { - Token::Dimension { unit, .. } => { - depends |= ["cqw", "cqh", "cqi", "cqb", "cqmin", "cqmax"] - .iter() - .any(|known| unit.eq_ignore_ascii_case(known)); - } - Token::Function(name) if name.eq_ignore_ascii_case("var") => { - depends |= input - .parse_nested_block(|arguments| { - let name = arguments.expect_ident_cloned()?.to_string(); - let value = (!visiting.contains(&name)) - .then(|| variable(&name)) - .flatten(); - if let Some(value) = value { - visiting.push(name); - let result = container_geometry_in_tokens( - &mut Parser::new(&value), - variable, - visiting, - depth + 1, - ); - visiting.pop(); - // The present value consumes var() without its fallback. - while arguments.next().is_ok() {} - return Ok::<_, cssparser::ParseError<()>>(result); - } - if arguments.try_parse(Parser::expect_comma).is_ok() { - return Ok(container_geometry_in_tokens( - arguments, - variable, - visiting, - depth + 1, - )); - } - Ok(false) - }) - .unwrap_or(true); - } - Token::Function(name) => { - let custom_function = name.starts_with("--"); - depends |= input - .parse_nested_block(|nested| { - let nested = - container_geometry_in_tokens(nested, variable, visiting, depth + 1); - Ok::<_, cssparser::ParseError<()>>(custom_function || nested) - }) - .unwrap_or(true); - } - Token::ParenthesisBlock | Token::SquareBracketBlock | Token::CurlyBracketBlock => { - depends |= input - .parse_nested_block(|nested| { - Ok::<_, cssparser::ParseError<()>>(container_geometry_in_tokens( - nested, - variable, - visiting, - depth + 1, - )) - }) - .unwrap_or(true); - } - _ => {} + fn value( + &self, + handle: DomHandle, + value: &str, + visiting: &mut Vec, + depth: usize, + ) -> bool { + if depth >= 64 { + return true; } + value_has_dependency(value, &mut |dependency| match dependency { + ValueDependency::Variable(name) => { + if visiting.iter().any(|candidate| candidate == name) { + return None; + } + let value = self.raw_property(handle, name)?; + visiting.push(name.to_owned()); + let result = self.value(handle, &value, visiting, depth + 1); + visiting.pop(); + Some(result) + } + ValueDependency::Dimension(unit) => Some(is_container_unit(unit)), + ValueDependency::Function(name) => Some(name.starts_with("--")), + _ => None, + }) } - depends } diff --git a/moli-renderer-v8/src/native_bridge/element/styles/public_layout.rs b/moli-renderer-v8/src/native_bridge/element/styles/public_layout.rs index 7be554b031f..8d344d8f678 100644 --- a/moli-renderer-v8/src/native_bridge/element/styles/public_layout.rs +++ b/moli-renderer-v8/src/native_bridge/element/styles/public_layout.rs @@ -1,7 +1,7 @@ use moli_layout::LayoutError; use super::declaration::{ - StyleObservation, native_value_uses_container_geometry, property_uses_container_geometry, + StyleObservation, property_uses_container_geometry, style_property_value_for_pseudo_with_context, style_property_value_with_context, }; use super::{ @@ -74,12 +74,7 @@ fn size_container_dependency_needs_layout<'a>( pass.depends_on_size_container_query(handle, pseudo) || properties.into_iter().any(|property| { let property = canonical_style_property_name(property); - pass.property_uses_container_units( - handle, - pseudo, - &property, - native_value_uses_container_geometry, - ) + pass.property_uses_container_units(handle, pseudo, &property) }) }) }) diff --git a/moli-renderer-v8/src/script_vm/tests/realtime_cssom.rs b/moli-renderer-v8/src/script_vm/tests/realtime_cssom.rs index cd594ff2b72..2c2071e107b 100644 --- a/moli-renderer-v8/src/script_vm/tests/realtime_cssom.rs +++ b/moli-renderer-v8/src/script_vm/tests/realtime_cssom.rs @@ -125,6 +125,73 @@ fn realtime_cssom_native_container_units_refresh_the_requested_property() { assert_eq!(vm.layout_pass_observability_for_test().1, builds + 3); } +#[test] +fn realtime_cssom_font_relative_values_refresh_container_dependent_font_sizes() { + let mut vm = realtime_vm( + r#"
+
"#, + ); + assert_eq!( + vm.eval("const held = getComputedStyle(target); void box.offsetWidth; held.fontSize") + .unwrap(), + "40px" + ); + let builds = vm.layout_pass_observability_for_test().1; + assert_eq!( + vm.eval("box.style.width = '300px'; held.color").unwrap(), + "rgb(0, 0, 255)" + ); + assert_eq!(vm.layout_pass_observability_for_test().1, builds); + assert_eq!( + vm.eval("box.style.width = '400px'; held.fontSize").unwrap(), + "80px" + ); + assert_eq!( + vm.eval("box.style.width = '350px'; held.outlineOffset") + .unwrap(), + "70px" + ); + assert_eq!(vm.layout_pass_observability_for_test().1, builds + 2); +} + +#[test] +fn realtime_cssom_registered_container_lengths_refresh_direct_and_variable_reads() { + let mut vm = realtime_vm( + r#"
"#, + ); + assert_eq!( + vm.eval("const held = getComputedStyle(target); void box.offsetWidth; JSON.stringify([held.getPropertyValue('--size'), held.fontSize])") + .unwrap(), + r#"["20px","20px"]"# + ); + let builds = vm.layout_pass_observability_for_test().1; + assert_eq!( + vm.eval("box.style.width = '300px'; JSON.stringify([held.getPropertyValue('--raw').trim(), held.color])") + .unwrap(), + r#"["10cqw","rgb(0, 0, 255)"]"# + ); + assert_eq!(vm.layout_pass_observability_for_test().1, builds); + assert_eq!( + vm.eval("box.style.width = '400px'; held.getPropertyValue('--size')") + .unwrap(), + "40px" + ); + assert_eq!( + vm.eval("box.style.width = '450px'; held.fontSize").unwrap(), + "45px" + ); + assert_eq!( + vm.eval("box.style.width = '500px'; held.outlineOffset") + .unwrap(), + "50px" + ); + assert_eq!(vm.layout_pass_observability_for_test().1, builds + 3); +} + #[test] fn on_demand_cssom_size_container_query_keeps_live_inline_sizes() { let mut vm = new_parsed_test_vm( diff --git a/moli-renderer-v8/src/style_engine/computed.rs b/moli-renderer-v8/src/style_engine/computed.rs index 76057d76f00..cd4bbb9195e 100644 --- a/moli-renderer-v8/src/style_engine/computed.rs +++ b/moli-renderer-v8/src/style_engine/computed.rs @@ -1,3 +1,4 @@ +mod container_units; mod marker; mod resolution_pass; diff --git a/moli-renderer-v8/src/style_engine/computed/container_units.rs b/moli-renderer-v8/src/style_engine/computed/container_units.rs new file mode 100644 index 00000000000..7c10e8b0064 --- /dev/null +++ b/moli-renderer-v8/src/style_engine/computed/container_units.rs @@ -0,0 +1,344 @@ +use std::collections::HashMap; + +use moli_selector::StyloElement; +use style::{ + Atom, + applicable_declarations::{CascadePriority, RevertKind}, + computed_value_flags::ComputedValueFlags, + context::SharedStyleContext, + dom::{TElement, TNode}, + properties::{ + CSSWideKeyword, ComputedValues, CustomDeclarationValue, LonghandId, + OwnedPropertyDeclarationId, PropertyDeclaration, PropertyDeclarationBlock, + PropertyDeclarationId, PropertyId, + }, + rule_tree::CascadeOrigin, + selector_parser::PseudoElement, + servo_arc::Arc as ServoArc, + shared_lock::StylesheetGuards, + values::computed::font::LineHeight, +}; +use style_traits::ToCss; + +use super::DomHandle; +use crate::css_style::value_dependencies::{ + ValueDependency, is_container_unit, value_has_dependency, +}; + +pub(super) fn property_uses_container_units( + shared: &SharedStyleContext<'_>, + element: StyloElement<'_>, + style: ServoArc, + pseudo: Option<&PseudoElement>, + property: &str, +) -> bool { + let Ok(property) = PropertyId::parse_enabled_for_all_content(property) else { + return false; + }; + let target = StyledElement { + element, + style, + pseudo, + }; + let mut dependencies = ContainerUnitDependencies { + shared, + properties: HashMap::new(), + }; + match property.as_shorthand() { + Ok(shorthand) => shorthand.longhands().any(|longhand| { + dependencies.property(&target, PropertyDeclarationId::Longhand(longhand), 0) + }), + Err(property) => dependencies.property(&target, property, 0), + } +} + +#[derive(Clone)] +struct StyledElement<'dom, 'style> { + element: StyloElement<'dom>, + style: ServoArc, + pseudo: Option<&'style PseudoElement>, +} + +impl StyledElement<'_, '_> { + fn inheritance_parent(&self) -> Option { + let element = if self.pseudo.is_some() { + self.element + } else { + self.element.traversal_parent()? + }; + let style = element.borrow_data()?.styles.get_primary()?.clone(); + Some(Self { + element, + style, + pseudo: None, + }) + } + + fn has_size_container(&self) -> bool { + self.style + .flags + .contains(ComputedValueFlags::SELF_OR_ANCESTOR_HAS_SIZE_CONTAINER_TYPE) + } +} + +struct ContainerUnitDependencies<'a, 'shared> { + shared: &'a SharedStyleContext<'shared>, + // None marks an edge under evaluation so cyclic references terminate. + properties: HashMap<(DomHandle, bool, OwnedPropertyDeclarationId), Option>, +} + +impl ContainerUnitDependencies<'_, '_> { + fn property( + &mut self, + target: &StyledElement<'_, '_>, + property: PropertyDeclarationId<'_>, + depth: usize, + ) -> bool { + if !target.has_size_container() { + return false; + } + if depth >= 64 { + return true; + } + let key = ( + DomHandle::new(target.element.as_node().debug_id()), + target.pseudo.is_some(), + property.to_owned(), + ); + if let Some(result) = self.properties.get(&key) { + return result.unwrap_or(false); + } + self.properties.insert(key.clone(), None); + let depends = self.declaration(target, property, depth); + self.properties.insert(key, Some(depends)); + depends + } + + fn declaration( + &mut self, + target: &StyledElement<'_, '_>, + property: PropertyDeclarationId<'_>, + depth: usize, + ) -> bool { + let (inherits, computes_units) = match property { + PropertyDeclarationId::Longhand(id) => (id.inherited(), true), + PropertyDeclarationId::Custom(name) => { + let registration = self.shared.stylist.get_custom_property_registration(name); + (registration.inherits(), !registration.is_universal()) + } + }; + // Inheritance walks the flat tree without spending the dependency + // recursion budget on ancestors that have no declaration of their own. + let mut target = target.clone(); + while target.has_size_container() { + let declaration = winning_declaration(&target, property, &self.shared.guards); + let keyword = declaration.and_then(|(declaration, _)| declaration_keyword(declaration)); + if keyword == Some(CSSWideKeyword::Inherit) + || inherits && (keyword == Some(CSSWideKeyword::Unset) || declaration.is_none()) + { + let Some(parent) = target.inheritance_parent() else { + return false; + }; + target = parent; + continue; + } + let Some((declaration, block)) = declaration.filter(|_| keyword.is_none()) else { + return false; + }; + let Some(value) = serialized_declaration(declaration, block) else { + return computes_units + && target + .style + .flags + .contains(ComputedValueFlags::USES_CONTAINER_UNITS); + }; + return self.value(&target, property, &value, computes_units, depth); + } + false + } + + fn parent_property( + &mut self, + target: &StyledElement<'_, '_>, + property: PropertyDeclarationId<'_>, + depth: usize, + ) -> bool { + target + .inheritance_parent() + .is_some_and(|parent| self.property(&parent, property, depth)) + } + + fn value( + &mut self, + target: &StyledElement<'_, '_>, + property: PropertyDeclarationId<'_>, + value: &str, + computes_units: bool, + depth: usize, + ) -> bool { + if depth >= 64 { + return true; + } + let is_font_size = property == PropertyDeclarationId::Longhand(LonghandId::FontSize); + let is_line_height = property == PropertyDeclarationId::Longhand(LonghandId::LineHeight); + value_has_dependency(value, &mut |dependency| { + if let ValueDependency::Variable(name) = dependency { + let name = Atom::from(name.strip_prefix("--")?); + let computed = target.style.custom_properties().get_for_cssom(&name)?; + // Typed substitutions may already be pixels. Their producer + // can depend on a container in a different inherited style. + return Some( + self.property(target, PropertyDeclarationId::Custom(&name), depth + 1) + || computes_units + && self.value( + target, + property, + &computed.to_css_string(), + true, + depth + 1, + ), + ); + } + if !computes_units { + return None; + } + let font_size = PropertyDeclarationId::Longhand(LonghandId::FontSize); + match dependency { + ValueDependency::Dimension(unit) if is_container_unit(unit) => Some(true), + ValueDependency::Dimension(unit) + if ["em", "ex", "ch", "cap", "ic"] + .iter() + .any(|relative| unit.eq_ignore_ascii_case(relative)) => + { + Some(if is_font_size { + self.parent_property(target, font_size, depth + 1) + } else { + self.property(target, font_size, depth + 1) + }) + } + ValueDependency::Dimension(unit) if unit.eq_ignore_ascii_case("lh") => { + Some(self.line_height(target, is_font_size || is_line_height, depth + 1)) + } + ValueDependency::Percentage if is_font_size => { + Some(self.parent_property(target, font_size, depth + 1)) + } + ValueDependency::Percentage if is_line_height => { + Some(self.property(target, font_size, depth + 1)) + } + ValueDependency::Identifier(keyword) + if is_font_size + && (keyword.eq_ignore_ascii_case("larger") + || keyword.eq_ignore_ascii_case("smaller")) => + { + Some(self.parent_property(target, font_size, depth + 1)) + } + ValueDependency::Function(name) if name.starts_with("--") => Some( + target + .style + .flags + .contains(ComputedValueFlags::USES_CONTAINER_UNITS), + ), + _ => None, + } + }) + } + + fn line_height( + &mut self, + target: &StyledElement<'_, '_>, + inherited: bool, + depth: usize, + ) -> bool { + if inherited { + return target + .inheritance_parent() + .is_some_and(|parent| self.line_height(&parent, false, depth)); + } + let property = match target.style.clone_line_height() { + LineHeight::Length(_) => LonghandId::LineHeight, + LineHeight::Normal | LineHeight::Number(_) => LonghandId::FontSize, + }; + self.property(target, PropertyDeclarationId::Longhand(property), depth) + } +} + +fn declaration_keyword(declaration: &PropertyDeclaration) -> Option { + if let PropertyDeclaration::Custom(custom) = declaration { + return match &custom.value { + CustomDeclarationValue::CSSWideKeyword(keyword) => Some(*keyword), + _ => None, + }; + } + declaration.get_css_wide_keyword() +} + +fn serialized_declaration( + declaration: &PropertyDeclaration, + block: &PropertyDeclarationBlock, +) -> Option { + let mut value = String::new(); + declaration.to_css(&mut value).ok()?; + if !value.is_empty() || !matches!(declaration, PropertyDeclaration::WithVariables(_)) { + return Some(value); + } + // Pending substitutions from shorthands serialize on the shorthand. + for shorthand in declaration.id().as_longhand()?.shorthands() { + block + .property_value_to_css(&PropertyId::NonCustom(shorthand.into()), &mut value) + .ok()?; + if !value.is_empty() { + return Some(value); + } + } + None +} + +fn winning_declaration<'a>( + target: &'a StyledElement<'_, '_>, + property: PropertyDeclarationId<'_>, + guards: &'a StylesheetGuards<'a>, +) -> Option<(&'a PropertyDeclaration, &'a PropertyDeclarationBlock)> { + let writing_mode = target.style.writing_mode; + let restriction = target + .pseudo + .and_then(|pseudo| pseudo.property_restriction()); + let mut reverted: Option<(CascadePriority, RevertKind)> = None; + for node in target.style.rules().self_and_ancestors() { + let priority = node.cascade_priority(); + let level = priority.cascade_level(); + let origin = level.origin(); + if !priority.flags().is_empty() + || reverted.is_some_and(|(from, kind)| !from.allows_when_reverted(&priority, kind)) + { + continue; + } + let Some(source) = node.style_source() else { + continue; + }; + let block = source.read(origin.guard(guards)); + for (declaration, importance) in block.declaration_importance_iter().rev() { + let matches = match (declaration.id(), property) { + ( + PropertyDeclarationId::Longhand(actual), + PropertyDeclarationId::Longhand(requested), + ) => { + actual.to_physical(writing_mode) == requested.to_physical(writing_mode) + && (origin == CascadeOrigin::UA + || restriction.is_none_or(|flags| actual.flags().contains(flags))) + } + (actual, requested) => actual == requested, + }; + if !matches || importance.important() != level.is_important() { + continue; + } + if let Some(kind) = + declaration_keyword(declaration).and_then(CSSWideKeyword::revert_kind) + { + reverted = Some((priority, kind)); + break; + } + return Some((declaration, block)); + } + } + None +} diff --git a/moli-renderer-v8/src/style_engine/computed/resolution_pass.rs b/moli-renderer-v8/src/style_engine/computed/resolution_pass.rs index 12b27baf272..260a2057efc 100644 --- a/moli-renderer-v8/src/style_engine/computed/resolution_pass.rs +++ b/moli-renderer-v8/src/style_engine/computed/resolution_pass.rs @@ -7,17 +7,14 @@ use selectors::matching::{ use style::{ Atom, animation::DocumentAnimationSet, - applicable_declarations::{ApplicableDeclarationList, CascadePriority, RevertKind}, + applicable_declarations::ApplicableDeclarationList, computed_value_flags::ComputedValueFlags, context::{ QuirksMode, RegisteredSpeculativePainter, RegisteredSpeculativePainters, SharedStyleContext, StyleContext, StyleSystemOptions, ThreadLocalStyleContext, }, dom::{TElement, TNode}, - properties::{ - CSSWideKeyword, ComputedValues, LonghandId, PropertyDeclaration, PropertyDeclarationBlock, - PropertyDeclarationId, PropertyId, - }, + properties::ComputedValues, selector_parser::{PseudoElement, SelectorImpl, SnapshotMap}, servo_arc::Arc as ServoArc, shared_lock::StylesheetGuards, @@ -274,19 +271,12 @@ impl<'dom> StyleResolutionPass<'_, 'dom> { false } - /// Inspect the winning native declaration for the requested property. - /// Stylo's container-unit flag describes the whole style, so it only - /// gates the value probe once we know which declaration the read uses. pub(crate) fn property_uses_container_units( &mut self, handle: DomHandle, pseudo: Option<&str>, property: &str, - value_uses_container_units: impl Fn(&str, &ComputedValues) -> bool, ) -> bool { - let Ok(property) = PropertyId::parse_enabled_for_all_content(property) else { - return false; - }; let Some(element) = self.prepare(handle) else { return false; }; @@ -304,85 +294,17 @@ impl<'dom> StyleResolutionPass<'_, 'dom> { element.borrow_data()?.styles.pseudos.get(pseudo).cloned() } }); - let probe = |longhand: LonghandId| { - let mut candidate = element; - let mut pseudo = pseudo.as_ref().zip(pseudo_style.as_deref()); - loop { - let primary = candidate - .borrow_data() - .and_then(|data| data.styles.get_primary().cloned()); - let Some(style) = pseudo.map(|(_, style)| style).or(primary.as_deref()) else { - return false; - }; - if !style - .flags - .contains(ComputedValueFlags::SELF_OR_ANCESTOR_HAS_SIZE_CONTAINER_TYPE) - { - return false; - } - match native_property_declaration( - style, - pseudo.map(|(pseudo, _)| pseudo), - longhand, - &self.context.shared.guards, - ) { - Some((declaration, block)) => match declaration.get_css_wide_keyword() { - Some(CSSWideKeyword::Inherit) => {} - Some(CSSWideKeyword::Unset) if longhand.inherited() => {} - Some(_) => return false, - None => { - if !style - .flags - .contains(ComputedValueFlags::USES_CONTAINER_UNITS) - { - return false; - } - let mut value = String::new(); - if declaration.to_css(&mut value).is_err() { - return true; - } - if value.is_empty() - && matches!(declaration, PropertyDeclaration::WithVariables(_)) - { - // Pending substitutions from shorthands serialize - // at the shorthand, rather than on each longhand. - for shorthand in declaration - .id() - .as_longhand() - .into_iter() - .flat_map(LonghandId::shorthands) - { - let _ = block.property_value_to_css( - &PropertyId::NonCustom(shorthand.into()), - &mut value, - ); - if !value.is_empty() { - break; - } - } - if value.is_empty() { - return true; - } - } - return value_uses_container_units(&value, style); - } - }, - None if longhand.inherited() => {} - None => return false, - } - if pseudo.take().is_none() { - let Some(parent) = candidate.traversal_parent() else { - return false; - }; - candidate = parent; - } - } + let (style, pseudo) = match pseudo.as_ref().zip(pseudo_style) { + Some((pseudo, style)) => (style, Some(pseudo)), + None => (primary, None), }; - match property.as_shorthand() { - Ok(shorthand) => shorthand.longhands().any(probe), - Err(PropertyDeclarationId::Longhand(longhand)) => probe(longhand), - Err(PropertyDeclarationId::Custom(_)) => false, - } + super::container_units::property_uses_container_units( + self.context.shared, + element, + style, + pseudo, + property, + ) } #[cfg(feature = "devtools")] @@ -566,52 +488,6 @@ impl<'dom> StyleResolutionPass<'_, 'dom> { } } -fn native_property_declaration<'a>( - style: &'a ComputedValues, - pseudo: Option<&PseudoElement>, - property: LonghandId, - guards: &'a StylesheetGuards<'a>, -) -> Option<(&'a PropertyDeclaration, &'a PropertyDeclarationBlock)> { - let physical = property.to_physical(style.writing_mode); - let restriction = pseudo.and_then(|pseudo| pseudo.property_restriction()); - let mut reverted: Option<(CascadePriority, RevertKind)> = None; - for node in style.rules().self_and_ancestors() { - let priority = node.cascade_priority(); - let level = priority.cascade_level(); - let origin = level.origin(); - if !priority.flags().is_empty() - || reverted.is_some_and(|(from, kind)| !from.allows_when_reverted(&priority, kind)) - { - continue; - } - let Some(source) = node.style_source() else { - continue; - }; - let block = source.read(origin.guard(guards)); - for (declaration, importance) in block.declaration_importance_iter().rev() { - let Some(longhand) = declaration.id().as_longhand() else { - continue; - }; - if longhand.to_physical(style.writing_mode) != physical - || importance.important() != level.is_important() - || restriction.is_some_and(|flags| !longhand.flags().contains(flags)) - && origin != style::rule_tree::CascadeOrigin::UA - { - continue; - } - if let Some(kind) = declaration - .get_css_wide_keyword() - .and_then(CSSWideKeyword::revert_kind) - { - reverted = Some((priority, kind)); - break; - } - return Some((declaration, block)); - } - } - None -} - impl Drop for StyleResolutionPass<'_, '_> { fn drop(&mut self) { self.context