Skip to content

armgit / moli

Public Imported from GitHub
0

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

Preserve structural ancestry through block-in-inline

ldm012820a520369
diff --git a/moli-layout/src/builder.rs b/moli-layout/src/builder.rs
index 952ce9da5..1b900a191 100644
--- a/moli-layout/src/builder.rs
+++ b/moli-layout/src/builder.rs
@@ -482,6 +482,11 @@ where
children: Vec<LayoutBoxId>,
allow_inline_split: bool,
) -> Result<Vec<LayoutBoxId>, LayoutError> {
+ // Preserve the LayoutObject/source ownership before table repair,
+ // anonymous block wrapping, or block-in-inline splitting rewrites the
+ // formatting tree. A promoted block must still see its inline source
+ // parent for containing-block and CSSOM ancestry.
+ world.record_structural_children(box_id, &children)?;
let table_role = self.table_role(world, box_id)?;
let children = if table_role == Some(TableBoxRole::Column) {
Vec::new()
diff --git a/moli-layout/src/form.rs b/moli-layout/src/form.rs
index ee4c2afe5..dd1b496ad 100644
--- a/moli-layout/src/form.rs
+++ b/moli-layout/src/form.rs
@@ -6,11 +6,11 @@ use taffy::Size;
use crate::{
LayoutAnonymousReason, LayoutBoxId, LayoutBoxKind, LayoutDisplay, LayoutElementCategory,
- LayoutElementSemantics, LayoutFormControlKind, LayoutInputControlKind, LayoutWorld,
- ResolvedLayoutStyle, replaced::ReplacedContext,
+ LayoutElementSemantics, LayoutError, LayoutFormControlKind, LayoutInputControlKind,
+ LayoutWorld, ResolvedLayoutStyle, replaced::ReplacedContext,
};
-pub(crate) fn prepare_form_controls<N>(world: &mut LayoutWorld<N>)
+pub(crate) fn prepare_form_controls<N>(world: &mut LayoutWorld<N>) -> Result<(), LayoutError>
where
N: Copy + Debug + Eq + Hash,
{
@@ -59,11 +59,10 @@ where
Some(Arc::from(text)),
None,
));
- world.boxes[text_id.index()].parent = Some(wrapper_id);
- world.boxes[wrapper_id.index()].children.push(text_id);
- world.boxes[wrapper_id.index()].parent = Some(control);
- world.boxes[control.index()].children.push(wrapper_id);
+ world.append_synthesized_child(wrapper_id, text_id)?;
+ world.append_synthesized_child(control, wrapper_id)?;
}
+ Ok(())
}
fn form_control_text(semantics: &Option<LayoutElementSemantics>) -> Option<String> {
diff --git a/moli-layout/src/layout_tree/model.rs b/moli-layout/src/layout_tree/model.rs
index 197a24ad0..6689ae31f 100644
--- a/moli-layout/src/layout_tree/model.rs
+++ b/moli-layout/src/layout_tree/model.rs
@@ -316,7 +316,11 @@ pub struct LayoutScrollExtent {
#[derive(Clone, Debug, PartialEq)]
pub struct LayoutBoxGeometry {
pub id: LayoutOutputBoxId,
+ /// Source/LayoutObject ancestry before formatting-tree normalization.
+ pub structural_parent: Option<LayoutOutputBoxId>,
+ /// Parent in the normalized formatting tree.
pub parent: Option<LayoutOutputBoxId>,
+ /// Parent used by the numeric layout algorithm.
pub layout_parent: Option<LayoutOutputBoxId>,
pub position: LayoutPosition,
pub coordinate_space: LayoutCoordinateSpaceId,
diff --git a/moli-layout/src/layout_tree/source_query.rs b/moli-layout/src/layout_tree/source_query.rs
index a6110482e..371fd36b2 100644
--- a/moli-layout/src/layout_tree/source_query.rs
+++ b/moli-layout/src/layout_tree/source_query.rs
@@ -491,7 +491,7 @@ where
}
let base_is_positioned = geometry.position != LayoutPosition::Static;
let mut in_fixed_position_chain = geometry.position == LayoutPosition::Fixed;
- let mut candidate = geometry.parent;
+ let mut candidate = geometry.structural_parent;
while let Some(id) = candidate {
let parent = self.box_geometry(id)?;
let source = self
@@ -499,7 +499,7 @@ where
.get(id.index())
.and_then(|layout_box| layout_box.geometry_source);
let Some(source) = source else {
- candidate = parent.parent;
+ candidate = parent.structural_parent;
continue;
};
@@ -509,7 +509,7 @@ where
} else if parent.position == LayoutPosition::Fixed {
in_fixed_position_chain = true;
}
- candidate = parent.parent;
+ candidate = parent.structural_parent;
continue;
}
@@ -524,7 +524,7 @@ where
return Some(id);
}
in_fixed_position_chain |= parent.position == LayoutPosition::Fixed;
- candidate = parent.parent;
+ candidate = parent.structural_parent;
}
None
}
diff --git a/moli-layout/src/list.rs b/moli-layout/src/list.rs
index 38a9a1189..3eca6ddf1 100644
--- a/moli-layout/src/list.rs
+++ b/moli-layout/src/list.rs
@@ -7,12 +7,12 @@
use std::{fmt::Debug, hash::Hash, sync::Arc};
use crate::{
- LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic, LayoutElementCategory,
+ LayoutBoxId, LayoutBoxKind, LayoutCapabilityDiagnostic, LayoutElementCategory, LayoutError,
LayoutListMarkerPosition, LayoutListMarkerType, LayoutListRole, LayoutPseudo, LayoutWorld,
ResolvedLayoutStyle,
};
-pub(crate) fn prepare_list_markers<N>(world: &mut LayoutWorld<N>)
+pub(crate) fn prepare_list_markers<N>(world: &mut LayoutWorld<N>) -> Result<(), LayoutError>
where
N: Copy + Debug + Eq + Hash,
{
@@ -53,7 +53,7 @@ where
.and_then(|semantics| semantics.metadata.list)
.and_then(|item| item.value)
.unwrap_or(counter);
- prepare_item_marker(world, item, value);
+ prepare_item_marker(world, item, value)?;
handled[item.index()] = true;
counter = value.saturating_add(step);
}
@@ -67,8 +67,9 @@ where
.filter(|id| !handled[id.index()] && world.boxes[id.index()].style.display().is_list_item())
.collect::<Vec<_>>();
for item in standalone {
- prepare_item_marker(world, item, 1);
+ prepare_item_marker(world, item, 1)?;
}
+ Ok(())
}
fn collect_container_items<N>(
@@ -99,13 +100,17 @@ fn collect_container_items<N>(
}
}
-fn prepare_item_marker<N>(world: &mut LayoutWorld<N>, item: LayoutBoxId, counter: i32)
+fn prepare_item_marker<N>(
+ world: &mut LayoutWorld<N>,
+ item: LayoutBoxId,
+ counter: i32,
+) -> Result<(), LayoutError>
where
N: Copy + Debug + Eq + Hash,
{
let marker_type = world.boxes[item.index()].style.list_marker_type().clone();
let Some(marker) = find_marker(world, item) else {
- return;
+ return Ok(());
};
world.boxes[marker.index()].outside_list_marker =
world.boxes[item.index()].style.list_marker_position() == LayoutListMarkerPosition::Outside;
@@ -117,10 +122,10 @@ where
);
}
if !world.boxes[marker.index()].children.is_empty() {
- return;
+ return Ok(());
}
let Some(text) = marker_text(&marker_type, counter) else {
- return;
+ return Ok(());
};
let owner = world.boxes[marker.index()].owner;
@@ -141,9 +146,9 @@ where
None,
);
let text_id = world.allocate(text_box);
- world.boxes[text_id.index()].parent = Some(marker);
- world.boxes[marker.index()].children.push(text_id);
+ world.append_synthesized_child(marker, text_id)?;
world.boxes[marker.index()].inline_formatting_context = true;
+ Ok(())
}
fn find_marker<N>(world: &LayoutWorld<N>, item: LayoutBoxId) -> Option<LayoutBoxId>
diff --git a/moli-layout/src/pass.rs b/moli-layout/src/pass.rs
index a5d862090..8a8ed7803 100644
--- a/moli-layout/src/pass.rs
+++ b/moli-layout/src/pass.rs
@@ -219,9 +219,10 @@ where
.is_none_or(|body| world.box_by_id(body).is_some()),
"viewport policy must retain only a live pass-local body box identity"
);
- prepare_list_markers(&mut world);
- prepare_form_controls(&mut world);
+ prepare_list_markers(&mut world)?;
+ prepare_form_controls(&mut world)?;
prepare_inline_contexts(&mut world, services);
+ world.validate_invariants()?;
compute_world_layout_with_scrollbars(&mut world, request.viewport);
let mut embedded_frames = HashMap::new();
if request.requests_embedded_frames() {
diff --git a/moli-layout/src/projection.rs b/moli-layout/src/projection.rs
index 4cc358369..7c80e6c9d 100644
--- a/moli-layout/src/projection.rs
+++ b/moli-layout/src/projection.rs
@@ -545,6 +545,9 @@ where
.global_layout_origin(LayoutBoxId::from_index(index));
self.boxes.push(LayoutBoxGeometry {
id,
+ structural_parent: layout_box
+ .structural_parent
+ .map(|parent| LayoutOutputBoxId::from_index(parent.index())),
parent: layout_box
.parent
.map(|parent| LayoutOutputBoxId::from_index(parent.index())),
diff --git a/moli-layout/src/world.rs b/moli-layout/src/world.rs
index d93a83c61..06e22126b 100644
--- a/moli-layout/src/world.rs
+++ b/moli-layout/src/world.rs
@@ -196,6 +196,16 @@ pub struct LayoutBox<N> {
pub(crate) anonymous_reason: Option<LayoutAnonymousReason>,
pub(crate) capability_diagnostics: Vec<LayoutCapabilityDiagnostic>,
pub(crate) kind: LayoutBoxKind,
+ /// Parent in the source-backed LayoutObject hierarchy, before anonymous
+ /// box normalization and block-in-inline promotion.
+ ///
+ /// Chromium keeps this ancestry on its LayoutObject tree while fragment
+ /// construction handles block-in-inline placement. Moli's normalized
+ /// `parent` tree is intentionally different, so containing-block and
+ /// CSSOM ancestry retain their own first-class relation here.
+ pub(crate) structural_parent: Option<LayoutBoxId>,
+ /// Parent in the normalized formatting tree, including anonymous wrappers
+ /// and block-in-inline promotion.
pub(crate) parent: Option<LayoutBoxId>,
pub(crate) children: Vec<LayoutBoxId>,
/// Parent used by the numeric layout algorithm.
@@ -507,6 +517,11 @@ impl<N> LayoutBox<N> {
&self.children
}
+ /// Returns the parent in the source-backed LayoutObject hierarchy.
+ pub fn structural_parent(&self) -> Option<LayoutBoxId> {
+ self.structural_parent
+ }
+
pub fn style(&self) -> &ResolvedLayoutStyle {
&self.style
}
@@ -644,11 +659,59 @@ where
index: child.index(),
});
};
+ // Raw source ownership is recorded before normalization. Boxes
+ // synthesized by normalization have no earlier owner, so their
+ // first formatting attachment is also their structural parent.
+ child_box.structural_parent.get_or_insert(parent);
child_box.parent = Some(parent);
}
Ok(())
}
+ /// Attaches one newly synthesized box through the same ownership seam as
+ /// construction-time children.
+ pub(crate) fn append_synthesized_child(
+ &mut self,
+ parent: LayoutBoxId,
+ child: LayoutBoxId,
+ ) -> Result<(), LayoutError> {
+ let Some(parent_box) = self.box_by_id(parent) else {
+ return Err(LayoutError::InvalidBoxReference {
+ index: parent.index(),
+ });
+ };
+ let mut children = parent_box.children.clone();
+ children.push(child);
+ self.replace_children(parent, children)
+ }
+
+ /// Records source/LayoutObject ownership before formatting normalization
+ /// is allowed to wrap or promote any child.
+ ///
+ /// The first owner deliberately wins. A split inline returns its promoted
+ /// block in an ancestor's child stream later, but that reattachment must
+ /// not erase the inline LayoutObject that originally owned the block.
+ pub(crate) fn record_structural_children(
+ &mut self,
+ parent: LayoutBoxId,
+ children: &[LayoutBoxId],
+ ) -> Result<(), LayoutError> {
+ if self.box_by_id(parent).is_none() {
+ return Err(LayoutError::InvalidBoxReference {
+ index: parent.index(),
+ });
+ }
+ for child in children {
+ let Some(child_box) = self.box_by_id_mut(*child) else {
+ return Err(LayoutError::InvalidBoxReference {
+ index: child.index(),
+ });
+ };
+ child_box.structural_parent.get_or_insert(parent);
+ }
+ Ok(())
+ }
+
pub(crate) fn compact_reachable(&mut self) {
let mut reachable = vec![false; self.boxes.len()];
let mut stack = vec![self.root];
@@ -673,6 +736,9 @@ where
if !reachable[index] {
continue;
}
+ layout_box.structural_parent = layout_box
+ .structural_parent
+ .and_then(|parent| remap[parent.index()]);
layout_box.parent = layout_box.parent.and_then(|parent| remap[parent.index()]);
layout_box.children = layout_box
.children
@@ -756,6 +822,20 @@ where
id: LayoutBoxId,
layout_box: &LayoutBox<N>,
) -> Result<(), LayoutError> {
+ if id == self.root {
+ if layout_box.structural_parent.is_some() {
+ return Err(LayoutError::InvalidBoxReference { index: id.index() });
+ }
+ } else if layout_box.structural_parent.is_none() {
+ return Err(LayoutError::InvalidBoxReference { index: id.index() });
+ }
+ if let Some(parent) = layout_box.structural_parent
+ && (parent == id || self.box_by_id(parent).is_none())
+ {
+ return Err(LayoutError::InvalidBoxReference {
+ index: parent.index(),
+ });
+ }
if let Some(source) = layout_box.source {
if layout_box.owner.is_some()
|| layout_box.pseudo.is_some()
@@ -891,6 +971,7 @@ where
anonymous_reason,
capability_diagnostics,
kind,
+ structural_parent: None,
parent: None,
children: Vec::new(),
layout_parent: None,
diff --git a/moli-layout/tests/box_builder_contract.rs b/moli-layout/tests/box_builder_contract.rs
index a1f07009d..30cb49580 100644
--- a/moli-layout/tests/box_builder_contract.rs
+++ b/moli-layout/tests/box_builder_contract.rs
@@ -921,7 +921,8 @@ fn inline_with_block_descendant_is_split_into_owned_continuations() {
assert_eq!(before_wrapper.kind(), LayoutBoxKind::AnonymousBlock);
assert_eq!(block.kind(), LayoutBoxKind::PrincipalBlock);
assert_eq!(after_wrapper.kind(), LayoutBoxKind::AnonymousBlock);
- let first_fragment = world.box_by_id(before_wrapper.children()[0]).unwrap();
+ let first_fragment_id = before_wrapper.children()[0];
+ let first_fragment = world.box_by_id(first_fragment_id).unwrap();
let continuation = world.box_by_id(after_wrapper.children()[0]).unwrap();
assert_eq!(first_fragment.kind(), LayoutBoxKind::PrincipalInline);
assert_eq!(first_fragment.source(), Some(1));
@@ -932,6 +933,12 @@ fn inline_with_block_descendant_is_split_into_owned_continuations() {
continuation.anonymous_reason(),
Some(LayoutAnonymousReason::InlineSplitContinuation)
);
+ assert_eq!(
+ block.structural_parent(),
+ Some(first_fragment_id),
+ "formatting promotion must not erase the block's LayoutObject parent"
+ );
+ assert_eq!(continuation.structural_parent(), Some(world.root()));
assert_eq!(world.source_box(1), Some(before_wrapper.children()[0]));
}
diff --git a/moli-layout/tests/phase5_output_contract.rs b/moli-layout/tests/phase5_output_contract.rs
index 13d5e158e..82ee75ba3 100644
--- a/moli-layout/tests/phase5_output_contract.rs
+++ b/moli-layout/tests/phase5_output_contract.rs
@@ -3,11 +3,12 @@ use std::collections::HashMap;
use moli_layout::{
DocumentLayoutServices, LayoutControlSurfaceHit, LayoutDisplay, LayoutElementCategory,
LayoutElementSemantics, LayoutError, LayoutFlushReason, LayoutFragmentKind, LayoutNamespace,
- LayoutPaintedSurfaceHit, LayoutPassRequest, LayoutPassResult, LayoutPoint, LayoutQuery,
- LayoutQueryAnswer, LayoutQueryBatch, LayoutRect, LayoutScrollbarColors, LayoutScrollbarGutter,
- LayoutScrollbarPart, LayoutScrollbarWidth, LayoutSource, LayoutSourceKind, LayoutStyleResolver,
- LayoutTransform2D, LayoutViewport, PaintBrush, PaintCaptureRequest, PaintColor, PaintFragment,
- PaintShape, ResolvedLayoutStyle, build_layout_pass,
+ LayoutPaintedSurfaceHit, LayoutPassRequest, LayoutPassResult, LayoutPoint, LayoutPosition,
+ LayoutQuery, LayoutQueryAnswer, LayoutQueryBatch, LayoutRect, LayoutScrollbarColors,
+ LayoutScrollbarGutter, LayoutScrollbarPart, LayoutScrollbarWidth, LayoutSource,
+ LayoutSourceKind, LayoutStyleResolver, LayoutTransform2D, LayoutViewport, PaintBrush,
+ PaintCaptureRequest, PaintColor, PaintFragment, PaintShape, ResolvedLayoutStyle,
+ build_layout_pass,
};
use style::Atom;
use taffy::{
@@ -1512,6 +1513,32 @@ fn split_inline_continuations_remain_mapped_to_the_originating_element() {
assert!(union.height >= second.bottom() - first.y);
}
+#[test]
+fn block_in_inline_offset_parent_uses_the_structural_inline_ancestor() {
+ let source = Source(vec![
+ Node::element("root", vec![1]),
+ Node::element("positioned-inline", vec![2]),
+ Node::element("promoted-block", Vec::new()),
+ ]);
+ let mut styles = Styles::default();
+ styles
+ .0
+ .insert(0, fixed_size(LayoutDisplay::Block, 200.0, 120.0));
+ styles.0.insert(
+ 1,
+ resolved(LayoutDisplay::Inline, Style::default()).with_position(LayoutPosition::Relative),
+ );
+ styles
+ .0
+ .insert(2, fixed_size(LayoutDisplay::Block, 50.0, 20.0));
+
+ let output = build(&source, &mut styles);
+ let metrics = output
+ .element_metrics_for_source(2)
+ .expect("promoted block metrics");
+ assert_eq!(metrics.offset_parent, Some(1));
+}
+
#[test]
fn scroll_is_sampled_per_pass_and_updates_geometry_clip_and_hit_testing() {
let mut source = Source(vec![
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs
index 173c9cb14..325ffa385 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/rendering_update.rs
@@ -3029,6 +3029,50 @@ document.body.innerHTML = `<div class=row><div class=item id=ask><i class=icon><
.expect("rounded flex max-content fixture should run");
}
+#[tokio::test(flavor = "current_thread")]
+async fn block_in_inline_cssom_uses_structural_ancestors() {
+ 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/block-in-inline-ancestry.html")?,
+ );
+ page_vm.vm_mut().eval(
+ r#"
+document.head.innerHTML = `<style>
+html,body{margin:0;font-size:0}
+#parent{position:relative}
+#block{height:20px}
+#absolute{position:absolute;height:10px}
+</style>`;
+document.body.innerHTML = `<span id=parent><div id=block><div id=absolute></div></div></span>`;
+'installed'
+"#,
+ )?;
+ page_vm.vm_mut().sync_live_document_style_sources();
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(moli_layout::PaintViewport::new(200, 100, 1.0))?
+ .expect("block-in-inline fixture must retain a layout root");
+
+ assert_eq!(
+ page_vm.vm_mut().eval(
+ r#"[
+document.getElementById('block').offsetParent === document.getElementById('parent'),
+document.getElementById('absolute').offsetParent === document.getElementById('parent')
+].join('|')"#,
+ )?,
+ "true|true",
+ "formatting promotion must preserve LayoutObject ancestry for CSSOM",
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("block-in-inline CSSOM ancestry fixture should run");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn stylesheet_lifecycle_registers_only_the_current_documents_data_web_fonts() {
run_page_vm_async_test(async move {