Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

Resolve used aspect ratios at layout boundaries

ldm0e5f4ef1f5fdd
diff --git a/Cargo.lock b/Cargo.lock
index 0d92ae543..0b57ed93d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4823,7 +4823,7 @@ dependencies = [
[[package]]
name = "taffy"
version = "0.13.0"
-source = "git+https://github.com/ldm0/taffy?rev=722358e39cd42cb95cc93d5bf06f3a2940a05748#722358e39cd42cb95cc93d5bf06f3a2940a05748"
+source = "git+https://github.com/ldm0/taffy?rev=3305c7b51c4c88d698d5d3039cd6c8e828ff2086#3305c7b51c4c88d698d5d3039cd6c8e828ff2086"
dependencies = [
"arrayvec",
"serde",
diff --git a/Cargo.toml b/Cargo.toml
index a58973fda..39f559a53 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -98,7 +98,7 @@ stylo_atoms = { git = "https://github.com/ldm0/stylo", rev = "713ba89c8e23dd76fd
stylo_dom = { git = "https://github.com/ldm0/stylo", rev = "713ba89c8e23dd76fd350c5bee68590bfdb885ae" }
stylo_static_prefs = { git = "https://github.com/ldm0/stylo", rev = "713ba89c8e23dd76fd350c5bee68590bfdb885ae" }
stylo_traits = { git = "https://github.com/ldm0/stylo", rev = "713ba89c8e23dd76fd350c5bee68590bfdb885ae" }
-taffy = { git = "https://github.com/ldm0/taffy", rev = "722358e39cd42cb95cc93d5bf06f3a2940a05748" }
+taffy = { git = "https://github.com/ldm0/taffy", rev = "3305c7b51c4c88d698d5d3039cd6c8e828ff2086" }
[workspace.lints.clippy]
disallowed_methods = "deny"
diff --git a/moli-layout/src/builder.rs b/moli-layout/src/builder.rs
index 1b900a191..909740d71 100644
--- a/moli-layout/src/builder.rs
+++ b/moli-layout/src/builder.rs
@@ -16,6 +16,7 @@ use crate::{
LayoutAnonymousReason, LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic, LayoutDisplay,
LayoutElementCategory, LayoutElementSemantics, LayoutError, LayoutPseudo, LayoutSource,
LayoutSourceKind, LayoutStyleResolver, LayoutWorld, ResolvedLayoutStyle,
+ form::form_control_context,
replaced::ReplacedContext,
style::{InlineWhiteSpaceCollapse, LayoutOverflowMode},
world::{ViewportDefiningBox, ViewportScrollPolicy},
@@ -105,7 +106,7 @@ where
root_style.force_display_none();
}
if root_semantics.is_replaced() {
- root_style.mark_replaced(natural_replaced_ratio(&root_semantics, root_metrics));
+ root_style.mark_replaced();
} else if matches!(
root_semantics.category,
crate::LayoutElementCategory::FormControl(crate::LayoutFormControlKind::Button)
@@ -201,7 +202,6 @@ where
LayoutBoxKind::Text,
ResolvedLayoutStyle::text_leaf_from(inherited_style),
Some(Arc::from(text)),
- None,
));
world.boxes[id.index()].text_selection = self.source.text_selection(source_node);
world.map_source(source_node, id);
@@ -243,7 +243,7 @@ where
}
let metrics = self.source.replaced_metrics(source_node);
if semantics.is_replaced() {
- style.mark_replaced(natural_replaced_ratio(&semantics, metrics));
+ style.mark_replaced();
} else if matches!(
semantics.category,
crate::LayoutElementCategory::FormControl(crate::LayoutFormControlKind::Button)
@@ -343,6 +343,7 @@ where
style: ResolvedLayoutStyle,
metrics: Option<crate::ReplacedMetrics>,
) -> crate::LayoutBox<S::NodeId> {
+ let replaced_context = build_replaced_context(&semantics, metrics, &style);
let mut layout_box = LayoutWorld::new_box(
Some(source_node),
None,
@@ -354,8 +355,8 @@ where
kind,
style.clone(),
None,
- metrics,
);
+ layout_box.replaced_context = replaced_context;
layout_box.replaced_image = self.source.replaced_image(source_node, &style);
if !matches!(
style.display(),
@@ -436,7 +437,6 @@ where
kind,
style.clone(),
None,
- None,
);
layout_box.css_images = self.css_image_resources(owner, &style);
if style.has_unsupported_generated_content() {
@@ -469,7 +469,6 @@ where
LayoutBoxKind::Text,
ResolvedLayoutStyle::text_leaf_from(pseudo_style),
Some(Arc::from(text)),
- None,
))
}
@@ -617,7 +616,6 @@ where
LayoutBoxKind::InlineContinuation,
style.clone(),
None,
- None,
);
continuation.css_images = self.css_image_resources(owner, style);
world.allocate(continuation)
@@ -842,7 +840,6 @@ where
anonymous_kind,
style,
None,
- None,
);
anonymous.inline_formatting_context = true;
let id = world.allocate(anonymous);
@@ -1102,7 +1099,6 @@ where
kind,
style,
None,
- None,
));
output.push(id);
Ok(id)
@@ -1289,21 +1285,30 @@ struct ViewportBodyCandidate<N> {
blocks_propagation: bool,
}
-fn natural_replaced_ratio(
+fn build_replaced_context(
semantics: &LayoutElementSemantics,
metrics: Option<crate::ReplacedMetrics>,
-) -> Option<f32> {
- let sizing_kind = if matches!(
+ style: &ResolvedLayoutStyle,
+) -> Option<ReplacedContext> {
+ if !semantics.is_replaced() {
+ return None;
+ }
+ if matches!(
semantics.category,
crate::LayoutElementCategory::FormControl(crate::LayoutFormControlKind::Input(
crate::LayoutInputControlKind::Image
))
) {
- crate::LayoutReplacedKind::Image
- } else {
- semantics.replaced?
- };
- ReplacedContext::for_element(sizing_kind, metrics).inherent_ratio()
+ return Some(ReplacedContext::for_element(
+ crate::LayoutReplacedKind::Image,
+ metrics,
+ ));
+ }
+ form_control_context(semantics, style.font_size(), style.line_height()).or_else(|| {
+ semantics
+ .replaced
+ .map(|kind| ReplacedContext::for_element(kind, metrics))
+ })
}
fn whitespace_text_is_ignorable(text: &str, mode: InlineWhiteSpaceCollapse) -> bool {
diff --git a/moli-layout/src/form.rs b/moli-layout/src/form.rs
index dd1b496ad..86dd3c59e 100644
--- a/moli-layout/src/form.rs
+++ b/moli-layout/src/form.rs
@@ -42,7 +42,6 @@ where
LayoutBoxKind::AnonymousBlock,
wrapper_style,
None,
- None,
);
wrapper.inline_formatting_context = true;
let wrapper_id = world.allocate(wrapper);
@@ -57,7 +56,6 @@ where
LayoutBoxKind::Text,
text_style,
Some(Arc::from(text)),
- None,
));
world.append_synthesized_child(wrapper_id, text_id)?;
world.append_synthesized_child(control, wrapper_id)?;
diff --git a/moli-layout/src/list.rs b/moli-layout/src/list.rs
index 3eca6ddf1..a6eb11245 100644
--- a/moli-layout/src/list.rs
+++ b/moli-layout/src/list.rs
@@ -143,7 +143,6 @@ where
LayoutBoxKind::Text,
text_style,
Some(Arc::from(text)),
- None,
);
let text_id = world.allocate(text_box);
world.append_synthesized_child(marker, text_id)?;
diff --git a/moli-layout/src/replaced.rs b/moli-layout/src/replaced.rs
index 27430ced9..578c703fb 100644
--- a/moli-layout/src/replaced.rs
+++ b/moli-layout/src/replaced.rs
@@ -8,13 +8,10 @@
use style::Atom;
use taffy::{
AvailableSpace, BoxSizing, CoreStyle as _, MaybeMath, MaybeResolve, RequestedAxis,
- ResolveOrZero as _, Size, SizingMode,
+ ResolveOrZero as _, ResolvedAspectRatio, Size, SizingMode,
};
-use crate::{
- LayoutReplacedKind, ReplacedMetrics,
- style::{ResolvedAspectRatio, resolve_stylo_calc_value},
-};
+use crate::{LayoutReplacedKind, ReplacedMetrics, style::resolve_stylo_calc_value};
#[derive(Clone, Copy, Debug)]
pub(crate) struct ReplacedContext {
@@ -179,12 +176,15 @@ fn content_width_from_height(
aspect_ratio: ResolvedAspectRatio,
padding_border: Size<f32>,
) -> Option<f32> {
- let ratio = aspect_ratio.ratio?;
- let width = match aspect_ratio.box_sizing {
- BoxSizing::ContentBox => height * ratio,
- BoxSizing::BorderBox => (height + padding_border.height) * ratio - padding_border.width,
- };
- width.is_finite().then_some(width.max(0.0))
+ apply_aspect_ratio_to_content_size(
+ Size {
+ width: None,
+ height: Some(height),
+ },
+ Some(aspect_ratio),
+ padding_border,
+ )
+ .width
}
fn content_height_from_width(
@@ -192,40 +192,30 @@ fn content_height_from_width(
aspect_ratio: ResolvedAspectRatio,
padding_border: Size<f32>,
) -> Option<f32> {
- let ratio = aspect_ratio.ratio?;
- let height = match aspect_ratio.box_sizing {
- BoxSizing::ContentBox => width / ratio,
- BoxSizing::BorderBox => (width + padding_border.width) / ratio - padding_border.height,
- };
- height.is_finite().then_some(height.max(0.0))
+ apply_aspect_ratio_to_content_size(
+ Size {
+ width: Some(width),
+ height: None,
+ },
+ Some(aspect_ratio),
+ padding_border,
+ )
+ .height
}
fn apply_aspect_ratio_to_content_size(
size: Size<Option<f32>>,
- aspect_ratio: ResolvedAspectRatio,
+ aspect_ratio: Option<ResolvedAspectRatio>,
padding_border: Size<f32>,
) -> Size<Option<f32>> {
- match size {
- Size {
- width: Some(width),
- height: None,
- } => Size {
- width: Some(width),
- height: content_height_from_width(width, aspect_ratio, padding_border),
- },
- Size {
- width: None,
- height: Some(height),
- } => Size {
- width: content_width_from_height(height, aspect_ratio, padding_border),
- height: Some(height),
- },
- _ => size,
- }
+ size.maybe_add(padding_border)
+ .maybe_apply_resolved_aspect_ratio(aspect_ratio, padding_border)
+ .maybe_sub(padding_border)
+ .maybe_max(Size::ZERO)
}
-fn ratio_basis_scale(constrained: f32, original: f32, inset: f32, box_sizing: BoxSizing) -> f32 {
- match box_sizing {
+fn ratio_basis_scale(constrained: f32, original: f32, inset: f32, sizing_box: BoxSizing) -> f32 {
+ match sizing_box {
BoxSizing::ContentBox => constrained / original,
BoxSizing::BorderBox => (constrained + inset) / (original + inset),
}
@@ -236,7 +226,7 @@ pub(crate) fn measure_replaced(
parent_size: Size<Option<f32>>,
available_space: Size<AvailableSpace>,
context: &ReplacedContext,
- resolved_aspect_ratio: ResolvedAspectRatio,
+ resolved_aspect_ratio: Option<ResolvedAspectRatio>,
style: &taffy::Style<Atom>,
sizing_mode: SizingMode,
requested_axis: RequestedAxis,
@@ -260,7 +250,6 @@ pub(crate) fn measure_replaced(
// The browser-owned style seam has already resolved the three CSS states
// (`auto`, `<ratio>`, and `auto <ratio>`) against the natural ratio. Do not
// reconstruct that precedence from Taffy's lossy numeric field here.
- let aspect_ratio = resolved_aspect_ratio.ratio;
let preferred_basis = Size {
width: if available_space.width == AvailableSpace::MinContent {
Some(0.0)
@@ -300,7 +289,7 @@ pub(crate) fn measure_replaced(
// reaches the complete replaced-element measure callback, and it has no
// vertical intrinsic-keyword resolver, so resolve both physical axes at
// this browser-owned sizing boundary.
- if aspect_ratio.is_some() {
+ if let Some(resolved_aspect_ratio) = resolved_aspect_ratio {
let transferred_width = preferred_size.height.and_then(|height| {
content_width_from_height(height, resolved_aspect_ratio, padding_border_sum)
});
@@ -384,7 +373,7 @@ pub(crate) fn measure_replaced(
} else {
Violation::None
};
- let Some(_) = aspect_ratio else {
+ let Some(resolved_aspect_ratio) = resolved_aspect_ratio else {
return size.maybe_clamp(min_size, max_size) + padding_border_sum;
};
let size = match (width_violation, height_violation) {
@@ -432,12 +421,12 @@ pub(crate) fn measure_replaced(
width,
size.width,
padding_border_sum.width,
- resolved_aspect_ratio.box_sizing,
+ resolved_aspect_ratio.sizing_box(),
) <= ratio_basis_scale(
height,
size.height,
padding_border_sum.height,
- resolved_aspect_ratio.box_sizing,
+ resolved_aspect_ratio.sizing_box(),
) {
Size {
width,
@@ -469,12 +458,12 @@ pub(crate) fn measure_replaced(
width,
size.width,
padding_border_sum.width,
- resolved_aspect_ratio.box_sizing,
+ resolved_aspect_ratio.sizing_box(),
) <= ratio_basis_scale(
height,
size.height,
padding_border_sum.height,
- resolved_aspect_ratio.box_sizing,
+ resolved_aspect_ratio.sizing_box(),
) {
Size {
width: content_width_from_height(
@@ -540,13 +529,11 @@ mod tests {
height: AvailableSpace::MaxContent,
},
&image_context(),
- ResolvedAspectRatio {
- ratio: style
- .aspect_ratio
- .filter(|ratio| ratio.is_finite() && *ratio > 0.0)
- .or(Some(1.0)),
- box_sizing: style.box_sizing,
- },
+ style
+ .aspect_ratio
+ .filter(|ratio| ratio.is_finite() && *ratio > 0.0)
+ .or(Some(1.0))
+ .and_then(|ratio| ResolvedAspectRatio::new(ratio, style.box_sizing)),
style,
SizingMode::InherentSize,
RequestedAxis::Both,
@@ -579,10 +566,7 @@ mod tests {
height: AvailableSpace::MaxContent,
},
&image_context(),
- ResolvedAspectRatio {
- ratio: Some(2.0),
- box_sizing,
- },
+ ResolvedAspectRatio::new(2.0, box_sizing),
&style,
SizingMode::InherentSize,
RequestedAxis::Both,
diff --git a/moli-layout/src/style.rs b/moli-layout/src/style.rs
index a93b240e8..bc4d0a41c 100644
--- a/moli-layout/src/style.rs
+++ b/moli-layout/src/style.rs
@@ -46,7 +46,9 @@ use style::{
},
},
};
-use taffy::{BoxSizing, Display as TaffyDisplay, Position as TaffyPosition, Size, Style};
+use taffy::{
+ BoxSizing, Display as TaffyDisplay, Position as TaffyPosition, ResolvedAspectRatio, Size, Style,
+};
use crate::{
LayoutPoint, LayoutRect, LayoutScrollbarAxis, LayoutScrollbarColors, LayoutScrollbarGutter,
@@ -263,13 +265,6 @@ pub(crate) enum PreferredAspectRatio {
AutoAndRatio(f32),
}
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub(crate) struct ResolvedAspectRatio {
- pub(crate) ratio: Option<f32>,
- /// The box whose dimensions the ratio constrains.
- pub(crate) box_sizing: BoxSizing,
-}
-
impl PreferredAspectRatio {
fn from_components(auto: bool, ratio: Option<f32>) -> Self {
match (auto, usable_aspect_ratio(ratio)) {
@@ -290,28 +285,22 @@ impl PreferredAspectRatio {
}
}
- fn resolve_for_replaced(
+ fn resolve(
self,
- inherent_ratio: Option<f32>,
+ natural_ratio: Option<f32>,
authored_box_sizing: BoxSizing,
- ) -> ResolvedAspectRatio {
- let inherent_ratio = usable_aspect_ratio(inherent_ratio);
+ ) -> Option<ResolvedAspectRatio> {
+ let natural_ratio = usable_aspect_ratio(natural_ratio);
match self {
- Self::Ratio(ratio) => ResolvedAspectRatio {
- ratio: Some(ratio),
- box_sizing: authored_box_sizing,
- },
- Self::Auto => ResolvedAspectRatio {
- ratio: inherent_ratio,
- box_sizing: BoxSizing::ContentBox,
- },
+ Self::Ratio(ratio) => ResolvedAspectRatio::new(ratio, authored_box_sizing),
+ Self::Auto => natural_ratio
+ .and_then(|ratio| ResolvedAspectRatio::new(ratio, BoxSizing::ContentBox)),
// Blink's BoxSizingForAspectRatio() uses content-box for the
// combined `auto <ratio>` value, including when its ratio is used
// as the fallback because no natural ratio is available.
- Self::AutoAndRatio(fallback) => ResolvedAspectRatio {
- ratio: inherent_ratio.or(Some(fallback)),
- box_sizing: BoxSizing::ContentBox,
- },
+ Self::AutoAndRatio(fallback) => {
+ ResolvedAspectRatio::new(natural_ratio.unwrap_or(fallback), BoxSizing::ContentBox)
+ }
}
}
}
@@ -2054,20 +2043,16 @@ impl ResolvedLayoutStyle {
}
}
- pub(crate) fn mark_replaced(&mut self, inherent_ratio: Option<f32>) {
+ pub(crate) fn mark_replaced(&mut self) {
self.taffy.item_is_replaced = true;
- self.taffy.aspect_ratio = self
- .preferred_aspect_ratio
- .resolve_for_replaced(inherent_ratio, self.taffy.box_sizing)
- .ratio;
}
- pub(crate) fn resolved_replaced_aspect_ratio(
+ pub(crate) fn resolved_aspect_ratio(
&self,
- inherent_ratio: Option<f32>,
- ) -> ResolvedAspectRatio {
+ natural_ratio: Option<f32>,
+ ) -> Option<ResolvedAspectRatio> {
self.preferred_aspect_ratio
- .resolve_for_replaced(inherent_ratio, self.taffy.box_sizing)
+ .resolve(natural_ratio, self.taffy.box_sizing)
}
pub(crate) fn mark_intrinsic_form_control_container(&mut self) {
@@ -2511,19 +2496,25 @@ mod aspect_ratio_tests {
#[test]
fn replaced_ratio_resolution_preserves_auto_precedence_and_box_basis() {
- let specified =
- PreferredAspectRatio::Ratio(1.0).resolve_for_replaced(Some(2.0), BoxSizing::BorderBox);
- assert_eq!(specified.ratio, Some(1.0));
- assert_eq!(specified.box_sizing, BoxSizing::BorderBox);
-
- let natural = PreferredAspectRatio::AutoAndRatio(1.0)
- .resolve_for_replaced(Some(2.0), BoxSizing::BorderBox);
- assert_eq!(natural.ratio, Some(2.0));
- assert_eq!(natural.box_sizing, BoxSizing::ContentBox);
-
- let fallback = PreferredAspectRatio::AutoAndRatio(1.0)
- .resolve_for_replaced(None, BoxSizing::BorderBox);
- assert_eq!(fallback.ratio, Some(1.0));
- assert_eq!(fallback.box_sizing, BoxSizing::ContentBox);
+ let specified = PreferredAspectRatio::Ratio(1.0).resolve(Some(2.0), BoxSizing::BorderBox);
+ let specified = specified.expect("specified ratio");
+ assert_eq!(specified.ratio(), 1.0);
+ assert_eq!(specified.sizing_box(), BoxSizing::BorderBox);
+
+ let natural =
+ PreferredAspectRatio::AutoAndRatio(1.0).resolve(Some(2.0), BoxSizing::BorderBox);
+ let natural = natural.expect("natural ratio");
+ assert_eq!(natural.ratio(), 2.0);
+ assert_eq!(natural.sizing_box(), BoxSizing::ContentBox);
+
+ let fallback = PreferredAspectRatio::AutoAndRatio(1.0).resolve(None, BoxSizing::BorderBox);
+ let fallback = fallback.expect("fallback ratio");
+ assert_eq!(fallback.ratio(), 1.0);
+ assert_eq!(fallback.sizing_box(), BoxSizing::ContentBox);
+
+ assert_eq!(
+ PreferredAspectRatio::Auto.resolve(None, BoxSizing::BorderBox),
+ None
+ );
}
}
diff --git a/moli-layout/src/taffy_tree.rs b/moli-layout/src/taffy_tree.rs
index ee5a99ab3..315c8e6b3 100644
--- a/moli-layout/src/taffy_tree.rs
+++ b/moli-layout/src/taffy_tree.rs
@@ -6,23 +6,22 @@ use taffy::{
AlignContent, AlignContentKeyword, AlignmentSafety, AvailableSpace, BlockContext,
BlockFormattingContext, BoxSizing, CacheTree, Clear, Dimension, Display, FloatDirection,
Layout, LayoutBlockContainer, LayoutFlexboxContainer, LayoutGridContainer, LayoutInput,
- LayoutOutput, LayoutPartialTree, Line, MaybeMath, MaybeResolve, NodeId, Point, ResolveOrZero,
- RoundTree, RunMode, Size, SizingMode, SizingPurpose, Style, TraversePartialTree, TraverseTree,
- compute_block_layout, compute_cached_layout, compute_flexbox_layout, compute_grid_layout,
- compute_hidden_layout, compute_leaf_layout_with_scrollbar_insets, compute_root_layout,
- round_layout,
+ LayoutOutput, LayoutPartialTree, LeafLayoutContext, Line, MaybeMath, MaybeResolve, NodeId,
+ Point, ResolveOrZero, RoundTree, RunMode, Size, SizingMode, SizingPurpose, Style,
+ TraversePartialTree, TraverseTree, compute_block_layout, compute_cached_layout,
+ compute_flexbox_layout, compute_grid_layout, compute_hidden_layout,
+ compute_leaf_layout_with_context, compute_root_layout, round_layout,
};
use crate::{
LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic, LayoutWorld, PaintRect, PaintViewport,
- form::form_control_context,
inline::{
InlineFormattingContext, InlineFragments, InlineLinePlacement, InlineObjectRole,
break_inline_lines, build_inline_fragments, build_inline_line_placements,
relative_atomic_inset_offset,
},
positioned::resolve_absolute_axis_margins,
- replaced::{ReplacedContext, measure_replaced},
+ replaced::measure_replaced,
style::{InlineDirection, resolve_stylo_calc_value},
table::{compute_table_layout, prepare_table_layout_trees},
world::InlineStaticPosition,
@@ -330,7 +329,6 @@ where
LayoutBoxKind::PrincipalBlock,
placeholder_style,
None,
- None,
);
placeholder.capability_diagnostics.clear();
placeholder.layout_parent = Some(original_parent);
@@ -1293,6 +1291,15 @@ where
}
}
+ fn get_resolved_aspect_ratio(&self, node_id: NodeId) -> Option<taffy::ResolvedAspectRatio> {
+ if self.is_viewport_taffy_node(node_id) {
+ return self.viewport_layout.style.aspect_ratio.and_then(|ratio| {
+ taffy::ResolvedAspectRatio::new(ratio, self.viewport_layout.style.box_sizing)
+ });
+ }
+ self.boxes[LayoutBoxId::from_taffy(node_id).index()].resolved_aspect_ratio()
+ }
+
fn resolve_calc_value(&self, value: *const (), basis: f32) -> f32 {
resolve_stylo_calc_value(value, basis)
}
@@ -1606,27 +1613,8 @@ where
let text = layout_box.text.clone();
let font_size = layout_box.style.font_size();
let line_height = layout_box.style.line_height();
- let replaced_context = layout_box.element_semantics.as_ref().and_then(|semantics| {
- if matches!(
- semantics.category,
- crate::LayoutElementCategory::FormControl(crate::LayoutFormControlKind::Input(
- crate::LayoutInputControlKind::Image
- ))
- ) {
- // Image buttons use ordinary image replaced sizing, including
- // HTML width/height hints. They remain classified as form
- // controls for DOM state and paint diagnostics only.
- return Some(ReplacedContext::for_element(
- crate::LayoutReplacedKind::Image,
- layout_box.replaced_metrics,
- ));
- }
- form_control_context(semantics, font_size, line_height).or_else(|| {
- semantics
- .replaced
- .map(|kind| ReplacedContext::for_element(kind, layout_box.replaced_metrics))
- })
- });
+ let replaced_context = layout_box.replaced_context;
+ let resolved_aspect_ratio = layout_box.resolved_aspect_ratio();
if let Some(context) = replaced_context {
// `measure_replaced` is the complete CSS replaced-element sizing
@@ -1636,9 +1624,6 @@ where
// adds CSS padding and borders itself. Routing the complete
// replaced result through that helper would therefore apply the
// box model twice (most visibly on padded form controls).
- let resolved_aspect_ratio = layout_box
- .style
- .resolved_replaced_aspect_ratio(context.inherent_ratio());
let size = measure_replaced(
inputs.known_dimensions,
inputs.parent_size,
@@ -1661,10 +1646,11 @@ where
}
let scrollbar_insets = self.get_scrollbar_insets(id.to_taffy());
- compute_leaf_layout_with_scrollbar_insets(
+ let context = LeafLayoutContext::new(resolved_aspect_ratio, scrollbar_insets);
+ compute_leaf_layout_with_context(
inputs,
&style,
- scrollbar_insets,
+ context,
resolve_stylo_calc_value,
|known_dimensions, available_space| {
if let Some(text) = text.as_deref() {
@@ -1693,6 +1679,7 @@ where
) -> LayoutOutput {
let scrollbar_insets = self.get_scrollbar_insets(id.to_taffy());
let style = self.boxes[id.index()].style.taffy.clone();
+ let resolved_aspect_ratio = self.boxes[id.index()].resolved_aspect_ratio();
let is_floated = box_is_effectively_floated(self, id);
// Both Taffy's block-float parent and Moli's IFC float parent
// pass the border-box space left after horizontal margins. Taffy's
@@ -1718,10 +1705,11 @@ where
.take()
.unwrap_or_else(empty_inline_context);
let mut measurement = None;
- let mut output = compute_leaf_layout_with_scrollbar_insets(
+ let context = LeafLayoutContext::new(resolved_aspect_ratio, scrollbar_insets);
+ let mut output = compute_leaf_layout_with_context(
leaf_inputs,
&style,
- scrollbar_insets,
+ context,
resolve_stylo_calc_value,
|known_dimensions, available_space| {
let result = self.measure_inline_context(
diff --git a/moli-layout/src/world.rs b/moli-layout/src/world.rs
index 06e22126b..6326ccfe3 100644
--- a/moli-layout/src/world.rs
+++ b/moli-layout/src/world.rs
@@ -6,7 +6,7 @@ use taffy::{Cache, Layout, Point, Style};
use crate::{
LayoutCssImageReference, LayoutElementSemantics, LayoutError, LayoutPoint, LayoutPseudo,
LayoutScrollbarAxis, LayoutScrollbarColors, LayoutScrollbarGutter, LayoutScrollbarWidth,
- ReplacedMetrics, ResolvedLayoutStyle, inline::InlineFormattingContext,
+ ResolvedLayoutStyle, inline::InlineFormattingContext, replaced::ReplacedContext,
style::LayoutOverflowMode,
};
@@ -237,7 +237,8 @@ pub struct LayoutBox<N> {
pub(crate) outside_list_marker: bool,
/// Current source-owned scroll offset sampled at construction time.
pub(crate) scroll_offset: LayoutPoint,
- pub(crate) replaced_metrics: Option<ReplacedMetrics>,
+ /// Pass-local natural sizing retained once at box construction.
+ pub(crate) replaced_context: Option<ReplacedContext>,
pub(crate) replaced_image: Option<crate::LayoutImageResource>,
pub(crate) css_images: crate::source::LayoutCssImageResources,
/// Winning collapsed-table edges owned by the table wrapper for this pass.
@@ -543,6 +544,15 @@ impl<N> LayoutBox<N> {
.as_ref()
.is_some_and(LayoutElementSemantics::is_replaced)
}
+
+ /// Resolve the used ratio at the layout-node boundary, after both authored
+ /// style and natural replaced-element sizing are available.
+ pub(crate) fn resolved_aspect_ratio(&self) -> Option<taffy::ResolvedAspectRatio> {
+ let natural_ratio = self
+ .replaced_context
+ .and_then(|context| context.inherent_ratio());
+ self.style.resolved_aspect_ratio(natural_ratio)
+ }
}
/// Entire short-lived sidecar used for one construction/layout demand.
@@ -957,7 +967,6 @@ where
kind: LayoutBoxKind,
style: ResolvedLayoutStyle,
text: Option<Arc<str>>,
- replaced_metrics: Option<ReplacedMetrics>,
) -> LayoutBox<N> {
let capability_diagnostics =
default_capability_diagnostics(kind, element_semantics.as_ref(), &style);
@@ -986,7 +995,7 @@ where
inline_flattened: false,
outside_list_marker: false,
scroll_offset: LayoutPoint::ZERO,
- replaced_metrics,
+ replaced_context: None,
replaced_image: None,
css_images: crate::source::LayoutCssImageResources::default(),
collapsed_table_borders: None,
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
index ad12b9ada..073c53ea8 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
@@ -149,6 +149,7 @@ mod navigation_api_task;
mod opfs;
mod parser_written_script_residence;
mod popup_document_completion;
+mod preferred_aspect_ratio;
mod rendering_update;
mod service_worker;
mod service_worker_client_message;
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/preferred_aspect_ratio.rs b/moli-renderer-v8/src/runtime/page_vm/tests/preferred_aspect_ratio.rs
new file mode 100644
index 000000000..f4b2098b6
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/preferred_aspect_ratio.rs
@@ -0,0 +1,91 @@
+use super::*;
+
+#[tokio::test(flavor = "current_thread")]
+async fn screenshot_resolves_preferred_ratios_at_layout_boundaries() {
+ run_page_vm_async_test(async move {
+ let loader =
+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
+ let mut page_vm = test_page_vm_with_loader_and_document_url(
+ &loader,
+ Vec::new(),
+ Url::parse("https://example.com/preferred-aspect-ratio.html")?,
+ );
+ page_vm.vm_mut().eval(
+ r#"
+document.head.innerHTML = `<style>
+html,body{margin:0}
+.ordinary{display:block;width:100px;border:20px solid}
+#ratio-content{aspect-ratio:2/1}
+#ratio-border{box-sizing:border-box;aspect-ratio:2/1}
+#auto-content{aspect-ratio:auto 2/1}
+#auto-border{box-sizing:border-box;aspect-ratio:auto 2/1}
+svg{display:block;width:120px;height:auto}
+.asymmetric-insets{
+ box-sizing:border-box;
+ padding:3px 10px;
+ border:solid;
+ border-width:2px 5px;
+}
+#natural-auto{aspect-ratio:auto}
+#natural-auto-fallback{aspect-ratio:auto 3/2}
+#fallback-no-natural{aspect-ratio:auto 3/2}
+#specified-border{aspect-ratio:3/2}
+#natural-border{aspect-ratio:auto}
+#height-only{width:auto;height:50px;aspect-ratio:2/1}
+#both-definite{width:130px;height:70px;aspect-ratio:1/1}
+#degenerate{aspect-ratio:0/1}
+#auto-degenerate{aspect-ratio:auto 0/1}
+</style>`;
+document.body.innerHTML = `
+<div class=ordinary id=ratio-content></div>
+<div class=ordinary id=ratio-border></div>
+<div class=ordinary id=auto-content></div>
+<div class=ordinary id=auto-border></div>
+<svg id=natural-auto viewBox="0 0 200 100"></svg>
+<svg id=natural-auto-fallback viewBox="0 0 200 100"></svg>
+<svg class=asymmetric-insets id=fallback-no-natural></svg>
+<svg class=asymmetric-insets id=specified-border viewBox="0 0 200 100"></svg>
+<svg class=asymmetric-insets id=natural-border viewBox="0 0 200 100"></svg>
+<svg id=height-only viewBox="0 0 200 100"></svg>
+<svg id=both-definite viewBox="0 0 200 100"></svg>
+<svg id=degenerate viewBox="0 0 200 100"></svg>
+<svg id=auto-degenerate viewBox="0 0 200 100"></svg>`;
+'installed'
+"#,
+ )?;
+ page_vm.vm_mut().sync_live_document_style_sources();
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(moli_layout::PaintViewport::new(640, 1_400, 1.0))?
+ .expect("preferred aspect-ratio fixture must retain a layout root");
+
+ let geometry = page_vm.vm_mut().eval(
+ r#"JSON.stringify(Object.fromEntries([...document.querySelectorAll('[id]')].map(element=>{const rect=element.getBoundingClientRect();return [element.id,[rect.width,rect.height]]})))"#,
+ )?;
+ let geometry: serde_json::Value = serde_json::from_str(&geometry)?;
+ for (id, expected) in [
+ ("ratio-content", [140, 90]),
+ ("ratio-border", [100, 50]),
+ ("auto-content", [140, 90]),
+ ("auto-border", [100, 70]),
+ ("natural-auto", [120, 60]),
+ ("natural-auto-fallback", [120, 60]),
+ ("fallback-no-natural", [120, 70]),
+ ("specified-border", [120, 80]),
+ ("natural-border", [120, 55]),
+ ("height-only", [100, 50]),
+ ("both-definite", [130, 70]),
+ ("degenerate", [120, 60]),
+ ("auto-degenerate", [120, 60]),
+ ] {
+ assert_eq!(
+ geometry[id],
+ serde_json::json!(expected),
+ "Chromium-calibrated geometry mismatch for {id}: {geometry}"
+ );
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("preferred aspect-ratio fixture should run");
+}