Skip to content

armgit / moli

Public Imported from GitHub
0

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

Model table cell presentation padding

ldm03300ba2af23b
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 4437a4beb..173c9cb14 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
@@ -2444,6 +2444,111 @@ html,body{{margin:0;padding:0;background:white}}
.expect("WebP and SVG CSS URL image-layer fixture should run");
}
+#[tokio::test(flavor = "current_thread")]
+async fn screenshot_recascades_nearest_table_cell_presentation_style() {
+ 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/table-cell-presentation-style.html")?,
+ );
+ page_vm.vm_mut().eval(
+ r#"
+document.head.innerHTML = `<style>
+html,body{margin:0;padding:0}
+table{border-spacing:0}
+td{font-size:0;border:0}
+.content{width:10px;height:10px}
+#author-cell{padding:7px}
+</style>`;
+document.body.innerHTML = `
+<table><tr><td id=default-cell><div class=content></div></td></tr></table>
+<table id=legacy-table cellpadding=4><tr><td id=legacy-cell><div class=content></div></td></tr></table>
+<table cellpadding=3><tr><td><table cellpadding=5><tr><td id=nested-cell><div class=content></div></td></tr></table></td></tr></table>
+<table id=author-table cellpadding=4><tr><td id=author-cell><div class=content></div></td></tr></table>`;
+const orphan = document.createElement('td');
+orphan.id = 'orphan-cell';
+orphan.innerHTML = '<div class=content></div>';
+document.body.append(orphan);
+'installed'
+"#,
+ )?;
+ page_vm.vm_mut().sync_live_document_style_sources();
+
+ let viewport = moli_layout::PaintViewport::new(200, 200, 1.0);
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(viewport)?
+ .expect("table-cell fixture must retain a layout root");
+ let read_cells = r#"(() => {
+const read = (id, includeGeometry = true) => {
+ const cell = document.getElementById(id);
+ const style = getComputedStyle(cell);
+ const values = [style.paddingTop,style.paddingRight,style.paddingBottom,style.paddingLeft];
+ if (includeGeometry) values.push(cell.offsetWidth,cell.offsetHeight);
+ return values.join(',');
+};
+return [
+ read('default-cell'),
+ read('legacy-cell'),
+ read('nested-cell'),
+ read('author-cell'),
+ read('orphan-cell', false),
+].join('|');
+})()
+"#;
+ assert_eq!(
+ page_vm.vm_mut().eval(read_cells)?,
+ "1px,1px,1px,1px,12,12|4px,4px,4px,4px,18,18|5px,5px,5px,5px,20,20|7px,7px,7px,7px,24,24|1px,1px,1px,1px",
+ "table cells must use the nearest table's legacy padding while author CSS and the orphan-cell UA fallback remain authoritative",
+ );
+
+ page_vm
+ .vm_mut()
+ .eval("document.getElementById('legacy-table').setAttribute('cellpadding','8')")?;
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(viewport)?
+ .expect("mutated table-cell fixture must retain a layout root");
+ assert_eq!(
+ page_vm.vm_mut().eval(read_cells)?,
+ "1px,1px,1px,1px,12,12|8px,8px,8px,8px,26,26|5px,5px,5px,5px,20,20|7px,7px,7px,7px,24,24|1px,1px,1px,1px",
+ "cellpadding mutation must recascade descendant cells without crossing a nested table boundary",
+ );
+
+ page_vm
+ .vm_mut()
+ .eval("document.getElementById('legacy-table').setAttribute('cellpadding','0')")?;
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(viewport)?
+ .expect("zero-cellpadding fixture must retain a layout root");
+ assert_eq!(
+ page_vm.vm_mut().eval(read_cells)?,
+ "1px,1px,1px,1px,12,12|0px,0px,0px,0px,10,10|5px,5px,5px,5px,20,20|7px,7px,7px,7px,24,24|1px,1px,1px,1px",
+ "cellpadding=0 must remove the shared presentational declaration",
+ );
+
+ page_vm
+ .vm_mut()
+ .eval("document.getElementById('legacy-table').removeAttribute('cellpadding')")?;
+ page_vm
+ .vm_mut()
+ .screenshot_layout_snapshot(viewport)?
+ .expect("default-cellpadding fixture must retain a layout root");
+ assert_eq!(
+ page_vm.vm_mut().eval(read_cells)?,
+ "1px,1px,1px,1px,12,12|1px,1px,1px,1px,12,12|5px,5px,5px,5px,20,20|7px,7px,7px,7px,24,24|1px,1px,1px,1px",
+ "removing cellpadding must restore the historical 1px default",
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("table-cell presentational-style fixture should run");
+}
+
#[tokio::test(flavor = "current_thread")]
async fn screenshot_paints_fresh_inline_svg_resources_with_computed_current_color() {
run_page_vm_async_test(async move {
diff --git a/moli-renderer-v8/src/style_engine/eligibility.rs b/moli-renderer-v8/src/style_engine/eligibility.rs
index d2393c7c4..1d11769bf 100644
--- a/moli-renderer-v8/src/style_engine/eligibility.rs
+++ b/moli-renderer-v8/src/style_engine/eligibility.rs
@@ -13,6 +13,7 @@ pub(super) fn attribute_has_non_css_runtime_side_effect(name: &str) -> bool {
matches!(
StyleAttributeImpact::for_attribute_name(name),
StyleAttributeImpact::LayoutMetric
+ | StyleAttributeImpact::DescendantComputedStyle
| StyleAttributeImpact::StylesheetLinkage
| StyleAttributeImpact::LayoutMetricAndStylesheetLinkage
)
diff --git a/moli-renderer-v8/src/style_engine/mutation_effect.rs b/moli-renderer-v8/src/style_engine/mutation_effect.rs
index d7fdbc7ed..0488bd261 100644
--- a/moli-renderer-v8/src/style_engine/mutation_effect.rs
+++ b/moli-renderer-v8/src/style_engine/mutation_effect.rs
@@ -157,6 +157,7 @@ pub(crate) enum StyleAttributeImpact {
None,
LayoutMetric,
ComputedStyle,
+ DescendantComputedStyle,
StylesheetLinkage,
LayoutMetricAndStylesheetLinkage,
}
@@ -168,6 +169,7 @@ impl StyleAttributeImpact {
"style" | "class" | "id" => Self::ComputedStyle,
"hidden" | "width" | "height" | "cols" | "rows" | "size" | "value" | "border"
| "slot" | "align" => Self::LayoutMetric,
+ "cellpadding" => Self::DescendantComputedStyle,
"href" | "rel" | "media" | "blocking" | "disabled" => Self::StylesheetLinkage,
"type" => Self::LayoutMetricAndStylesheetLinkage,
_ if moli_selector::is_svg_presentation_attribute_name(&name) => Self::LayoutMetric,
@@ -178,13 +180,16 @@ impl StyleAttributeImpact {
pub(crate) fn affects_layout_metric(self) -> bool {
matches!(
self,
- Self::LayoutMetric | Self::ComputedStyle | Self::LayoutMetricAndStylesheetLinkage
+ Self::LayoutMetric
+ | Self::ComputedStyle
+ | Self::DescendantComputedStyle
+ | Self::LayoutMetricAndStylesheetLinkage
)
}
#[cfg(test)]
pub(crate) fn changes_computed_style(self) -> bool {
- matches!(self, Self::ComputedStyle)
+ matches!(self, Self::ComputedStyle | Self::DescendantComputedStyle)
}
#[cfg(test)]
diff --git a/moli-renderer-v8/src/style_engine/tests/lifecycle.rs b/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
index b81bbdbee..a16e875bb 100644
--- a/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
+++ b/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
@@ -2568,6 +2568,10 @@ fn style_attribute_impact_classifies_dom_and_stylesheet_inputs() {
);
}
+ assert!(StyleAttributeImpact::for_attribute_name("cellpadding").affects_layout_metric());
+ assert!(StyleAttributeImpact::for_attribute_name("cellpadding").changes_computed_style());
+ assert!(!StyleAttributeImpact::for_attribute_name("cellpadding").changes_stylesheet_linkage());
+
assert!(!StyleAttributeImpact::for_attribute_name("href").affects_layout_metric());
assert!(StyleAttributeImpact::for_attribute_name("href").changes_stylesheet_linkage());
diff --git a/moli-renderer-v8/src/style_engine/ua/html.css b/moli-renderer-v8/src/style_engine/ua/html.css
index 23ee9a372..c9a8e1255 100644
--- a/moli-renderer-v8/src/style_engine/ua/html.css
+++ b/moli-renderer-v8/src/style_engine/ua/html.css
@@ -111,6 +111,13 @@ td, th {
display: table-cell;
}
+/* Normal table cells receive their padding from the nearest table's legacy
+ shared cell style. Keep Blink's UA fallback for orphan cells. */
+td:not(table td),
+th:not(table th) {
+ padding: 1px;
+}
+
caption {
display: table-caption;
}
diff --git a/moli-selector/src/stylo/presentation.rs b/moli-selector/src/stylo/presentation.rs
index 00ca17c28..ca8f86f52 100644
--- a/moli-selector/src/stylo/presentation.rs
+++ b/moli-selector/src/stylo/presentation.rs
@@ -1,11 +1,11 @@
// SPDX-License-Identifier: MIT OR Apache-2.0
//
-// SVG presentation-attribute synthesis is narrowly ported from
-// DioxusLabs/blitz packages/blitz-dom/src/stylo.rs. Keeping it in the Stylo
-// adapter lets the normal cascade, inheritance, and relative-length resolver
-// own the result instead of teaching layout about authored attribute strings.
+// Presentational hints belong at the Stylo adapter boundary. Keeping legacy
+// HTML attributes and SVG presentation attributes here lets the normal
+// cascade, inheritance, and relative-length resolver own the result instead
+// of teaching layout about authored attribute strings.
-use selectors::sink::Push;
+use selectors::{Element as SelectorsElement, sink::Push};
use style::{
applicable_declarations::ApplicableDeclarationBlock,
context::QuirksMode,
@@ -16,7 +16,10 @@ use style::{
rule_tree::{CascadeLevel, CascadeOrigin},
servo_arc::Arc,
stylesheets::{CssRuleType, Origin, UrlExtraData, layer_rule::LayerOrder},
- values::specified::{LengthPercentage, NoCalcLength, NoCalcPercentage},
+ values::{
+ generics::NonNegative,
+ specified::{LengthPercentage, NoCalcLength, NoCalcPercentage},
+ },
};
use style_traits::ParsingMode;
@@ -24,6 +27,7 @@ use crate::dom::native::Element;
use super::query::QueryElement;
+const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml";
const SVG_NAMESPACE: &str = "http://www.w3.org/2000/svg";
// Mirrors Blink's CSSPropertyIdForSVGAttributeName allowlist. These attributes
@@ -99,31 +103,35 @@ pub fn is_svg_presentation_attribute_name(name: &str) -> bool {
}
impl QueryElement<'_> {
- pub(in crate::stylo) fn synthesize_svg_presentational_hints<V>(&self, hints: &mut V)
+ pub(in crate::stylo) fn synthesize_presentational_hints<V>(&self, hints: &mut V)
where
V: Push<ApplicableDeclarationBlock>,
{
let element = self.element();
- if element.namespace() != SVG_NAMESPACE {
- return;
- }
-
let mut block = PropertyDeclarationBlock::new();
- if element.local_name() == "svg" {
- append_root_svg_size_declarations(element, &mut block);
- }
+ if element.namespace() == SVG_NAMESPACE {
+ if element.local_name() == "svg" {
+ append_root_svg_size_declarations(element, &mut block);
+ }
- let base_url = self
- .host()
- .owner_document_handle(self.handle())
- .and_then(|document| self.host().document_base_url_for_handle(document));
- if let Some(base_url) = base_url {
- append_svg_style_presentation_declarations(
- element,
- &UrlExtraData::from(base_url),
- self.read_quirks_mode(),
- &mut block,
- );
+ let base_url = self
+ .host()
+ .owner_document_handle(self.handle())
+ .and_then(|document| self.host().document_base_url_for_handle(document));
+ if let Some(base_url) = base_url {
+ append_svg_style_presentation_declarations(
+ element,
+ &UrlExtraData::from(base_url),
+ self.read_quirks_mode(),
+ &mut block,
+ );
+ }
+ } else if element.namespace() == HTML_NAMESPACE
+ && matches!(element.local_name(), "td" | "th")
+ {
+ append_html_table_cell_padding_declarations(*self, &mut block);
+ } else {
+ return;
}
if !block.is_empty() {
@@ -144,7 +152,7 @@ fn append_root_svg_size_declarations(element: &Element, block: &mut PropertyDecl
let Some(size) = parse_svg_size_attribute(value) else {
continue;
};
- use style::values::generics::{NonNegative, length::Size};
+ use style::values::generics::length::Size;
let size = Size::LengthPercentage(NonNegative(size));
let declaration = if is_width {
PropertyDeclaration::Width(size)
@@ -189,6 +197,73 @@ fn append_svg_style_presentation_declarations(
}
}
+fn append_html_table_cell_padding_declarations(
+ element: QueryElement<'_>,
+ block: &mut PropertyDeclarationBlock,
+) {
+ // Blink's HTMLTableCellElement asks its nearest parent table for a shared
+ // cell style. Cells without a parent table instead receive the equivalent
+ // 1px fallback from the UA stylesheet.
+ let mut ancestor = element.parent_element();
+ let padding = loop {
+ let Some(current) = ancestor else {
+ return;
+ };
+ let native = current.element();
+ if native.namespace() == HTML_NAMESPACE && native.local_name() == "table" {
+ break parse_html_table_cell_padding(native.attribute("cellpadding"));
+ }
+ ancestor = current.parent_element();
+ };
+
+ // Chromium omits the shared declaration for zero rather than emitting
+ // `padding: 0`. That distinction lets lower cascade origins remain
+ // observable when the legacy attribute disables the default padding.
+ if padding == 0 {
+ return;
+ }
+
+ let padding = NonNegative(LengthPercentage::Length(NoCalcLength::from_px(f32::from(
+ padding,
+ ))));
+ for declaration in [
+ PropertyDeclaration::PaddingTop(padding.clone()),
+ PropertyDeclaration::PaddingRight(padding.clone()),
+ PropertyDeclaration::PaddingBottom(padding.clone()),
+ PropertyDeclaration::PaddingLeft(padding),
+ ] {
+ block.push(declaration, Importance::Normal);
+ }
+}
+
+/// Mirrors Blink's legacy `cellpadding` state: an absent or exactly empty
+/// attribute keeps the historical 1px default; non-empty values use loose
+/// signed-integer parsing and are clamped to `uint16_t`.
+fn parse_html_table_cell_padding(value: Option<&str>) -> u16 {
+ let Some(value) = value else {
+ return 1;
+ };
+ if value.is_empty() {
+ return 1;
+ }
+
+ parse_loose_i32(value)
+ .unwrap_or(0)
+ .clamp(0, i32::from(u16::MAX)) as u16
+}
+
+fn parse_loose_i32(value: &str) -> Option<i32> {
+ let value = value.trim_start();
+ let digits_start = usize::from(value.starts_with(['+', '-']));
+ let digits_len = value[digits_start..]
+ .bytes()
+ .take_while(u8::is_ascii_digit)
+ .count();
+ (digits_len != 0)
+ .then(|| &value[..digits_start + digits_len])
+ .and_then(|number| number.parse().ok())
+}
+
/// Parses the SVG 2 root `width`/`height` presentation attributes.
///
/// These are CSS `<length-percentage>` values, unlike legacy HTML dimension
@@ -257,4 +332,17 @@ mod tests {
assert!(!is_svg_presentation_attribute_name("viewBox"));
assert!(!is_svg_presentation_attribute_name("d"));
}
+
+ #[test]
+ fn html_table_cell_padding_matches_blink_legacy_parsing() {
+ assert_eq!(parse_html_table_cell_padding(None), 1);
+ assert_eq!(parse_html_table_cell_padding(Some("")), 1);
+ assert_eq!(parse_html_table_cell_padding(Some("0")), 0);
+ assert_eq!(parse_html_table_cell_padding(Some(" +12px")), 12);
+ assert_eq!(parse_html_table_cell_padding(Some("-3")), 0);
+ assert_eq!(parse_html_table_cell_padding(Some("70000")), u16::MAX);
+ assert_eq!(parse_html_table_cell_padding(Some("not-a-number")), 0);
+ assert_eq!(parse_html_table_cell_padding(Some(" ")), 0);
+ assert_eq!(parse_html_table_cell_padding(Some("2147483648")), 0);
+ }
}
diff --git a/moli-selector/src/stylo/query/element.rs b/moli-selector/src/stylo/query/element.rs
index 9d4babebe..196fab497 100644
--- a/moli-selector/src/stylo/query/element.rs
+++ b/moli-selector/src/stylo/query/element.rs
@@ -409,7 +409,7 @@ impl<'a> TElement for QueryElement<'a> {
) where
V: selectors::sink::Push<style::applicable_declarations::ApplicableDeclarationBlock>,
{
- self.synthesize_svg_presentational_hints(hints);
+ self.synthesize_presentational_hints(hints);
}
fn local_name(&self) -> &<SelectorImpl as selectors::parser::SelectorImpl>::BorrowedLocalName {
diff --git a/moli-selector/src/stylo/style_traversal.rs b/moli-selector/src/stylo/style_traversal.rs
index 222f8725c..967eef7ad 100644
--- a/moli-selector/src/stylo/style_traversal.rs
+++ b/moli-selector/src/stylo/style_traversal.rs
@@ -1566,11 +1566,11 @@ impl<'a> StyleElement<'a> {
)
}
- fn synthesize_svg_presentational_hints<V>(&self, hints: &mut V)
+ fn synthesize_presentational_hints<V>(&self, hints: &mut V)
where
V: selectors::sink::Push<style::applicable_declarations::ApplicableDeclarationBlock>,
{
- self.as_query().synthesize_svg_presentational_hints(hints);
+ self.as_query().synthesize_presentational_hints(hints);
}
fn from_handle(state: &'a StyleDomState, handle: NodeId) -> Option<Self> {
@@ -2101,7 +2101,7 @@ impl<'a> TElement for StyleElement<'a> {
) where
V: selectors::sink::Push<style::applicable_declarations::ApplicableDeclarationBlock>,
{
- self.synthesize_svg_presentational_hints(hints);
+ self.synthesize_presentational_hints(hints);
}
fn local_name(&self) -> &<SelectorImpl as selectors::parser::SelectorImpl>::BorrowedLocalName {