Truly independent web browser
LibWeb: Support anchor-size()
Andreas Klingfe7669177ae4
diff --git a/Libraries/LibWeb/Rust/src/css/absolutize.rs b/Libraries/LibWeb/Rust/src/css/absolutize.rsindex 0d89570661f..955ac041f3a 100644--- a/Libraries/LibWeb/Rust/src/css/absolutize.rs+++ b/Libraries/LibWeb/Rust/src/css/absolutize.rs@@ -1922,7 +1922,7 @@ pub(crate) fn absolutize(value: &StyleValueData, context: &AbsolutizationContext}}StyleValueData::Edge { .. } => absolutize_edge(value, context),- StyleValueData::Anchor { .. } => {+ StyleValueData::Anchor { .. } | StyleValueData::AnchorSize { .. } => {let mut tracked = false;let mut calc_length_context = *context.length;calc_length_context.resolved_viewport_relative_length = &raw mut tracked;diff --git a/Libraries/LibWeb/Rust/src/css/calc.rs b/Libraries/LibWeb/Rust/src/css/calc.rsindex 9322d675772..8aa243a69a5 100644--- a/Libraries/LibWeb/Rust/src/css/calc.rs+++ b/Libraries/LibWeb/Rust/src/css/calc.rs@@ -2569,27 +2569,30 @@ pub(crate) fn length_percentage_calculated_style_value(}}-/// Wraps a computed anchor() inset value into the calculated style value the-/// layout engine resolves, matching what the C++ bridge built through-/// CalculatedStyleValue::create with CalculationContext::for_property for the-/// top/right/bottom/left properties: the anchor value as a non-math-function-/// leaf of the length numeric type, percentages resolving as length, and no-/// integer rounding. Those properties accept the full float range for both-/// length and percentage, which equals the clamp fallback for an absent-/// accepted-range entry, so the wrapper carries an empty range list.+/// Wraps a computed anchor() or anchor-size() value into the calculated style+/// value the layout engine resolves, matching what the C++ bridge built+/// through CalculatedStyleValue::create with CalculationContext::for_property+/// for the top/right/bottom/left properties: the anchor value as a+/// non-math-function leaf of the length numeric type, percentages resolving as+/// length, and no integer rounding. Those properties accept the full float+/// range for both length and percentage, which equals the clamp fallback for+/// an absent accepted-range entry, so the wrapper carries an empty range list.////// # Safety-/// `anchor` must point at live anchor style value data.+/// `anchor` must point at live anchor() or anchor-size() style value data.// NB: Same main-thread-only contract as `handle` above.#[allow(clippy::arc_with_non_send_sync)]-pub(crate) unsafe fn create_anchor_inset_calculated(+pub(crate) unsafe fn create_anchor_function_calculated(anchor: *const crate::css::style_value::StyleValueData,) -> Arc<crate::css::style_value::StyleValueData> {use crate::css::style_value::StyleValueData;assert!(- matches!(unsafe { &*anchor }, StyleValueData::Anchor { .. }),- "anchor inset handle holds a non-anchor style value"+ matches!(+ unsafe { &*anchor },+ StyleValueData::Anchor { .. } | StyleValueData::AnchorSize { .. }+ ),+ "anchor function handle holds a non-anchor style value");unsafe { Arc::increment_strong_count(anchor) };let anchor_value = unsafe { RetainedStyleValueData::from_retained_pointer(anchor) };@@ -4186,9 +4189,9 @@ pub(crate) enum AbsolutizedCalculation {Value(crate::css::style_value::StyleValueData),}-/// Absolutizes the fallback value of an anchor() function, which keeps its anchor query-/// until style and layout interleaving resolves it. Returns the rebuilt function, none when-/// nothing changed, or None when the fallback value cannot absolutize.+/// Absolutizes the fallback value of an anchor() or anchor-size() function, which keeps its+/// anchor query until style and layout interleaving resolves it. Returns the rebuilt function,+/// none when nothing changed, or None when the fallback value cannot absolutize.pub(crate) fn absolutize_anchor_function(value: &crate::css::style_value::StyleValueData,length_context: &crate::css::style_compute::FfiLengthResolutionContext,@@ -4196,12 +4199,7 @@ pub(crate) fn absolutize_anchor_function(random_base_values: &[crate::css::style_compute::FfiRandomBaseValue],) -> Option<Option<crate::css::style_value::StyleValueData>> {use crate::css::style_value::StyleValueData;- let StyleValueData::Anchor {- has_anchor_name,- anchor_name,- anchor_side,- fallback_value,- } = value+ let (StyleValueData::Anchor { fallback_value, .. } | StyleValueData::AnchorSize { fallback_value, .. }) = valueelse {return None;};@@ -4227,7 +4225,7 @@ pub(crate) fn absolutize_anchor_function(AbsolutizedCalculation::Value(value) => value,}}- Some(fallback @ StyleValueData::Anchor { .. }) => {+ Some(fallback @ (StyleValueData::Anchor { .. } | StyleValueData::AnchorSize { .. })) => {match absolutize_anchor_function(fallback, length_context, tree_counting, random_base_values)? {Some(value) => value,None => return Some(None),@@ -4235,11 +4233,33 @@ pub(crate) fn absolutize_anchor_function(}Some(_) => return Some(None),};- Some(Some(StyleValueData::Anchor {- has_anchor_name: *has_anchor_name,- anchor_name: anchor_name.clone(),- anchor_side: anchor_side.clone_retained(),- fallback_value: RetainedStyleValueData::from_arc(Arc::new(absolutized_fallback)),+ let fallback_value = RetainedStyleValueData::from_arc(Arc::new(absolutized_fallback));+ Some(Some(match value {+ StyleValueData::Anchor {+ has_anchor_name,+ anchor_name,+ anchor_side,+ ..+ } => StyleValueData::Anchor {+ has_anchor_name: *has_anchor_name,+ anchor_name: anchor_name.clone(),+ anchor_side: anchor_side.clone_retained(),+ fallback_value,+ },+ StyleValueData::AnchorSize {+ has_anchor_name,+ anchor_name,+ has_anchor_size,+ anchor_size,+ ..+ } => StyleValueData::AnchorSize {+ has_anchor_name: *has_anchor_name,+ anchor_name: anchor_name.clone(),+ has_anchor_size: *has_anchor_size,+ anchor_size: *anchor_size,+ fallback_value,+ },+ _ => unreachable!("the value was matched as an anchor function above"),}))}@@ -4329,8 +4349,11 @@ pub(crate) fn absolutize_calculation_value(}let source = external.source.data();let StyleValueData::TreeCountingFunction { function, .. } = source else {- if matches!(source, StyleValueData::Anchor { .. }) {- // anchor() stays unresolved until style and layout interleaving supplies+ if matches!(+ source,+ StyleValueData::Anchor { .. } | StyleValueData::AnchorSize { .. }+ ) {+ // anchor() and anchor-size() stay unresolved until style and layout interleaving supplies// an anchor resolver, matching the context-free computed-value pass.if let Some(absolutized) =absolutize_anchor_function(source, length_context, tree_counting, random_base_values)?@@ -4688,7 +4711,11 @@ impl CalcNode {pub(crate) fn contains_anchor_function(&self) -> bool {if let CalcNode::NonMathFunction { value, .. } = self- && matches!(value.data(), crate::css::style_value::StyleValueData::Anchor { .. })+ && matches!(+ value.data(),+ crate::css::style_value::StyleValueData::Anchor { .. }+ | crate::css::style_value::StyleValueData::AnchorSize { .. }+ ){return true;}diff --git a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs b/Libraries/LibWeb/Rust/src/css/computed_value_views.rsindex 417270c3a76..20a79a69948 100644--- a/Libraries/LibWeb/Rust/src/css/computed_value_views.rs+++ b/Libraries/LibWeb/Rust/src/css/computed_value_views.rs@@ -44,8 +44,14 @@ pub(crate) fn resolve_calc_to_px_without_rounding(calculated: *const c_void, perassert!(!calculated.is_null());// SAFETY: The style value stays alive for the pass.let value = unsafe { &*calculated.cast::<StyleValueData>() };- crate::css::calc::resolve_calculated_length_without_context(value, percentage_basis.to_double())- .expect("computed length-percentage calc failed to resolve")+ crate::css::calc::resolve_calculated_length_without_context(value, percentage_basis.to_double()).unwrap_or_else(|| {+ assert!(+ matches!(value, StyleValueData::Calculated { rust_calculation, .. } if rust_calculation.node().contains_anchor_function()),+ "computed length-percentage calc failed to resolve"+ );+ // NB: The abspos engine resolves the anchor functions it can itself, so these are unresolvable.+ crate::layout::style_values::resolve_calc_with_unresolvable_anchor_functions(calculated, percentage_basis)+ })}pub(crate) fn resolve_calc_to_px(calculated: *const c_void, percentage_basis: CssPixels) -> CssPixels {@@ -332,6 +338,19 @@ pub(crate) fn auto_computed_size() -> &'static ComputedSize {&AUTO_COMPUTED_SIZE.0}+static NONE_COMPUTED_SIZE: SyncComputedSize = SyncComputedSize(ComputedSize {+ kind: ComputedSizeKind::None,+ value: ComputedStyleValueHandle {+ pointer: std::ptr::null(),+ },+});++/// A shared computed `none` size for readers that substitute none for a+/// stored size.+pub(crate) fn none_computed_size() -> &'static ComputedSize {+ &NONE_COMPUTED_SIZE.0+}+fn counter_definitions(handle: &ComputedStyleValueHandle) -> &[crate::css::style_value::RetainedCounterDefinition] {match handle.data() {Some(StyleValueData::CounterDefinitions { counter_definitions }) => counter_definitions.as_slice(),diff --git a/Libraries/LibWeb/Rust/src/css/computed_values.rs b/Libraries/LibWeb/Rust/src/css/computed_values.rsindex 95f64f7534d..81f0b8892bb 100644--- a/Libraries/LibWeb/Rust/src/css/computed_values.rs+++ b/Libraries/LibWeb/Rust/src/css/computed_values.rs@@ -2765,8 +2765,11 @@ impl ComputedSize {Some(StyleValueData::Calculated { .. }) => Self::retained(ComputedSizeKind::Calculated, data),Some(StyleValueData::Percentage { .. }) => Self::retained(ComputedSizeKind::Percentage, data),Some(StyleValueData::Length { .. }) => Self::retained(ComputedSizeKind::Length, data),- // FIXME: Support `anchor-size(..)`.- Some(StyleValueData::AnchorSize { .. }) => Self::keyword(ComputedSizeKind::None),+ // NB: Layout resolves anchor-size() itself, through the calculation that wraps it.+ Some(StyleValueData::AnchorSize { .. }) => Self {+ kind: ComputedSizeKind::Calculated,+ value: anchor_function_calculated_handle(data),+ },_ => Self::keyword(ComputedSizeKind::Auto),}}@@ -2868,6 +2871,15 @@ impl AlignmentValues {}}+/// A handle to the calculated style value wrapping the anchor() or anchor-size() value `data` holds.+fn anchor_function_calculated_handle(data: &RetainedStyleValueData) -> ComputedStyleValueHandle {+ // SAFETY: The caller matched `data` as live anchor() or anchor-size() style value data.+ let calculated = unsafe { crate::css::calc::create_anchor_function_calculated(data.pointer().cast()) };+ ComputedStyleValueHandle {+ pointer: std::sync::Arc::into_raw(calculated).cast(),+ }+}+impl ComputedLengthPercentageOrAuto {fn auto() -> Self {Self {@@ -2913,6 +2925,12 @@ impl ComputedLengthPercentageOrAuto {is_auto: false,value: ComputedStyleValueHandle::from_retained(data),},+ // NB: Layout resolves an anchor-size() margin itself, through the calculation that wraps it. Insets keep+ // their anchor functions in separate wrappers instead, and expose auto here.+ Some(StyleValueData::AnchorSize { .. }) if !default_is_auto => Self {+ is_auto: false,+ value: anchor_function_calculated_handle(data),+ },_ if default_is_auto => Self::auto(),_ => Self::zero(),}@@ -3834,7 +3852,10 @@ pub(crate) fn rust_build_surround_group(let build_or_reuse_group_payload = || {let anchor = |data: &RetainedStyleValueData| {- if matches!(data.optional_data(), Some(StyleValueData::Anchor { .. })) {+ if matches!(+ data.optional_data(),+ Some(StyleValueData::Anchor { .. } | StyleValueData::AnchorSize { .. })+ ) {ComputedStyleValueHandle::from_retained(data)} else {ComputedStyleValueHandle::empty()@@ -3867,7 +3888,7 @@ pub(crate) fn rust_build_surround_group(return ComputedStyleValueHandle::empty();}// SAFETY: The handle retains anchor style value data.- let calculated = unsafe { crate::css::calc::create_anchor_inset_calculated(handle.pointer.cast()) };+ let calculated = unsafe { crate::css::calc::create_anchor_function_calculated(handle.pointer.cast()) };ComputedStyleValueHandle {pointer: std::sync::Arc::into_raw(calculated).cast(),}diff --git a/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rsindex 5b69c549342..de1398df027 100644--- a/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/calc_parser.rs@@ -23,7 +23,7 @@ use crate::css::css_string::CssString;use crate::css::css_tokenizer::ParserTokenKind;use crate::css::math_functions::{MathFunction, math_function_from_name};use crate::css::parser::component_value::{ComponentKind, ComponentValue};-use crate::css::parser::positions_shapes_parser::parse_anchor_function;+use crate::css::parser::positions_shapes_parser::{parse_anchor_function, parse_anchor_size_function};use crate::css::property_metadata::property_name;use crate::css::style_compute::LENGTH_UNIT_NAMES;use crate::css::style_value::{RetainedStyleValueData, StyleValueData};@@ -224,9 +224,8 @@ fn parse_non_math_function(numeric_type: CalcNumericType::default(),}));}- // NB: Only anchor() becomes a NonMathFunction calc leaf. anchor-size() remains a native- // style value.- let parsed = parse_anchor_function(parse_context, context.property, value);+ let parsed = parse_anchor_function(parse_context, context.property, value)+ .or_else(|| parse_anchor_size_function(parse_context, context.property, value));let Some(parsed) = parsed else {return Err(CalcParseError::NotHandled);};diff --git a/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rsindex a9a783cd026..7f5e32824b1 100644--- a/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/positions_shapes_parser.rs@@ -2003,7 +2003,11 @@ fn property_allows_anchor_size(property: u16) -> bool {}// https://drafts.csswg.org/css-anchor-position-1/#funcdef-anchor-size-fn parse_anchor_size_function(context: &ParseContext, property: u16, value: &ComponentValue) -> Option<StyleValueData> {+pub(crate) fn parse_anchor_size_function(+ context: &ParseContext,+ property: u16,+ value: &ComponentValue,+) -> Option<StyleValueData> {if !property_allows_anchor_size(property) {return None;}diff --git a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rsindex 69f073e7e24..1b712ccdecc 100644--- a/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/parser/value_parser.rs@@ -7685,7 +7685,7 @@ mod tests {}assert!(matches!(parse(property_id::WIDTH, "calc(anchor-size(width) + 1px)"),- ParseOutcome::Invalid+ ParseOutcome::Parsed(_)));}diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rsindex 8ab14e899aa..c9c3afb3eb9 100644--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs@@ -1531,7 +1531,9 @@ pub(crate) fn collect_external_value_dependencies(value: &StyleValueData) -> Extcollect_values(&[numerator, denominator], dependencies);}StyleValueData::Edge { offset, .. } => collect_optional(offset, dependencies),- StyleValueData::Anchor { fallback_value, .. } => collect_optional(fallback_value, dependencies),+ StyleValueData::Anchor { fallback_value, .. } | StyleValueData::AnchorSize { fallback_value, .. } => {+ collect_optional(fallback_value, dependencies);+ }StyleValueData::Ray { angle, position, .. } => {collect_optional(angle, dependencies);collect_optional(position, dependencies);diff --git a/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs b/Libraries/LibWeb/Rust/src/layout/abspos_engine.rsindex 45203b8cb0b..eaec3d561b2 100644--- a/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs+++ b/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs@@ -251,7 +251,16 @@ impl<'pass> AbsposEngine<'pass> {}fn style(&self, node: Node) -> StyleValues<'pass> {- StyleValues::for_node(&self.callbacks, node)+ let style = StyleValues::for_node(&self.callbacks, node);+ if !style.is_absolutely_positioned() {+ return style;+ }+ let anchor_resolved_values = self+ .records+ .used_values_if_owned(node)+ .and_then(|used| used.anchor_resolved_values.get())+ .map(|resolved| &**resolved);+ style.with_anchor_resolved_values(anchor_resolved_values)}fn facts(&self, node: Node) -> NodeFacts<'_> {@@ -312,15 +321,6 @@ impl<'pass> AbsposEngine<'pass> {}}-fn calc_node_create_px_dimension(value: f64) -> *const c_void {- crate::css::calc::rust_calc_node_create_numeric_dimension(- formatting_context::CALC_NUMERIC_KIND_LENGTH,- value,- crate::css::style_compute::px_length_unit(),- )- .cast()-}-struct AnchorResolutionState {default_anchor_box: Node,compensates_for_horizontal_scroll: bool,@@ -596,6 +596,38 @@ impl AbsposEngine<'_> {}}+ /// https://drafts.csswg.org/css-anchor-position-1/#anchor-size-fn+ /// The length an anchor-size() function with the given <anchor-size> keyword resolves to against the anchor box+ /// `rect`, used in a property of the horizontal axis or not.+ fn anchor_size(+ &self,+ anchor_size: Option<u8>,+ rect: CssPixelRect,+ positioned_box: Node,+ containing_block: Node,+ is_horizontal_axis: bool,+ ) -> CssPixels {+ use crate::css::css_enums::anchor_size;+ // The logical <anchor-size> keywords (block, inline, self-block, and self-inline) map to one of the physical+ // keywords according to either the writing mode of the box (for self-block and self-inline) or the writing+ // mode of the box's containing block (for block and inline).+ let inline_axis_is_horizontal =+ |writing_mode_box: Node| self.style(writing_mode_box).writing_mode() == writing_mode::HORIZONTAL_TB;+ // If the <anchor-size> keyword is omitted, it defaults to behaving as whatever keyword matches the axis of+ // the property that anchor-size() is used in.+ let measures_width = match anchor_size {+ None => is_horizontal_axis,+ Some(anchor_size::WIDTH) => true,+ Some(anchor_size::HEIGHT) => false,+ Some(anchor_size::INLINE) => inline_axis_is_horizontal(containing_block),+ Some(anchor_size::BLOCK) => !inline_axis_is_horizontal(containing_block),+ Some(anchor_size::SELF_INLINE) => inline_axis_is_horizontal(positioned_box),+ Some(anchor_size::SELF_BLOCK) => !inline_axis_is_horizontal(positioned_box),+ Some(_) => unreachable!("anchor-size() holds an unknown <anchor-size> keyword"),+ };+ if measures_width { rect.width } else { rect.height }+ }+fn note_resolved_anchor_function(&self,anchor_box: Node,@@ -621,7 +653,7 @@ impl AbsposEngine<'_> {#[allow(clippy::too_many_arguments)]fn resolve_anchor_value(&self,- value: style_values::InsetValue,+ calculated: *const c_void,positioned_box: Node,containing_block: Node,containing_block_geometry: Option<ContainingBlockGeometry>,@@ -629,8 +661,6 @@ impl AbsposEngine<'_> {axis: AnchorValueAxis,resolution_state: &mut AnchorResolutionState,) -> Option<CssPixels> {- assert!(value.contains_anchor_function());- let calculated = value.anchor_bearing_calculated();let mut callback_context = AnchorCalcCallbackContext {engine: self,positioned_box,@@ -729,7 +759,7 @@ impl AbsposEngine<'_> {let mut resolve_inset = |inset: style_values::InsetValue<'_>, axis: AnchorValueAxis| {inset.contains_anchor_function().then(|| {self.resolve_anchor_value(- inset,+ inset.anchor_bearing_calculated(),node,containing_block,entry_containing_block_geometry.copied(),@@ -787,6 +817,88 @@ impl AbsposEngine<'_> {(Some(resolved), default_scroll_shift)}+ /// Resolves the anchor-size() functions in the sizing and margin properties of `node`.+ /// https://drafts.csswg.org/css-anchor-position-1/#anchor-size-fn+ fn resolve_anchor_sizes(+ &self,+ node: Node,+ containing_block: Node,+ containing_block_geometry: &ContainingBlockGeometry,+ entry_coordinate_space_box: Node,+ ) -> style_values::ResolvedAnchorSizes {+ // NB: Read the computed values themselves, not what an earlier resolution made of them.+ let style = *StyleValues::for_node(&self.callbacks, node);+ let mut resolution_state = AnchorResolutionState::NO_SCROLL_SHIFT;+ let mut resolve = |calculated: *const c_void, is_horizontal: bool, containing_block_extent: CssPixels| {+ self.resolve_anchor_value(+ calculated,+ node,+ containing_block,+ Some(*containing_block_geometry),+ entry_coordinate_space_box,+ AnchorValueAxis {+ is_from_end: false,+ is_horizontal,+ containing_block_extent,+ },+ &mut resolution_state,+ )+ };+ let inline_size = containing_block_geometry.padding_box_inline_size();+ let block_size = containing_block_geometry.padding_box_block_size();+ // https://drafts.csswg.org/css-anchor-position-1/#anchor-size-resolution+ // If no fallback value is specified, it makes the declaration referencing it invalid at computed-value time.+ let mut resolve_size = |size: &ComputedSize, is_horizontal: bool, initial: ComputedSizeKind| {+ if !size.is_length_percentage() || !size.length_percentage().contains_anchor_function() {+ return None;+ }+ let extent = if is_horizontal { inline_size } else { block_size };+ Some(+ match resolve(size.length_percentage().calculated_pointer(), is_horizontal, extent) {+ Some(px) => style_values::ResolvedSizeOverride::Length(px),+ None => style_values::ResolvedSizeOverride::Keyword(initial),+ },+ )+ };+ let mut resolved = style_values::ResolvedAnchorSizes {+ width: resolve_size(style.width(), true, ComputedSizeKind::Auto),+ min_width: resolve_size(style.min_width(), true, ComputedSizeKind::Auto),+ max_width: resolve_size(style.max_width(), true, ComputedSizeKind::None),+ height: resolve_size(style.height(), false, ComputedSizeKind::Auto),+ min_height: resolve_size(style.min_height(), false, ComputedSizeKind::Auto),+ max_height: resolve_size(style.max_height(), false, ComputedSizeKind::None),+ ..Default::default()+ };+ let mut resolve_margin = |margin: &ComputedLengthPercentageOrAuto, is_horizontal: bool| {+ let length_percentage = margin.length_percentage()?;+ if !length_percentage.contains_anchor_function() {+ return None;+ }+ // NB: Margin percentages resolve against the inline size of the containing block in both axes.+ Some(resolve(length_percentage.calculated_pointer(), is_horizontal, inline_size).unwrap_or_default())+ };+ resolved.margin_top = resolve_margin(style.margin_top(), false);+ resolved.margin_right = resolve_margin(style.margin_right(), true);+ resolved.margin_bottom = resolve_margin(style.margin_bottom(), false);+ resolved.margin_left = resolve_margin(style.margin_left(), true);+ resolved+ }++ /// Makes the resolved anchor sizes of `inputs` visible to the style reads of `node` in this run's records.+ fn install_resolved_anchor_sizes(&self, node: Node, inputs: &abspos_inputs::AbsposLayoutInputs) {+ if inputs.resolved_anchor_sizes.is_empty() {+ return;+ }+ let used = self.used(node);+ if used.anchor_resolved_values.get().is_none() {+ let _ = used+ .anchor_resolved_values+ .set(Box::new(style_values::AnchorResolvedValues::new(+ &inputs.resolved_anchor_sizes,+ )));+ }+ }+/// https://drafts.csswg.org/css-anchor-position-1/#anchor-center/// If the positioned box has a default anchor box, then it is centered (insofar as possible) over the default/// anchor box in the relevant axis.@@ -1321,14 +1433,20 @@ unsafe extern "C" fn resolve_anchor_non_math_function(context: *mut c_void, shellet engine = unsafe { &*context.engine };// SAFETY: `shell` is the live Rust style-value data retained by the CSS// calc core's non-math-function node for this synchronous resolution.- let StyleValueData::Anchor {- has_anchor_name,- anchor_name: explicit_anchor_name,- anchor_side,- fallback_value,- } = (unsafe { &*shell.cast::<StyleValueData>() })- else {- return std::ptr::null();+ let (has_anchor_name, explicit_anchor_name, fallback_value) = match unsafe { &*shell.cast::<StyleValueData>() } {+ StyleValueData::Anchor {+ has_anchor_name,+ anchor_name,+ fallback_value,+ ..+ }+ | StyleValueData::AnchorSize {+ has_anchor_name,+ anchor_name,+ fallback_value,+ ..+ } => (*has_anchor_name, anchor_name, fallback_value),+ _ => return std::ptr::null(),};let style = engine.style(context.positioned_box);let bound_anchor_name = has_anchor_name.then(|| explicit_anchor_name.to_fly_string());@@ -1349,68 +1467,57 @@ unsafe extern "C" fn resolve_anchor_non_math_function(context: *mut c_void, shelcontext.containing_block_geometry.as_ref(),context.entry_coordinate_space_box,);- if let Some(side) = engine.anchor_side(- anchor_side_from_style_value(anchor_side.data()),- rect,- context.positioned_box,- context.containing_block,- context.is_from_end,- context.is_horizontal_axis,- ) {- // SAFETY: The state pointer is live and uniquely used by this- // synchronous resolver.- let resolution_state = unsafe { &mut *context.resolution_state };- engine.note_resolved_anchor_function(anchor_box, context.is_horizontal_axis, resolution_state);- let inset = if context.is_from_end {- context.containing_block_extent - side- } else {- side- };+ // SAFETY: As above.+ let resolved = match unsafe { &*shell.cast::<StyleValueData>() } {+ StyleValueData::Anchor { anchor_side, .. } => engine+ .anchor_side(+ anchor_side_from_style_value(anchor_side.data()),+ rect,+ context.positioned_box,+ context.containing_block,+ context.is_from_end,+ context.is_horizontal_axis,+ )+ .map(|side| {+ // SAFETY: The state pointer is live and uniquely used by this+ // synchronous resolver.+ let resolution_state = unsafe { &mut *context.resolution_state };+ engine.note_resolved_anchor_function(anchor_box, context.is_horizontal_axis, resolution_state);+ if context.is_from_end {+ context.containing_block_extent - side+ } else {+ side+ }+ }),+ StyleValueData::AnchorSize {+ has_anchor_size,+ anchor_size,+ ..+ } => Some(engine.anchor_size(+ has_anchor_size.then_some(*anchor_size),+ rect,+ context.positioned_box,+ context.containing_block,+ context.is_horizontal_axis,+ )),+ _ => unreachable!("the shell was matched as an anchor function above"),+ };+ if let Some(resolved) = resolved {// SAFETY: This CSS crate export transfers one Arc reference to// the external-resolution snapshot, which releases it after// calc resolution.- return calc_node_create_px_dimension(inset.to_double());- }- }-- match fallback_value.optional_data() {- None => std::ptr::null(),- Some(StyleValueData::Length { value, unit }) => {- // Computed anchor() fallbacks hold absolute lengths only; relative- // units carry NaN canonical ratios.- let ratio = crate::css::style_compute::LENGTH_UNIT_CANONICAL_PX_RATIOS[*unit as usize];- assert!(ratio.is_finite());- calc_node_create_px_dimension(CssPixels::nearest_value_for(*value * ratio).to_double())- }- Some(StyleValueData::Percentage { value }) => {- calc_node_create_px_dimension(context.containing_block_extent.to_double() * (value / 100.0))- }- Some(StyleValueData::Calculated { .. }) => {- let mut nested_context = *context;- // SAFETY: The anchor() shell retains the fallback calculation for- // this synchronous resolution.- let resolved = unsafe {- style_values::resolve_calc_with_external_resolutions(- fallback_value.pointer().cast(),- context.containing_block_extent,- (&raw mut nested_context).cast(),- Some(resolve_anchor_non_math_function),- )- };- if !resolved.resolved {- return std::ptr::null();- }- calc_node_create_px_dimension(resolved.value)- }- Some(StyleValueData::Anchor { .. }) => {- let mut nested_context = *context;- // SAFETY: The outer anchor() shell retains the nested anchor()- // for this synchronous resolution.- unsafe {- resolve_anchor_non_math_function((&raw mut nested_context).cast(), fallback_value.pointer().cast())- }+ return style_values::calc_node_create_px_dimension(resolved.to_double());}- Some(_) => unreachable!("anchor() fallback must be a length, percentage, calculation or nested anchor()"),+ }++ // SAFETY: The callback context is live for this synchronous resolution.+ unsafe {+ style_values::anchor_function_fallback_node(+ fallback_value,+ context.containing_block_extent,+ std::ptr::from_mut(context).cast(),+ resolve_anchor_non_math_function,+ )}}@@ -2442,6 +2549,7 @@ impl<'pass> AbsposEngine<'pass> {// metrics, the inset-aware inline solve, the pre-inside-layout block// pass, and the definiteness overrides insets and aspect ratios provide.pub(crate) fn dimension_out_of_flow_root(&self, node: Node, inputs: abspos_inputs::AbsposLayoutInputs) {+ self.install_resolved_anchor_sizes(node, &inputs);let (available_space, constraints) = out_of_flow_root_space(inputs);let containing_block_inline_size = available_space.inline_size.to_px_or_zero();let resolved = inputs.resolved_anchor_insets.as_ref();@@ -2526,6 +2634,7 @@ impl<'pass> AbsposEngine<'pass> {inputs: abspos_inputs::AbsposLayoutInputs,automatic_content_block_size_of_inside_layout: Option<CssPixels>,) {+ self.install_resolved_anchor_sizes(node, &inputs);let (available_space, constraints) = out_of_flow_root_space(inputs);let containing_block_size = geometry::LogicalSize {inline_size: available_space.inline_size.to_px_or_zero(),@@ -2716,7 +2825,7 @@ impl<'pass> AbsposEngine<'pass> {child.coordinate_space_box,unresolved_containing_block_info,);- let (containing_block_info, resolved) = if let Some((+ let (containing_block_info, resolved, resolved_anchor_sizes) = if let Some((static_position_rect,position_area_containing_block_info,position_area_geometry,@@ -2725,6 +2834,12 @@ impl<'pass> AbsposEngine<'pass> {)) = position_area_inputs{child.static_position_rect = static_position_rect;+ let resolved_anchor_sizes = self.resolve_anchor_sizes(+ child_box,+ child.containing_block(),+ &position_area_geometry,+ child.coordinate_space_box,+ );let resolved = self.resolve_anchor_insets(child_box,child.containing_block(),@@ -2733,8 +2848,14 @@ impl<'pass> AbsposEngine<'pass> {Some(anchor_box),);let resolved = self.position_area_stretch_insets(child_box, resolved, stretches_inline, stretches_block);- (position_area_containing_block_info, resolved)+ (position_area_containing_block_info, resolved, resolved_anchor_sizes)} else {+ let resolved_anchor_sizes = self.resolve_anchor_sizes(+ child_box,+ child.containing_block(),+ &containing_block_geometry,+ child.coordinate_space_box,+ );let resolved = self.resolve_anchor_insets(child_box,child.containing_block(),@@ -2759,7 +2880,7 @@ impl<'pass> AbsposEngine<'pass> {&mut child.static_position_rect,&mut containing_block_info,);- (containing_block_info, resolved)+ (containing_block_info, resolved, resolved_anchor_sizes)};let inputs = abspos_inputs::AbsposLayoutInputs {containing_block: child.containing_block(),@@ -2767,7 +2888,9 @@ impl<'pass> AbsposEngine<'pass> {static_position_rect: child.static_position_rect,containing_block_info,resolved_anchor_insets: resolved,+ resolved_anchor_sizes,};+ self.install_resolved_anchor_sizes(child_box, &inputs);self.layout_element(run, child_box, inputs);}diff --git a/Libraries/LibWeb/Rust/src/layout/abspos_inputs.rs b/Libraries/LibWeb/Rust/src/layout/abspos_inputs.rsindex ef267336b3d..897a32ad372 100644--- a/Libraries/LibWeb/Rust/src/layout/abspos_inputs.rs+++ b/Libraries/LibWeb/Rust/src/layout/abspos_inputs.rs@@ -65,6 +65,7 @@ pub(crate) struct AbsposLayoutInputs {pub(crate) static_position_rect: StaticPositionRect,pub(crate) containing_block_info: AbsposContainingBlockInfo,pub(crate) resolved_anchor_insets: Option<super::formatting_context::ResolvedAnchorInsets>,+ pub(crate) resolved_anchor_sizes: super::style_values::ResolvedAnchorSizes,}#[derive(Clone, Copy, Debug, PartialEq, Eq)]diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rsindex 023a35a47cf..d62435ac8a9 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs@@ -7140,6 +7140,7 @@ mod tests {derives_from_own_computed_values: true,},resolved_anchor_insets: None,+ resolved_anchor_sizes: Default::default(),}}diff --git a/Libraries/LibWeb/Rust/src/layout/partial_relayout.rs b/Libraries/LibWeb/Rust/src/layout/partial_relayout.rsindex 5217a0fc96c..59a1f57ddcb 100644--- a/Libraries/LibWeb/Rust/src/layout/partial_relayout.rs+++ b/Libraries/LibWeb/Rust/src/layout/partial_relayout.rs@@ -557,6 +557,33 @@ impl LayoutNodeArena {{return None;}+ // Anchor functions resolve against anchors this path does not look up.+ let size_contains_anchor_function = |size: &crate::layout::ComputedSize| {+ size.is_length_percentage() && size.length_percentage().contains_anchor_function()+ };+ let side_contains_anchor_function = |side: &crate::layout::ComputedLengthPercentageOrAuto| {+ side.length_percentage()+ .is_some_and(|length_percentage| length_percentage.contains_anchor_function())+ };+ let surround = style.surround();+ if [+ style.width(),+ style.min_width(),+ style.max_width(),+ style.height(),+ style.min_height(),+ style.max_height(),+ ]+ .into_iter()+ .any(size_contains_anchor_function)+ || [&surround.inset, &surround.margin].into_iter().any(|sides| {+ [&sides.top, &sides.right, &sides.bottom, &sides.left]+ .into_iter()+ .any(side_contains_anchor_function)+ })+ {+ return None;+ }// A static position depends on where the box would have been in flow.let inset = &style.surround().inset;if (inset.left.is_auto() && inset.right.is_auto()) || (inset.top.is_auto() && inset.bottom.is_auto()) {@@ -619,6 +646,7 @@ impl LayoutNodeArena {derives_from_own_computed_values: false,},resolved_anchor_insets: None,+ resolved_anchor_sizes: Default::default(),})}diff --git a/Libraries/LibWeb/Rust/src/layout/sizing_context.rs b/Libraries/LibWeb/Rust/src/layout/sizing_context.rsindex 7843165793c..6b8624e4dd2 100644--- a/Libraries/LibWeb/Rust/src/layout/sizing_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/sizing_context.rs@@ -131,14 +131,24 @@ impl<'pass> SizingContext<'pass> {pub(super) fn style(&self, node: Node) -> StyleValues<'pass> {let kind = self.callbacks.node_data(node).kind.get();- if let Some((cached_node, payloads)) = self.style_cache.get()- && cached_node == node- {- return StyleValues::new(payloads).for_kind(kind);- }- let payloads = self.callbacks.style_payloads(node);- self.style_cache.set(Some((node, payloads)));- StyleValues::new(payloads).for_kind(kind)+ let payloads = match self.style_cache.get() {+ Some((cached_node, payloads)) if cached_node == node => payloads,+ _ => {+ let payloads = self.callbacks.style_payloads(node);+ self.style_cache.set(Some((node, payloads)));+ payloads+ }+ };+ let style = StyleValues::new(payloads).for_kind(kind);+ if !style.is_absolutely_positioned() {+ return style;+ }+ let anchor_resolved_values = self+ .records+ .used_values_if_owned(node)+ .and_then(|used| used.anchor_resolved_values.get())+ .map(|resolved| &**resolved);+ style.with_anchor_resolved_values(anchor_resolved_values)}#[track_caller]diff --git a/Libraries/LibWeb/Rust/src/layout/style_values.rs b/Libraries/LibWeb/Rust/src/layout/style_values.rsindex f0974b55f1c..757ad50c66d 100644--- a/Libraries/LibWeb/Rust/src/layout/style_values.rs+++ b/Libraries/LibWeb/Rust/src/layout/style_values.rs@@ -84,6 +84,90 @@ impl InsetValue<'_> {}}+/// A sizing property whose computed value holds anchor-size() functions, as the abspos engine resolved it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum ResolvedSizeOverride {+ Length(CssPixels),+ Keyword(ComputedSizeKind),+}++/// The sizing and margin properties of one positioned box whose computed values hold anchor-size() functions, with+/// those functions resolved by the abspos engine. A property without one stays None and reads from style. Margins+/// also carry the zero that auto resolves to in the axes a position area or anchor-center aligns the box in.+/// https://drafts.csswg.org/css-anchor-position-1/#anchor-size-fn+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub(crate) struct ResolvedAnchorSizes {+ pub(crate) width: Option<ResolvedSizeOverride>,+ pub(crate) min_width: Option<ResolvedSizeOverride>,+ pub(crate) max_width: Option<ResolvedSizeOverride>,+ pub(crate) height: Option<ResolvedSizeOverride>,+ pub(crate) min_height: Option<ResolvedSizeOverride>,+ pub(crate) max_height: Option<ResolvedSizeOverride>,+ pub(crate) margin_top: Option<CssPixels>,+ pub(crate) margin_right: Option<CssPixels>,+ pub(crate) margin_bottom: Option<CssPixels>,+ pub(crate) margin_left: Option<CssPixels>,+}++impl ResolvedAnchorSizes {+ pub(crate) fn is_empty(&self) -> bool {+ *self == Self::default()+ }+}++/// The computed values `ResolvedAnchorSizes` stands for, which style reads borrow.+#[derive(Default)]+pub(crate) struct AnchorResolvedValues {+ width: Option<ComputedSize>,+ min_width: Option<ComputedSize>,+ max_width: Option<ComputedSize>,+ height: Option<ComputedSize>,+ min_height: Option<ComputedSize>,+ max_height: Option<ComputedSize>,+ margin_top: Option<ComputedLengthPercentageOrAuto>,+ margin_right: Option<ComputedLengthPercentageOrAuto>,+ margin_bottom: Option<ComputedLengthPercentageOrAuto>,+ margin_left: Option<ComputedLengthPercentageOrAuto>,+}++impl std::fmt::Debug for AnchorResolvedValues {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.debug_struct("AnchorResolvedValues").finish_non_exhaustive()+ }+}++impl AnchorResolvedValues {+ pub(crate) fn new(resolved: &ResolvedAnchorSizes) -> Self {+ let size = |value: Option<ResolvedSizeOverride>| {+ value.map(|value| match value {+ ResolvedSizeOverride::Length(px) => ComputedSize {+ kind: ComputedSizeKind::Length,+ value: ComputedStyleValueHandle::length(px.to_double()),+ },+ ResolvedSizeOverride::Keyword(kind) => ComputedSize::keyword(kind),+ })+ };+ let margin = |value: Option<CssPixels>| {+ value.map(|px| ComputedLengthPercentageOrAuto {+ is_auto: false,+ value: ComputedStyleValueHandle::length(px.to_double()),+ })+ };+ Self {+ width: size(resolved.width),+ min_width: size(resolved.min_width),+ max_width: size(resolved.max_width),+ height: size(resolved.height),+ min_height: size(resolved.min_height),+ max_height: size(resolved.max_height),+ margin_top: margin(resolved.margin_top),+ margin_right: margin(resolved.margin_right),+ margin_bottom: margin(resolved.margin_bottom),+ margin_left: margin(resolved.margin_left),+ }+ }+}+/// A padding read: the style's, or zero for a non-devolvable widget.#[derive(Clone, Copy)]pub(crate) enum PaddingValue<'a> {@@ -116,6 +200,7 @@ impl PaddingValue<'_> {pub(crate) struct StyleValues<'a> {style: ComputedValuesView<'a>,resolved_anchor_insets: Option<&'a formatting_context::ResolvedAnchorInsets>,+ anchor_resolved_values: Option<&'a AnchorResolvedValues>,vertical_align_override: Option<u8>,is_non_devolvable_widget: bool,}@@ -134,6 +219,7 @@ impl<'a> StyleValues<'a> {Self {style: ComputedValuesView::new(&payloads.groups),resolved_anchor_insets: None,+ anchor_resolved_values: None,vertical_align_override: None,is_non_devolvable_widget: false,}@@ -160,6 +246,71 @@ impl<'a> StyleValues<'a> {self}+ pub(crate) fn with_anchor_resolved_values(mut self, resolved: Option<&'a AnchorResolvedValues>) -> Self {+ self.anchor_resolved_values = resolved;+ self+ }++ pub(crate) fn width(self) -> &'a ComputedSize {+ self.anchor_resolved_values+ .and_then(|resolved| resolved.width.as_ref())+ .unwrap_or_else(|| unresolvable_anchor_size_or(self.style.width(), auto_computed_size()))+ }++ pub(crate) fn min_width(self) -> &'a ComputedSize {+ self.anchor_resolved_values+ .and_then(|resolved| resolved.min_width.as_ref())+ .unwrap_or_else(|| unresolvable_anchor_size_or(self.style.min_width(), auto_computed_size()))+ }++ pub(crate) fn max_width(self) -> &'a ComputedSize {+ self.anchor_resolved_values+ .and_then(|resolved| resolved.max_width.as_ref())+ .unwrap_or_else(|| unresolvable_anchor_size_or(self.style.max_width(), none_computed_size()))+ }++ pub(crate) fn height(self) -> &'a ComputedSize {+ self.anchor_resolved_values+ .and_then(|resolved| resolved.height.as_ref())+ .unwrap_or_else(|| unresolvable_anchor_size_or(self.style.height(), auto_computed_size()))+ }++ pub(crate) fn min_height(self) -> &'a ComputedSize {+ self.anchor_resolved_values+ .and_then(|resolved| resolved.min_height.as_ref())+ .unwrap_or_else(|| unresolvable_anchor_size_or(self.style.min_height(), auto_computed_size()))+ }++ pub(crate) fn max_height(self) -> &'a ComputedSize {+ self.anchor_resolved_values+ .and_then(|resolved| resolved.max_height.as_ref())+ .unwrap_or_else(|| unresolvable_anchor_size_or(self.style.max_height(), none_computed_size()))+ }++ pub(crate) fn margin_top(self) -> &'a ComputedLengthPercentageOrAuto {+ self.anchor_resolved_values+ .and_then(|resolved| resolved.margin_top.as_ref())+ .unwrap_or_else(|| self.style.margin_top())+ }++ pub(crate) fn margin_right(self) -> &'a ComputedLengthPercentageOrAuto {+ self.anchor_resolved_values+ .and_then(|resolved| resolved.margin_right.as_ref())+ .unwrap_or_else(|| self.style.margin_right())+ }++ pub(crate) fn margin_bottom(self) -> &'a ComputedLengthPercentageOrAuto {+ self.anchor_resolved_values+ .and_then(|resolved| resolved.margin_bottom.as_ref())+ .unwrap_or_else(|| self.style.margin_bottom())+ }++ pub(crate) fn margin_left(self) -> &'a ComputedLengthPercentageOrAuto {+ self.anchor_resolved_values+ .and_then(|resolved| resolved.margin_left.as_ref())+ .unwrap_or_else(|| self.style.margin_left())+ }+fn bare_anchor_wrapper(self, field: InsetField) -> Option<&'a crate::css::style_value::StyleValueData> {let values = self.style.surround();let handle = match field {@@ -279,6 +430,126 @@ impl<'a> StyleValues<'a> {}}+/// `size`, or `initial` when `size` holds an anchor function that is unresolvable and has no fallback value.+/// https://drafts.csswg.org/css-anchor-position-1/#anchor-size-resolution+/// If no fallback value is specified, it makes the declaration referencing it invalid at computed-value time.+/// NB: Outside of the resolutions the abspos engine installs, an anchor function is unresolvable.+fn unresolvable_anchor_size_or<'a>(size: &'a ComputedSize, initial: &'static ComputedSize) -> &'a ComputedSize {+ if !size.is_length_percentage() || !size.length_percentage().contains_anchor_function() {+ return size;+ }+ let mut percentage_basis = CssPixels::default();+ // SAFETY: The callback context is the percentage basis, live for this synchronous resolution.+ let resolved = unsafe {+ resolve_calc_with_external_resolutions(+ size.length_percentage().calculated_pointer(),+ percentage_basis,+ (&raw mut percentage_basis).cast(),+ Some(resolve_unresolvable_anchor_function),+ )+ };+ if resolved.resolved { size } else { initial }+}++/// A px calc node, holding one reference for the external-resolution snapshot that releases it.+pub(crate) fn calc_node_create_px_dimension(value: f64) -> *const c_void {+ crate::css::calc::rust_calc_node_create_numeric_dimension(+ formatting_context::CALC_NUMERIC_KIND_LENGTH,+ value,+ crate::css::style_compute::px_length_unit(),+ )+ .cast()+}++/// The calc node the fallback value of an unresolvable anchor() or anchor-size() function resolves to, or null when+/// it has none. Nested anchor functions resolve through `resolve_non_math_function`.+/// https://drafts.csswg.org/css-anchor-position-1/#anchor-resolution+///+/// # Safety+/// `callback_context` must be what `resolve_non_math_function` expects, and stay live for the resolution.+pub(crate) unsafe fn anchor_function_fallback_node(+ fallback_value: &crate::css::style_value::RetainedStyleValueData,+ percentage_basis: CssPixels,+ callback_context: *mut c_void,+ resolve_non_math_function: unsafe extern "C" fn(*mut c_void, *const c_void) -> *const c_void,+) -> *const c_void {+ use crate::css::style_value::StyleValueData;+ match fallback_value.optional_data() {+ None => std::ptr::null(),+ Some(StyleValueData::Length { value, unit }) => {+ // Computed anchor() fallbacks hold absolute lengths only; relative+ // units carry NaN canonical ratios.+ let ratio = crate::css::style_compute::LENGTH_UNIT_CANONICAL_PX_RATIOS[*unit as usize];+ assert!(ratio.is_finite());+ calc_node_create_px_dimension(CssPixels::nearest_value_for(*value * ratio).to_double())+ }+ Some(StyleValueData::Percentage { value }) => {+ calc_node_create_px_dimension(percentage_basis.to_double() * (value / 100.0))+ }+ Some(StyleValueData::Calculated { .. }) => {+ // SAFETY: The anchor function shell retains the fallback calculation for+ // this synchronous resolution.+ let resolved = unsafe {+ resolve_calc_with_external_resolutions(+ fallback_value.pointer().cast(),+ percentage_basis,+ callback_context,+ Some(resolve_non_math_function),+ )+ };+ if !resolved.resolved {+ return std::ptr::null();+ }+ calc_node_create_px_dimension(resolved.value)+ }+ // SAFETY: The outer anchor function shell retains the nested one for this synchronous resolution.+ Some(StyleValueData::Anchor { .. } | StyleValueData::AnchorSize { .. }) => unsafe {+ resolve_non_math_function(callback_context, fallback_value.pointer().cast())+ },+ Some(_) => {+ unreachable!("anchor function fallback must be a length, percentage, calculation or anchor function")+ }+ }+}++/// Resolves an anchor() or anchor-size() function outside the abspos engine, where it is unresolvable and resolves+/// to its fallback value. The callback context is the percentage basis.+unsafe extern "C" fn resolve_unresolvable_anchor_function(context: *mut c_void, shell: *const c_void) -> *const c_void {+ use crate::css::style_value::StyleValueData;+ // SAFETY: The context is the percentage basis resolve_calc_with_unresolvable_anchor_functions passes.+ let percentage_basis = unsafe { *context.cast::<CssPixels>() };+ // SAFETY: `shell` is the live style value the calc core's non-math-function node retains.+ match unsafe { &*shell.cast::<StyleValueData>() } {+ StyleValueData::Anchor { fallback_value, .. } | StyleValueData::AnchorSize { fallback_value, .. } => unsafe {+ anchor_function_fallback_node(+ fallback_value,+ percentage_basis,+ context,+ resolve_unresolvable_anchor_function,+ )+ },+ _ => std::ptr::null(),+ }+}++/// Resolves `calculated`, whose anchor functions are unresolvable, to px. A function without a fallback value makes+/// the declaration invalid at computed-value time, which this approximates as zero.+pub(crate) fn resolve_calc_with_unresolvable_anchor_functions(+ calculated: *const c_void,+ mut percentage_basis: CssPixels,+) -> f64 {+ // SAFETY: The callback context is the percentage basis, live for this synchronous resolution.+ let resolved = unsafe {+ resolve_calc_with_external_resolutions(+ calculated,+ percentage_basis,+ (&raw mut percentage_basis).cast(),+ Some(resolve_unresolvable_anchor_function),+ )+ };+ if resolved.resolved { resolved.value } else { 0.0 }+}+pub(crate) unsafe fn resolve_calc_with_external_resolutions(calculated: *const c_void,percentage_basis: CssPixels,diff --git a/Libraries/LibWeb/Rust/src/layout/used_values.rs b/Libraries/LibWeb/Rust/src/layout/used_values.rsindex c9f4cc1e290..3174ab0c00f 100644--- a/Libraries/LibWeb/Rust/src/layout/used_values.rs+++ b/Libraries/LibWeb/Rust/src/layout/used_values.rs@@ -377,6 +377,8 @@ pub(crate) struct UsedValues {pub(crate) line_data: RefCell<LineDataState>,pub(crate) rare_data: LazyRefCell<UsedValuesRareData>,+ /// The anchor-size() resolutions of an absolutely positioned box, set once as the abspos engine places it.+ pub(crate) anchor_resolved_values: std::cell::OnceCell<Box<style_values::AnchorResolvedValues>>,pub(crate) held_committed_fragment: fragment_tree::HeldCommittedFragmentCell,}@@ -428,6 +430,7 @@ impl Default for UsedValues {has_descendant_that_depends_on_percentage_block_size: Cell::new(false),line_data: RefCell::new(LineDataState::Empty),rare_data: LazyRefCell::new(),+ anchor_resolved_values: std::cell::OnceCell::new(),held_committed_fragment: fragment_tree::HeldCommittedFragmentCell::default(),}}diff --git a/Tests/LibWeb/Text/expected/css/anchor-size-without-fallback.txt b/Tests/LibWeb/Text/expected/css/anchor-size-without-fallback.txtnew file mode 100644index 00000000000..53be64e281d--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/anchor-size-without-fallback.txt@@ -0,0 +1,8 @@+width: anchor-size(--a width): 200+max-width: anchor-size(--a width): 200+position: relative; width: anchor-size(--a width): 200+width: anchor-size(--a width, 33px): 33+position: absolute; width: anchor-size(--missing width, 2em): 20+position: absolute; width: calc(anchor-size(--missing width, 3em) + 1px): 31+position: absolute; width: anchor-size(--missing width, 10cqw): 20+position: absolute; position-anchor: --a; width: anchor-size(width, 2em): 50diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-invalid-fallback.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-invalid-fallback.txtindex c4c4fa8121d..04a1fee9f37 100644--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-invalid-fallback.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-invalid-fallback.txt@@ -2,25 +2,25 @@ Harness status: OKFound 39 tests-25 Pass-14 Fail-Fail Element can be anchor positioned-Fail Element can use <length> fallback if present-Fail Element can use <length> fallback with percentage+29 Pass+10 Fail+Pass Element can be anchor positioned+Pass Element can use <length> fallback if present+Pass Element can use <length> fallback with percentageFail Element can use <length> fallback for max size with percentage-Fail Element can use <length> fallback for margin with percentage+Pass Element can use <length> fallback for margin with percentagePass Invalid anchor function, leftPass Invalid anchor function, rightPass Invalid anchor function, bottomPass Invalid anchor function, top-Fail Invalid anchor function, width-Fail Invalid anchor function, height+Pass Invalid anchor function, width+Pass Invalid anchor function, heightFail Invalid anchor function, min-widthFail Invalid anchor function, min-heightFail Invalid anchor function, max-widthFail Invalid anchor function, max-heightPass Invalid anchor function, --unknown left-Fail Invalid anchor function, --unknown width+Pass Invalid anchor function, --unknown widthPass Invalid anchor function, cross-axis query (vertical)Pass Invalid anchor function, cross-axis query (horizontal)Pass Invalid anchor function, anchor() in sizing property@@ -28,12 +28,12 @@ Pass Invalid anchor function, nested leftPass Invalid anchor function, nested rightPass Invalid anchor function, nested bottomPass Invalid anchor function, nested top-Pass Invalid anchor function, nested min-width-Pass Invalid anchor function, nested min-height-Pass Invalid anchor function, nested max-width-Pass Invalid anchor function, nested max-height+Fail Invalid anchor function, nested min-width+Fail Invalid anchor function, nested min-height+Fail Invalid anchor function, nested max-width+Fail Invalid anchor function, nested max-heightPass Invalid anchor function, invalid anchor() in fallback-Fail Invalid anchor function, invalid anchor-size() in fallback+Pass Invalid anchor function, invalid anchor-size() in fallbackPass Invalid anchor function, min()Pass Invalid anchor function, max()Pass Invalid anchor function, abs()diff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-name-003.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-name-003.txtindex 821466d2f99..a0cecf92b23 100644--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-name-003.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-name-003.txt@@ -2,44 +2,43 @@ Harness status: OKFound 39 tests-4 Pass-35 Fail-Fail .target 1-Fail .target 2+39 Pass+Pass .target 1+Pass .target 2Pass .target 3-Fail .target 4-Fail .target 5-Fail .target 6-Fail .target 7-Fail .target 8-Fail .target 9+Pass .target 4+Pass .target 5+Pass .target 6+Pass .target 7+Pass .target 8+Pass .target 9Pass .target 10-Fail .target 11-Fail .target 12-Fail .target 13-Fail .target 14-Fail .target 15-Fail .target 16+Pass .target 11+Pass .target 12+Pass .target 13+Pass .target 14+Pass .target 15+Pass .target 16Pass .target 17-Fail .target 18-Fail .target 19-Fail .target 20-Fail .target 21-Fail .target 22-Fail .target 23-Fail .target 24-Fail .target 25-Fail .target 26-Fail .target 27-Fail .target 28-Fail .target 29-Fail .target 30-Fail .target 31+Pass .target 18+Pass .target 19+Pass .target 20+Pass .target 21+Pass .target 22+Pass .target 23+Pass .target 24+Pass .target 25+Pass .target 26+Pass .target 27+Pass .target 28+Pass .target 29+Pass .target 30+Pass .target 31Pass .target 32-Fail .target 33-Fail .target 34-Fail .target 35-Fail .target 36-Fail .target 37-Fail .target 38-Fail .target 39\ No newline at end of file+Pass .target 33+Pass .target 34+Pass .target 35+Pass .target 36+Pass .target 37+Pass .target 38+Pass .target 39\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-name-inline-001.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-name-inline-001.txtindex 4ef43a76c6e..e83d35d2853 100644--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-name-inline-001.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-name-inline-001.txt@@ -2,11 +2,12 @@ Harness status: OKFound 7 tests-7 Fail+3 Pass+4 FailFail .target 1Fail .target 2Fail .target 3Fail .target 4-Fail .target 5-Fail .target 6-Fail .target 7\ No newline at end of file+Pass .target 5+Pass .target 6+Pass .target 7\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-position-dynamic-003.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-position-dynamic-003.txtindex 7b69ed92d3e..9dec10a18f5 100644--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-position-dynamic-003.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-position-dynamic-003.txt@@ -2,14 +2,14 @@ Harness status: OKFound 10 tests-10 Fail-Fail .target 1-Fail .target 2-Fail .target 3-Fail .target 4-Fail .target 5-Fail .after .target 6-Fail .after .target 7-Fail .after .target 8-Fail .after .target 9-Fail .after .target 10\ No newline at end of file+10 Pass+Pass .target 1+Pass .target 2+Pass .target 3+Pass .target 4+Pass .target 5+Pass .after .target 6+Pass .after .target 7+Pass .after .target 8+Pass .after .target 9+Pass .after .target 10\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-query-fallback.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-query-fallback.txtindex 0446c29a965..5d4125def11 100644--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-query-fallback.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-query-fallback.txt@@ -2,10 +2,9 @@ Harness status: OKFound 16 tests-10 Pass-6 Fail+16 PassPass .target 1-Fail .target 2+Pass .target 2Pass .target 3Pass .target 4Pass .target 5@@ -13,10 +12,10 @@ Pass .target 6Pass .target 7Pass .target 8Pass .target 9-Fail .target 10+Pass .target 10Pass .target 11Pass .target 12-Fail .target 13-Fail .target 14-Fail .target 15-Fail .target 16\ No newline at end of file+Pass .target 13+Pass .target 14+Pass .target 15+Pass .target 16\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-001.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-001.txtindex e3039d0d853..896541c86d9 100644--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-001.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-001.txt@@ -2,33 +2,32 @@ Harness status: OKFound 28 tests-2 Pass-26 Fail-Fail .target 1-Fail .target 2-Fail .target 3-Fail .target 4-Fail .target 5-Fail .target 6-Fail .target 7-Fail .target 8-Fail .target 9-Fail .target 10-Fail .target 11-Fail .target 12-Fail .target 13+28 Pass+Pass .target 1+Pass .target 2+Pass .target 3+Pass .target 4+Pass .target 5+Pass .target 6+Pass .target 7+Pass .target 8+Pass .target 9+Pass .target 10+Pass .target 11+Pass .target 12+Pass .target 13Pass .target 14-Fail .target 15-Fail .target 16-Fail .target 17-Fail .target 18-Fail .target 19-Fail .target 20-Fail .target 21-Fail .target 22-Fail .target 23+Pass .target 15+Pass .target 16+Pass .target 17+Pass .target 18+Pass .target 19+Pass .target 20+Pass .target 21+Pass .target 22+Pass .target 23Pass .target 24-Fail .target 25-Fail .target 26-Fail .target 27-Fail .target 28\ No newline at end of file+Pass .target 25+Pass .target 26+Pass .target 27+Pass .target 28\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-parse-valid.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-parse-valid.txtindex ab78a31e7db..81674432873 100644--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-parse-valid.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-parse-valid.txt@@ -2,8 +2,7 @@ Harness status: OKFound 4305 tests-4289 Pass-16 Fail+4305 PassPass e.style['width'] = "anchor-size(--foo width)" should set the property valuePass e.style['width'] = "anchor-size(width --foo)" should set the property valuePass e.style['width'] = "anchor-size(--foo width, 1px)" should set the property value@@ -4292,20 +4291,20 @@ Pass e.style['width'] = "anchor-size()" should set the property valuePass e.style['width'] = "anchor-size(--foo)" should set the property valuePass e.style['width'] = "anchor-size(--foo, 10px)" should set the property valuePass e.style['width'] = "anchor-size(10px)" should set the property value-Fail e.style['width'] = "calc((anchor-size(--foo width) + anchor-size(--bar height)) / 2)" should set the property value-Fail e.style['width'] = "calc(0.5 * (anchor-size(--foo width) + anchor-size(--bar height)))" should set the property value-Fail e.style['width'] = "anchor-size(--foo width, calc(0.5 * anchor-size(--bar height)))" should set the property value-Fail e.style['width'] = "min(100px, 10%, anchor-size(--foo width), anchor-size(--bar height))" should set the property value-Fail e.style['width'] = "calc(anchor-size(--foo width, 1px) + 10%)" should set the property value-Fail e.style['max-width'] = "calc((anchor-size(--foo width) + anchor-size(--bar height)) / 2)" should set the property value-Fail e.style['max-width'] = "calc(0.5 * (anchor-size(--foo width) + anchor-size(--bar height)))" should set the property value-Fail e.style['max-width'] = "anchor-size(--foo width, calc(0.5 * anchor-size(--bar height)))" should set the property value-Fail e.style['max-width'] = "min(100px, 10%, anchor-size(--foo width), anchor-size(--bar height))" should set the property value-Fail e.style['max-width'] = "calc(anchor-size(--foo width, 1px) + 10%)" should set the property value-Fail e.style['margin-left'] = "calc((anchor-size(--foo width) + anchor-size(--bar height)) / 2)" should set the property value-Fail e.style['margin-left'] = "calc(0.5 * (anchor-size(--foo width) + anchor-size(--bar height)))" should set the property value-Fail e.style['margin-left'] = "anchor-size(--foo width, calc(0.5 * anchor-size(--bar height)))" should set the property value-Fail e.style['margin-left'] = "min(100px, 10%, anchor-size(--foo width), anchor-size(--bar height))" should set the property value-Fail e.style['margin-left'] = "calc(anchor-size(--foo width, 1px) + 10%)" should set the property value+Pass e.style['width'] = "calc((anchor-size(--foo width) + anchor-size(--bar height)) / 2)" should set the property value+Pass e.style['width'] = "calc(0.5 * (anchor-size(--foo width) + anchor-size(--bar height)))" should set the property value+Pass e.style['width'] = "anchor-size(--foo width, calc(0.5 * anchor-size(--bar height)))" should set the property value+Pass e.style['width'] = "min(100px, 10%, anchor-size(--foo width), anchor-size(--bar height))" should set the property value+Pass e.style['width'] = "calc(anchor-size(--foo width, 1px) + 10%)" should set the property value+Pass e.style['max-width'] = "calc((anchor-size(--foo width) + anchor-size(--bar height)) / 2)" should set the property value+Pass e.style['max-width'] = "calc(0.5 * (anchor-size(--foo width) + anchor-size(--bar height)))" should set the property value+Pass e.style['max-width'] = "anchor-size(--foo width, calc(0.5 * anchor-size(--bar height)))" should set the property value+Pass e.style['max-width'] = "min(100px, 10%, anchor-size(--foo width), anchor-size(--bar height))" should set the property value+Pass e.style['max-width'] = "calc(anchor-size(--foo width, 1px) + 10%)" should set the property value+Pass e.style['margin-left'] = "calc((anchor-size(--foo width) + anchor-size(--bar height)) / 2)" should set the property value+Pass e.style['margin-left'] = "calc(0.5 * (anchor-size(--foo width) + anchor-size(--bar height)))" should set the property value+Pass e.style['margin-left'] = "anchor-size(--foo width, calc(0.5 * anchor-size(--bar height)))" should set the property value+Pass e.style['margin-left'] = "min(100px, 10%, anchor-size(--foo width), anchor-size(--bar height))" should set the property value+Pass e.style['margin-left'] = "calc(anchor-size(--foo width, 1px) + 10%)" should set the property valuePass e.style['width'] = "anchor-size(--foo width, 0)" should set the property value-Fail e.style['width'] = "calc(anchor-size(--foo width, 0))" should set the property value\ No newline at end of file+Pass e.style['width'] = "calc(anchor-size(--foo width, 0))" should set the property value\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-replaced-001.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-replaced-001.txtindex f1242ca077b..6c67023bd65 100644--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-replaced-001.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-replaced-001.txt@@ -2,17 +2,16 @@ Harness status: OKFound 12 tests-4 Pass-8 Fail-Fail .target 1-Fail .target 2+12 Pass+Pass .target 1+Pass .target 2Pass .target 3Pass .target 4-Fail .target 5-Fail .target 6-Fail .target 7-Fail .target 8+Pass .target 5+Pass .target 6+Pass .target 7+Pass .target 8Pass .target 9Pass .target 10-Fail .target 11-Fail .target 12\ No newline at end of file+Pass .target 11+Pass .target 12\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-writing-modes-001.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-writing-modes-001.txtindex c506f6c7f10..6e483519d53 100644--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-writing-modes-001.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-anchor-position/anchor-size-writing-modes-001.txt@@ -2,28 +2,28 @@ Harness status: OKFound 24 tests-24 Fail-Fail .target 1-Fail .target 2-Fail .target 3-Fail .target 4-Fail .target 5-Fail .target 6-Fail .target 7-Fail .target 8-Fail .target 9-Fail .target 10-Fail .target 11-Fail .target 12-Fail .target 13-Fail .target 14-Fail .target 15-Fail .target 16-Fail .target 17-Fail .target 18-Fail .target 19-Fail .target 20-Fail .target 21-Fail .target 22-Fail .target 23-Fail .target 24\ No newline at end of file+24 Pass+Pass .target 1+Pass .target 2+Pass .target 3+Pass .target 4+Pass .target 5+Pass .target 6+Pass .target 7+Pass .target 8+Pass .target 9+Pass .target 10+Pass .target 11+Pass .target 12+Pass .target 13+Pass .target 14+Pass .target 15+Pass .target 16+Pass .target 17+Pass .target 18+Pass .target 19+Pass .target 20+Pass .target 21+Pass .target 22+Pass .target 23+Pass .target 24\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/css/anchor-size-without-fallback.html b/Tests/LibWeb/Text/input/css/anchor-size-without-fallback.htmlnew file mode 100644index 00000000000..2755ad9d122--- /dev/null+++ b/Tests/LibWeb/Text/input/css/anchor-size-without-fallback.html@@ -0,0 +1,38 @@+<!DOCTYPE html>+<style>+#cb {+ position: relative;+ width: 200px;+ height: 200px;+ font-size: 10px;+ container-type: size;+}+#anchor {+ anchor-name: --a;+ position: absolute;+ width: 50px;+ height: 40px;+}+</style>+<div id="cb"><div id="anchor"></div><div id="main"></div></div>+<script src="../include.js"></script>+<script>+ test(() => {+ for (const style of [+ "width: anchor-size(--a width)",+ "max-width: anchor-size(--a width)",+ "position: relative; width: anchor-size(--a width)",+ "width: anchor-size(--a width, 33px)",+ "position: absolute; width: anchor-size(--missing width, 2em)",+ "position: absolute; width: calc(anchor-size(--missing width, 3em) + 1px)",+ "position: absolute; width: anchor-size(--missing width, 10cqw)",+ "position: absolute; position-anchor: --a; width: anchor-size(width, 2em)",+ ]) {+ const target = document.createElement("div");+ target.style = style;+ main.append(target);+ println(`${style}: ${target.getBoundingClientRect().width}`);+ target.remove();+ }+ });+</script>