Skip to content

Truly independent web browser

LibWeb: Resolve anchor-size() in computed min and max sizes

Andreas Klingc7488d78cb8c
diff --git a/Libraries/LibWeb/CSS/CSSStyleProperties.cpp b/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
index 4aa749360eb..8116c9bd6b6 100644
--- a/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
+++ b/Libraries/LibWeb/CSS/CSSStyleProperties.cpp
@@ -657,6 +657,32 @@ static void ensure_pseudo_element_style_for_cssom(Layout::BegunRead const& read,
static RefPtr<StyleValue const> resolve_color_style_value(StyleValue const&, Color, Optional<ColorResolutionStyle> = {});
+static bool is_min_or_max_size_property(PropertyID property_id)
+{
+ return first_is_one_of(property_id,
+ PropertyID::MaxBlockSize, PropertyID::MaxHeight, PropertyID::MaxInlineSize, PropertyID::MaxWidth,
+ PropertyID::MinBlockSize, PropertyID::MinHeight, PropertyID::MinInlineSize, PropertyID::MinWidth);
+}
+
+static bool min_or_max_size_holds_anchor_function(ComputedValues const& style, PropertyID property_id)
+{
+ // NB: computed_style_value() maps a logical alias to its physical property.
+ return style.computed_style_value(property_id)->contains_anchor_function();
+}
+
+// NB: The computed value of a min or max sizing property resolves its anchor-size() functions. Where layout did not
+// resolve them against an anchor box, they are unresolvable: each resolves to its fallback value, and one without
+// makes the declaration invalid at computed-value time.
+static NonnullRefPtr<StyleValue const> resolve_unresolvable_anchor_functions(PropertyID property_id, NonnullRefPtr<StyleValue const> computed_value)
+{
+ bool is_invalid = false;
+ if (auto const* substituted = StyleValueFFI::rust_style_value_with_unresolvable_anchor_functions(computed_value->rust_style_value_data(), &is_invalid))
+ return StyleValue::adopt_rust_style_value_data(substituted);
+ if (is_invalid)
+ return property_initial_value(property_id);
+ return computed_value;
+}
+
// Brings style (and, when the property needs it, layout) up to date for computed-style property
// access, and returns the layout node to read used values from (may be null). An empty Optional
// means the element cannot expose computed style at all (disconnected, or no browsing context).
@@ -700,6 +726,14 @@ static Optional<Layout::NodeWithStyle*> prepare_computed_style_and_layout_for_pr
abstract_element.document().update_style_for_element(abstract_element, DOM::Document::StyleUpdateMode::OnlyIfNeeded);
ensure_pseudo_element_style_for_cssom(read, abstract_element);
+ // NB: Only layout resolves the anchor-size() functions of a min or max sizing property against an anchor box.
+ if (!needs_layout && !needs_layout_node && is_min_or_max_size_property(property_id)) {
+ if (auto style = abstract_element.computed_style(); style && min_or_max_size_holds_anchor_function(*style, property_id)) {
+ abstract_element.document().update_layout_if_needed_for_node(abstract_element.element(), DOM::UpdateLayoutReason::ResolvedCSSStyleDeclarationProperty);
+ layout_node = abstract_element.layout_node(read);
+ }
+ }
+
// Container queries and container-relative units need layout to resolve. Avoid forcing layout for every
// getComputedStyle() call; only elements that actually depend on a query container need the post-layout style.
bool style_or_inheritance_ancestor_depends_on_size_container_query = abstract_element.element().style_depends_on_size_container_query();
@@ -870,6 +904,11 @@ Optional<StyleProperty> CSSStyleProperties::get_direct_property(PropertyNameAndI
return resolve_touch_action_style_value(move(computed_value));
case PropertyID::TransformOrigin:
return style_value_for_transform_origin(computed_values->transform_origin(), {});
+ case PropertyID::MaxHeight:
+ case PropertyID::MaxWidth:
+ case PropertyID::MinHeight:
+ case PropertyID::MinWidth:
+ return resolve_unresolvable_anchor_functions(computed_property_id, move(computed_value));
default:
return computed_value;
}
@@ -1278,6 +1317,16 @@ RefPtr<StyleValue const> CSSStyleProperties::style_value_for_computed_property(L
return get_computed_value(property_id);
}
+ // NB: The computed value of a min or max sizing property resolves its anchor-size() functions, which layout
+ // resolves against an anchor box.
+ case PropertyID::MaxHeight:
+ case PropertyID::MaxWidth:
+ case PropertyID::MinHeight:
+ case PropertyID::MinWidth:
+ if (auto resolved_size = Painting::anchor_resolved_size(layout_node, property_id); resolved_size.has_value())
+ return LengthStyleValue::create(Length::make_px(resolved_size.release_value()));
+ return resolve_unresolvable_anchor_functions(property_id, get_computed_value(property_id));
+
// -> bottom
// -> left
// -> inset-block-end
diff --git a/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp b/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp
index 6e75f004c1f..46728c95bff 100644
--- a/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp
+++ b/Libraries/LibWeb/CSS/StyleValues/StyleValue.cpp
@@ -316,6 +316,11 @@ bool StyleValue::is_computationally_independent() const
return ComputedValuesFFI::rust_style_value_is_computationally_independent(m_value.operator->());
}
+bool StyleValue::contains_anchor_function() const
+{
+ return StyleValueFFI::rust_style_value_contains_anchor_function(m_value.operator->());
+}
+
void StyleValue::serialize(StringBuilder& builder, SerializationMode mode) const
{
auto string = to_utf16_string(mode);
diff --git a/Libraries/LibWeb/CSS/StyleValues/StyleValue.h b/Libraries/LibWeb/CSS/StyleValues/StyleValue.h
index 168f01cb412..6d04ed61d9b 100644
--- a/Libraries/LibWeb/CSS/StyleValues/StyleValue.h
+++ b/Libraries/LibWeb/CSS/StyleValues/StyleValue.h
@@ -232,6 +232,8 @@ public:
// of the property on the element, and "global" information that cannot be changed by CSS.
bool is_computationally_independent() const;
+ bool contains_anchor_function() const;
+
protected:
StyleValue(Type, StyleValueFFI::StyleValueData const*);
diff --git a/Libraries/LibWeb/Painting/BoxViews.cpp b/Libraries/LibWeb/Painting/BoxViews.cpp
index 16f28c059d8..4b744cb45c2 100644
--- a/Libraries/LibWeb/Painting/BoxViews.cpp
+++ b/Libraries/LibWeb/Painting/BoxViews.cpp
@@ -158,6 +158,28 @@ BoxModelMetrics box_model(Layout::Node const& node)
};
}
+Optional<CSSPixels> anchor_resolved_size(Layout::Node const& node, CSS::PropertyID property_id)
+{
+ auto property = [&] {
+ switch (property_id) {
+ case CSS::PropertyID::MinWidth:
+ return Layout::RustFFI::FfiAnchorSizedProperty::MinWidth;
+ case CSS::PropertyID::MinHeight:
+ return Layout::RustFFI::FfiAnchorSizedProperty::MinHeight;
+ case CSS::PropertyID::MaxWidth:
+ return Layout::RustFFI::FfiAnchorSizedProperty::MaxWidth;
+ case CSS::PropertyID::MaxHeight:
+ return Layout::RustFFI::FfiAnchorSizedProperty::MaxHeight;
+ default:
+ VERIFY_NOT_REACHED();
+ }
+ }();
+ CSSPixels size;
+ if (!Layout::RustFFI::layout_script_anchor_resolved_size(node.document_host(), committed_row_slot(node), property, &size))
+ return {};
+ return size;
+}
+
CSSPixels border_box_width(Layout::Node const& node)
{
auto border_box = box_model(node).border_box();
diff --git a/Libraries/LibWeb/Painting/BoxViews.h b/Libraries/LibWeb/Painting/BoxViews.h
index 98d109eac18..768be60fbc3 100644
--- a/Libraries/LibWeb/Painting/BoxViews.h
+++ b/Libraries/LibWeb/Painting/BoxViews.h
@@ -44,6 +44,7 @@ WEB_API CSSPixels content_height(Layout::Node const&);
WEB_API CSSPixels border_box_width(Layout::Node const&);
WEB_API CSSPixels border_box_height(Layout::Node const&);
WEB_API BoxModelMetrics box_model(Layout::Node const&);
+WEB_API Optional<CSSPixels> anchor_resolved_size(Layout::Node const&, CSS::PropertyID);
WEB_API CSSPixelRect transform_reference_box(Layout::Node const&);
WEB_API Optional<CSSPixelRect> scrollable_overflow_rect(Layout::Node const&);
WEB_API bool has_scrollable_overflow(Layout::Node const&);
diff --git a/Libraries/LibWeb/Rust/src/css/calc.rs b/Libraries/LibWeb/Rust/src/css/calc.rs
index 8aa243a69a5..b6ce9c69238 100644
--- a/Libraries/LibWeb/Rust/src/css/calc.rs
+++ b/Libraries/LibWeb/Rust/src/css/calc.rs
@@ -4280,11 +4280,8 @@ pub(crate) fn absolutize_calculation_value(
rust_calculation,
resolve_as_is_number,
resolve_as_base,
- resolved_type,
has_percentages_resolve_as,
- percentages_resolve_as,
- resolve_numbers_as_integers,
- accepted_ranges,
+ ..
} = value
else {
return None;
@@ -4393,50 +4390,178 @@ pub(crate) fn absolutize_calculation_value(
&context,
&externals,
|evaluation_context, callbacks| {
- let simplified = root.simplify(evaluation_context, callbacks);
- if let Some(percentage) = percentage_dimension_mix(&simplified, evaluation_context) {
- return AbsolutizedCalculation::Percentage(percentage);
- }
- if let Some(collapsed) =
- collapse_absolutized_calculation(&simplified, *resolve_numbers_as_integers, accepted_ranges.as_slice())
- {
- return AbsolutizedCalculation::Value(collapsed);
+ computed_calculation_from_simplified(
+ value,
+ &root,
+ root.simplify(evaluation_context, callbacks),
+ evaluation_context,
+ )
+ },
+ ))
+}
+
+/// The computed value form of the Calculated style value `value`, whose tree `root` simplified to `simplified`.
+fn computed_calculation_from_simplified(
+ value: &crate::css::style_value::StyleValueData,
+ root: &Arc<CalcNode>,
+ simplified: Arc<CalcNode>,
+ evaluation_context: &CalcEvaluationContext,
+) -> AbsolutizedCalculation {
+ use crate::css::style_value::StyleValueData;
+ let StyleValueData::Calculated {
+ resolve_as_is_number,
+ resolve_as_base,
+ resolved_type,
+ has_percentages_resolve_as,
+ percentages_resolve_as,
+ resolve_numbers_as_integers,
+ accepted_ranges,
+ ..
+ } = value
+ else {
+ unreachable!("computed_calculation_from_simplified requires calculated value data");
+ };
+ if let Some(percentage) = percentage_dimension_mix(&simplified, evaluation_context) {
+ return AbsolutizedCalculation::Percentage(percentage);
+ }
+ if let Some(collapsed) =
+ collapse_absolutized_calculation(&simplified, *resolve_numbers_as_integers, accepted_ranges.as_slice())
+ {
+ return AbsolutizedCalculation::Value(collapsed);
+ }
+ // https://drafts.csswg.org/css-values-4/#functional-numeric
+ // "the value of a numeric function is clamped to the range allowed in the context it is used
+ // at computed value time if possible, and at used value time otherwise."
+ // NB: A lone percentage stays a calculation (see collapse_absolutized_calculation), but its
+ // range is already known, so it is clamped now like a calculation that collapses.
+ let simplified = match &*simplified {
+ CalcNode::Numeric(leaf @ CalcNumericValue::Percentage(..)) => {
+ let clamped = CalcSerializer::clamp_and_censor_numeric_leaf(
+ *leaf,
+ *resolve_numbers_as_integers,
+ accepted_ranges.as_slice(),
+ );
+ if clamped == *leaf {
+ simplified
+ } else {
+ Arc::new(CalcNode::Numeric(clamped))
}
- // https://drafts.csswg.org/css-values-4/#functional-numeric
- // "the value of a numeric function is clamped to the range allowed in the context it is used
- // at computed value time if possible, and at used value time otherwise."
- // NB: A lone percentage stays a calculation (see collapse_absolutized_calculation), but its
- // range is already known, so it is clamped now like a calculation that collapses.
- let simplified = match &*simplified {
- CalcNode::Numeric(leaf @ CalcNumericValue::Percentage(..)) => {
- let clamped = CalcSerializer::clamp_and_censor_numeric_leaf(
- *leaf,
- *resolve_numbers_as_integers,
- accepted_ranges.as_slice(),
- );
- if clamped == *leaf {
- simplified
- } else {
- Arc::new(CalcNode::Numeric(clamped))
- }
+ }
+ _ => simplified,
+ };
+ if Arc::ptr_eq(&simplified, root) {
+ return AbsolutizedCalculation::Unchanged;
+ }
+ AbsolutizedCalculation::Value(StyleValueData::Calculated {
+ rust_calculation: CalcNodeHandle::from_arc(simplified),
+ resolve_as_is_number: *resolve_as_is_number,
+ resolve_as_base: *resolve_as_base,
+ resolved_type: *resolved_type,
+ has_percentages_resolve_as: *has_percentages_resolve_as,
+ percentages_resolve_as: *percentages_resolve_as,
+ resolve_numbers_as_integers: *resolve_numbers_as_integers,
+ accepted_ranges: accepted_ranges.clone(),
+ })
+}
+
+/// Replaces the anchor() and anchor-size() functions of a computed `<length-percentage>` with their fallback values,
+/// as where they are unresolvable. Returns the rebuilt value, none when it holds no anchor functions, or None when one
+/// of them 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.
+#[allow(clippy::arc_with_non_send_sync)]
+pub(crate) fn substitute_unresolvable_anchor_functions(
+ value: &crate::css::style_value::StyleValueData,
+) -> Option<Option<RetainedStyleValueData>> {
+ use crate::css::style_value::StyleValueData;
+ match value {
+ StyleValueData::Anchor { fallback_value, .. } | StyleValueData::AnchorSize { fallback_value, .. } => {
+ let fallback = fallback_value.optional_data()?;
+ Some(Some(
+ substitute_unresolvable_anchor_functions(fallback)?.unwrap_or_else(|| fallback_value.clone()),
+ ))
+ }
+ StyleValueData::Calculated {
+ rust_calculation,
+ resolve_as_is_number,
+ resolve_as_base,
+ has_percentages_resolve_as,
+ ..
+ } if rust_calculation.node().contains_anchor_function() => {
+ let root = rust_calculation.node_arc();
+ let mut externals = Vec::new();
+ collect_external_resolutions(&root, &mut externals);
+ for external in &mut externals {
+ if external.kind != CalcExternalResolutionKind::NonMathFunction
+ || !matches!(
+ external.source.data(),
+ StyleValueData::Anchor { .. } | StyleValueData::AnchorSize { .. }
+ )
+ {
+ continue;
}
- _ => simplified,
- };
- if Arc::ptr_eq(&simplified, &root) {
- return AbsolutizedCalculation::Unchanged;
+ let substituted = substitute_unresolvable_anchor_functions(external.source.data())?
+ .expect("an anchor function is always substituted");
+ external.resolved_node = Some(length_percentage_calc_node(substituted.data())?);
}
- AbsolutizedCalculation::Value(StyleValueData::Calculated {
- rust_calculation: CalcNodeHandle::from_arc(simplified),
- resolve_as_is_number: *resolve_as_is_number,
- resolve_as_base: *resolve_as_base,
- resolved_type: *resolved_type,
- has_percentages_resolve_as: *has_percentages_resolve_as,
- percentages_resolve_as: *percentages_resolve_as,
- resolve_numbers_as_integers: *resolve_numbers_as_integers,
- accepted_ranges: accepted_ranges.clone(),
- })
- },
- ))
+ let context = FfiCalcResolutionContext {
+ basis_kind: 0,
+ basis_value: 0.0,
+ basis_unit: 0,
+ length_resolution_context: std::ptr::null(),
+ element_facts: std::ptr::null(),
+ };
+ let resolve_as =
+ resolve_as_from_fields(*has_percentages_resolve_as, *resolve_as_is_number, *resolve_as_base);
+ let computed = with_ffi_evaluation(resolve_as, &context, &externals, |evaluation_context, callbacks| {
+ computed_calculation_from_simplified(
+ value,
+ &root,
+ root.simplify(evaluation_context, callbacks),
+ evaluation_context,
+ )
+ });
+ Some(Some(match computed {
+ AbsolutizedCalculation::Unchanged => unreachable!("substituting an anchor function changes the tree"),
+ AbsolutizedCalculation::Percentage(value) => {
+ RetainedStyleValueData::from_arc(Arc::new(StyleValueData::Percentage { value }))
+ }
+ AbsolutizedCalculation::Value(value) => RetainedStyleValueData::from_arc(Arc::new(value)),
+ }))
+ }
+ _ => Some(None),
+ }
+}
+
+/// Whether a `<length-percentage>` is or holds an anchor() or anchor-size() function.
+#[unsafe(no_mangle)]
+pub extern "C" fn rust_style_value_contains_anchor_function(value: &crate::css::style_value::StyleValueData) -> bool {
+ use crate::css::style_value::StyleValueData;
+ match value {
+ StyleValueData::Anchor { .. } | StyleValueData::AnchorSize { .. } => true,
+ StyleValueData::Calculated { rust_calculation, .. } => rust_calculation.node().contains_anchor_function(),
+ _ => false,
+ }
+}
+
+/// The value of a computed `<length-percentage>` whose anchor() and anchor-size() functions are unresolvable: one
+/// strong reference to it with the functions replaced by their fallback values, or null when it holds no anchor
+/// functions or when one of them has no fallback value, which `is_invalid` tells apart.
+///
+/// # Safety
+/// `value` must point at live style value data.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn rust_style_value_with_unresolvable_anchor_functions(
+ value: *const std::ffi::c_void,
+ is_invalid: &mut bool,
+) -> *const crate::css::style_value::StyleValueData {
+ // SAFETY: Guaranteed by the caller.
+ let value = unsafe { &*value.cast::<crate::css::style_value::StyleValueData>() };
+ let substituted = substitute_unresolvable_anchor_functions(value);
+ *is_invalid = substituted.is_none();
+ substituted
+ .flatten()
+ .map_or(std::ptr::null(), RetainedStyleValueData::into_pointer)
}
/// A calculation leaf for a length-percentage style value, or None for other kinds.
diff --git a/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs b/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs
index aebe2a37f5d..45dae0595b7 100644
--- a/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs
+++ b/Libraries/LibWeb/Rust/src/layout/abspos_engine.rs
@@ -327,6 +327,8 @@ struct AnchorResolutionState {
default_anchor_box: Node,
compensates_for_horizontal_scroll: bool,
compensates_for_vertical_scroll: bool,
+ /// Whether an anchor function resolved against an anchor box, rather than to its fallback value.
+ resolved_against_anchor_box: bool,
}
impl AnchorResolutionState {
@@ -334,6 +336,7 @@ impl AnchorResolutionState {
default_anchor_box: NodeSlotId::INVALID,
compensates_for_horizontal_scroll: false,
compensates_for_vertical_scroll: false,
+ resolved_against_anchor_box: false,
};
}
@@ -708,6 +711,7 @@ impl AbsposEngine<'_> {
default_anchor_box: anchor_box,
compensates_for_horizontal_scroll: true,
compensates_for_vertical_scroll: true,
+ resolved_against_anchor_box: false,
},
None => default_scroll_shift,
};
@@ -757,6 +761,7 @@ impl AbsposEngine<'_> {
default_anchor_box,
compensates_for_horizontal_scroll: false,
compensates_for_vertical_scroll: false,
+ resolved_against_anchor_box: false,
};
let mut resolve_inset = |inset: style_values::InsetValue<'_>, axis: AnchorValueAxis| {
inset.contains_anchor_function().then(|| {
@@ -830,9 +835,10 @@ impl AbsposEngine<'_> {
) -> 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(
+ // NB: Each resolution also tells whether any of its anchor functions resolved against an anchor box.
+ let resolve = |calculated: *const c_void, is_horizontal: bool, containing_block_extent: CssPixels| {
+ let mut resolution_state = AnchorResolutionState::NO_SCROLL_SHIFT;
+ let resolved = self.resolve_anchor_value(
calculated,
node,
containing_block,
@@ -844,23 +850,25 @@ impl AbsposEngine<'_> {
containing_block_extent,
},
&mut resolution_state,
- )
+ );
+ (resolved, resolution_state.resolved_against_anchor_box)
};
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| {
+ let 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),
- },
- )
+ match resolve(size.length_percentage().calculated_pointer(), is_horizontal, extent) {
+ // NB: A size whose anchor functions all resolve to their fallback values resolves like anywhere
+ // else, so it keeps reading from style. A resolved size thus always comes from an anchor box.
+ (Some(_), false) => None,
+ (Some(px), true) => Some(style_values::ResolvedSizeOverride::Length(px)),
+ (None, _) => Some(style_values::ResolvedSizeOverride::Keyword(initial)),
+ }
};
let mut resolved = style_values::ResolvedAnchorSizes {
width: resolve_size(style.width(), true, ComputedSizeKind::Auto),
@@ -871,13 +879,17 @@ impl AbsposEngine<'_> {
max_height: resolve_size(style.max_height(), false, ComputedSizeKind::None),
..Default::default()
};
- let mut resolve_margin = |margin: &ComputedLengthPercentageOrAuto, is_horizontal: bool| {
+ let 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())
+ Some(
+ resolve(length_percentage.calculated_pointer(), is_horizontal, inline_size)
+ .0
+ .unwrap_or_default(),
+ )
};
resolved.margin_top = resolve_margin(style.margin_top(), false);
resolved.margin_right = resolve_margin(style.margin_right(), true);
@@ -1539,6 +1551,8 @@ unsafe extern "C" fn resolve_anchor_non_math_function(context: *mut c_void, shel
_ => unreachable!("the shell was matched as an anchor function above"),
};
if let Some(resolved) = resolved {
+ // SAFETY: The state pointer is live and uniquely used by this synchronous resolver.
+ unsafe { (*context.resolution_state).resolved_against_anchor_box = true };
// SAFETY: This CSS crate export transfers one Arc reference to
// the external-resolution snapshot, which releases it after
// calc resolution.
diff --git a/Libraries/LibWeb/Rust/src/layout/script_entries.rs b/Libraries/LibWeb/Rust/src/layout/script_entries.rs
index b30f1a676f7..c5608979673 100644
--- a/Libraries/LibWeb/Rust/src/layout/script_entries.rs
+++ b/Libraries/LibWeb/Rust/src/layout/script_entries.rs
@@ -616,3 +616,47 @@ pub unsafe extern "C" fn layout_script_find_matching_text(
unsafe { append(context, range) };
}
}
+
+/// A min or max sizing property, whose anchor-size() functions the abspos engine resolves.
+#[repr(u8)]
+#[derive(Clone, Copy)]
+#[expect(dead_code, reason = "C++ constructs the variants")]
+pub enum FfiAnchorSizedProperty {
+ MinWidth,
+ MinHeight,
+ MaxWidth,
+ MaxHeight,
+}
+
+/// Writes the size `property` of the absolutely positioned box `slot` resolved to in the committed layout to `out`,
+/// when its anchor-size() functions resolved against an anchor box.
+#[unsafe(no_mangle)]
+pub extern "C" fn layout_script_anchor_resolved_size(
+ host: &DocumentHost,
+ slot: NodeSlotId,
+ property: FfiAnchorSizedProperty,
+ out: &mut crate::css::css_pixels::CssPixels,
+) -> bool {
+ use super::style_values::ResolvedSizeOverride;
+ let resolved = read_rows(host, |arena| {
+ if !arena.paintable_row_is_populated(slot) {
+ return None;
+ }
+ arena.with_committed_fragment_link(slot, |link| {
+ let sizes = link?.abspos_layout_inputs.as_ref()?.resolved_anchor_sizes;
+ match property {
+ FfiAnchorSizedProperty::MinWidth => sizes.min_width,
+ FfiAnchorSizedProperty::MinHeight => sizes.min_height,
+ FfiAnchorSizedProperty::MaxWidth => sizes.max_width,
+ FfiAnchorSizedProperty::MaxHeight => sizes.max_height,
+ }
+ })
+ });
+ // NB: A size resolved to a keyword holds an anchor function with neither an anchor box nor a fallback value, which
+ // makes the declaration invalid at computed-value time however its other functions resolve.
+ let Some(ResolvedSizeOverride::Length(px)) = resolved else {
+ return false;
+ };
+ *out = px;
+ true
+}
diff --git a/Libraries/LibWeb/Rust/src/layout/style_values.rs b/Libraries/LibWeb/Rust/src/layout/style_values.rs
index 757ad50c66d..683434e7d6d 100644
--- a/Libraries/LibWeb/Rust/src/layout/style_values.rs
+++ b/Libraries/LibWeb/Rust/src/layout/style_values.rs
@@ -92,8 +92,9 @@ pub(crate) enum ResolvedSizeOverride {
}
/// 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.
+/// those functions resolved by the abspos engine. A property without one stays None and reads from style, as does a
+/// sizing property whose anchor-size() functions all resolve to their fallback values. 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 {
diff --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.txt
index 04a1fee9f37..8f7e2454f1b 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,12 +2,12 @@ Harness status: OK
Found 39 tests
-29 Pass
-10 Fail
+38 Pass
+1 Fail
Pass Element can be anchor positioned
Pass Element can use <length> fallback if present
Pass Element can use <length> fallback with percentage
-Fail Element can use <length> fallback for max size with percentage
+Pass Element can use <length> fallback for max size with percentage
Pass Element can use <length> fallback for margin with percentage
Pass Invalid anchor function, left
Pass Invalid anchor function, right
@@ -15,10 +15,10 @@ Pass Invalid anchor function, bottom
Pass Invalid anchor function, top
Pass Invalid anchor function, width
Pass Invalid anchor function, height
-Fail Invalid anchor function, min-width
-Fail Invalid anchor function, min-height
-Fail Invalid anchor function, max-width
-Fail Invalid anchor function, max-height
+Pass Invalid anchor function, min-width
+Pass Invalid anchor function, min-height
+Pass Invalid anchor function, max-width
+Pass Invalid anchor function, max-height
Pass Invalid anchor function, --unknown left
Pass Invalid anchor function, --unknown width
Pass Invalid anchor function, cross-axis query (vertical)
@@ -28,10 +28,10 @@ Pass Invalid anchor function, nested left
Pass Invalid anchor function, nested right
Pass Invalid anchor function, nested bottom
Pass Invalid anchor function, nested top
-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-height
+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
Pass Invalid anchor function, invalid anchor() in fallback
Pass Invalid anchor function, invalid anchor-size() in fallback
Pass Invalid anchor function, min()