Truly independent web browser
LibWeb: Keep the style of text inside a `display: contents` element
Tim Ledbetter534e1ae97711
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex a5184addb76..e41415ab6b5 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -824,9 +824,8 @@ Layout::NodeArena& Document::layout_node_arena()Layout::RustFFI::document_host_set_layout_update_host_callbacks(m_layout_node_arena->host(), layout_update_host_callbacks());Layout::RustFFI::FfiStyleRecordHostCallbacks style_record_host_callbacks {.context = this,- .shell_style_changed = [](void*, void* shell, u64 record, void const* payloads, bool derived, bool attach_resources) {- as<Layout::NodeWithStyle>(*static_cast<Layout::Node*>(shell)).refresh_style_from_arena(CSS::StyleRecordID { record }, payloads, derived, attach_resources);- },+ .shell_style_changed = [](void*, void* shell, u64 record, void const* payloads, bool derived, bool attach_resources) { as<Layout::NodeWithStyle>(*static_cast<Layout::Node*>(shell)).refresh_style_from_arena(CSS::StyleRecordID { record }, payloads, derived, attach_resources); },+ .shell_style_damaged = [](void*, void* shell, u32 damage) { Painting::repaint_after_style_change(*static_cast<Layout::Node*>(shell), CSS::decode_style_invalidation(damage)); },};Layout::RustFFI::document_host_set_style_record_host_callbacks(m_layout_node_arena->host(), style_record_host_callbacks);m_layout_node_arena->start_reporting_box_presence({});diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex 05495f767b4..975550e2245 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -2004,6 +2004,14 @@ bool Element::apply_box_presence_change_in_place(Layout::BegunRead const& read,return true;}+static void apply_display_contents_style_to_text_boxes(Element& element, CSS::RequiredInvalidationAfterStyleChange const& invalidation)+{+ if (invalidation.is_none())+ return;+ if (auto* arena = element.document().layout_node_arena_if_created())+ Layout::RustFFI::render_state_reinherit_display_contents_text(arena->host(), element.style_node_id().value());+}+void Element::apply_computed_style_to_layout_node_if_needed(Layout::BegunRead const& read, CSS::RequiredInvalidationAfterStyleChange const& invalidation){auto* layout_node = unsafe_layout_node(read);@@ -2013,6 +2021,8 @@ void Element::apply_computed_style_to_layout_node_if_needed(Layout::BegunRead coreturn;if (!layout_node) {+ if (auto style = computed_style(); style && style->display().is_contents())+ apply_display_contents_style_to_text_boxes(*this, invalidation);apply_computed_pseudo_element_styles_to_layout_nodes_if_needed(read, invalidation);return;}diff --git a/Libraries/LibWeb/Rust/src/layout/host_tables.rs b/Libraries/LibWeb/Rust/src/layout/host_tables.rsindex b78ec8b71c5..3ab7b61dbc7 100644--- a/Libraries/LibWeb/Rust/src/layout/host_tables.rs+++ b/Libraries/LibWeb/Rust/src/layout/host_tables.rs@@ -11,7 +11,7 @@use super::LayoutNodeArena;use super::formatting_context::FfiLayoutHostCallbacks;-use super::layout_node_arena::{ShellFactory, ShellStyleChangedHost};+use super::layout_node_arena::{FfiStyleRecordHostCallbacks, ShellFactory};use super::node_data::{NodeKind, NodeSlotId};use super::trace::DescribeNode;use super::update_layout::FfiLayoutUpdateHostCallbacks;@@ -36,7 +36,7 @@ pub(crate) struct HostTables {pub(super) layout_update_host: Cell<Option<FfiLayoutUpdateHostCallbacks>>,/// Makes the shell of an anonymous row the first time something asks for it.pub(super) shell_factory: Cell<Option<ShellFactory>>,- pub(super) shell_style_changed_host: Cell<Option<ShellStyleChangedHost>>,+ pub(super) style_record_host: Cell<Option<FfiStyleRecordHostCallbacks>>,pub(crate) chrome_state_callback: Cell<Option<ChromeStateCallback>>,/// What the overflow pass tells the document once it has settled a box's scroll offset.pub(crate) geometry_host: Cell<Option<FfiGeometryHostCallbacks>>,@@ -70,7 +70,7 @@ impl HostTables {self.layout_host.set(None);self.layout_update_host.set(None);self.shell_factory.set(None);- self.shell_style_changed_host.set(None);+ self.style_record_host.set(None);self.chrome_state_callback.set(None);self.geometry_host.set(None);}diff --git a/Libraries/LibWeb/Rust/src/layout/layout_changes.rs b/Libraries/LibWeb/Rust/src/layout/layout_changes.rsindex ef470d03535..ede602f2d2f 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_changes.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_changes.rs@@ -344,6 +344,8 @@ pub(crate) enum LayoutWrite<'a> {AdoptDerivedNodeStyle { node: NodeSlotId, record: u64 },/// The anonymous rows below the row inherit its style again.ReinheritAnonymousDescendants { node: NodeSlotId },+ /// The anonymous boxes that give the text of a `display: contents` element its style take it again.+ ReinheritDisplayContentsText { element: StyleNodeID },/// The viewport and the boxes of the root element and its body take the styles viewport propagation gives them.PropagateRootStylesToViewport,/// Prepares every row of the subtree the row heads for leaving the layout tree.@@ -397,6 +399,10 @@ impl LayoutWrite<'_> {arena.reinherit_anonymous_descendants(host_calls, node);false}+ Self::ReinheritDisplayContentsText { element } => {+ arena.reinherit_display_contents_text(host_calls, element);+ false+ }Self::PropagateRootStylesToViewport => {let viewport = arena.bound_viewport_row();if !viewport.is_invalid() {diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rsindex 06649604f88..805521d1779 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs@@ -595,15 +595,9 @@ pub const BOX_PRESENCE_HAS_COMMITTED_BOX: u8 = 1 << 1;pub struct FfiStyleRecordHostCallbacks {pub context: *mut c_void,pub shell_style_changed: unsafe extern "C" fn(*mut c_void, *mut c_void, u64, *const c_void, bool, bool),+ pub shell_style_damaged: unsafe extern "C" fn(*mut c_void, *mut c_void, u32),}-/// How the host learns that a shell's row took a new style: the shell, its new record and-/// payloads, whether the arena derived the record, and whether the shell should attach the style's resources.-pub(crate) type ShellStyleChangedHost = (- *mut c_void,- unsafe extern "C" fn(*mut c_void, *mut c_void, u64, *const c_void, bool, bool),-);-/// Whether `a` and `b` hold equal payloads in the inherited groups, which are all an anonymous box inherits.fn style_payloads_equal_in_inherited_groups(a: StylePayloadsRef, b: StylePayloadsRef) -> bool {style_payloads_equal_in_groups(a, b, |group_index| {@@ -1170,6 +1164,8 @@ pub(crate) struct LayoutNodeArena {image_resources_owed_to_host: Vec<(NodeSlotId, OwedImageResources)>,/// The image boxes among the rows that own the provider of the image they show.owned_image_providers: HashMap<NodeSlotId, OwnedImageProvider>,+ /// The text node that each `display: contents` text wrapper box wraps.+ display_contents_text_wrappers: HashMap<NodeSlotId, StyleNodeID>,/// Whether a row has ever been given a style with `content-visibility: auto`.may_have_auto_content_visibility: bool,/// Whether a row has ever been given a style with a scroll snap type.@@ -1266,6 +1262,7 @@ impl LayoutNodeArena {built_scroll_containers: Default::default(),image_resources_owed_to_host: Default::default(),owned_image_providers: Default::default(),+ display_contents_text_wrappers: Default::default(),may_have_auto_content_visibility: false,may_have_scroll_snap_areas: false,nodes_enrolled_for_replaced_content_facts_sync: Vec::new(),@@ -1601,6 +1598,7 @@ impl LayoutNodeArena {}self.owned_image_natural_sizes.remove(&id);self.owned_image_providers.remove(&id);+ self.display_contents_text_wrappers.remove(&id);self.memo_invalidations.note_slot_freed(index);self.remove_layout_update_flag_node(id);self.math_layout_kinds.remove(&id);@@ -3609,6 +3607,12 @@ impl LayoutNodeArena {AnonymousStyleKind::WritingSuggestion,AnonymousStyleOverrides::default(),)+ } else if let Some(style_record) = self.display_contents_text_style_record(child) {+ self.derive_anonymous_style_record(+ style_record,+ AnonymousStyleKind::InlineStyleWrapper,+ AnonymousStyleOverrides::default(),+ )} else {let column_source = self.anonymous_box_column_source(child)@@ -3632,7 +3636,7 @@ impl LayoutNodeArena {host_calls: HostCalls<'_>,slot: NodeSlotId,derived: DerivedStyleRecord,- ) {+ ) -> bool {let previous_payloads = self.data(slot).style.get();let changes_layout_affecting_style =!self.style_move_keeps_layout_inputs(slot, previous_payloads, derived.payloads);@@ -3641,6 +3645,7 @@ impl LayoutNodeArena {self.invalidate_fragments_and_intrinsic_sizes_of_self_and_ancestors(slot);}self.notify_shell_of_style_change(host_calls, slot, false);+ changes_layout_affecting_style}fn notify_shell_of_style_change(&self, host_calls: HostCalls<'_>, slot: NodeSlotId, attach_resources: bool) {@@ -5365,6 +5370,55 @@ impl LayoutNodeArena {.is_some_and(|state| state.precedes_writing_suggestion)}+ pub(crate) fn note_display_contents_text_wrapper(&mut self, wrapper: NodeSlotId, text: StyleNodeID) {+ self.display_contents_text_wrappers.insert(wrapper, text);+ }++ pub(crate) fn reinherit_display_contents_text(&mut self, host_calls: HostCalls<'_>, element: StyleNodeID) {+ let assigned_node_count = self.assigned_node_count(Some(element));+ let children: smallvec::SmallVec<[StyleNodeID; 4]> = if assigned_node_count != 0 {+ (0..assigned_node_count)+ .map(|index| self.assigned_node_at(element, index))+ .collect()+ } else {+ self.with_style_store(|engine| engine.tree().dom_children(element).collect())+ };+ for child in children {+ let row = self.bound_row(child);+ if row.is_invalid() {+ continue;+ }+ let wrapper = self.data(row).parent.get();+ if wrapper.is_invalid() {+ continue;+ }+ let Some(style_record) = self.display_contents_text_style_record(wrapper) else {+ continue;+ };+ let derived = self.derive_anonymous_style_record(+ style_record,+ AnonymousStyleKind::InlineStyleWrapper,+ AnonymousStyleOverrides::default(),+ );+ let shown_record = self.node_style_record(wrapper);+ let damage = self+ .with_style_engine(|engine| engine.element_record_damage(element, true, shown_record, derived.record));+ if self.apply_reinherited_style_record(host_calls, wrapper, derived) {+ self.set_needs_layout_update(wrapper, true);+ }+ self.reinherit_anonymous_children(host_calls, wrapper, derived.record);+ if damage & crate::css::style::bridge::FfiStyleInvalidationField::LevelMask as u32 != 0 {+ host_calls.shell_style_damaged(wrapper, damage);+ }+ }+ }++ fn display_contents_text_style_record(&self, wrapper: NodeSlotId) -> Option<u64> {+ let text = self.display_contents_text_wrappers.get(&wrapper).copied()?;+ let style_record = self.text_style_parent_facts(Some(text)).style_record;+ (style_record != 0).then_some(style_record)+ }+/// Whether a box is the inline box that renders a writing suggestion, i.e. the one right after the text slice in/// front of the suggestion.fn is_writing_suggestion_box(&self, id: NodeSlotId) -> bool {@@ -6162,9 +6216,7 @@ pub unsafe extern "C" fn document_host_set_style_record_host_callbacks(host: &DocumentHost,callbacks: FfiStyleRecordHostCallbacks,) {- host.host_tables()- .shell_style_changed_host- .set(Some((callbacks.context, callbacks.shell_style_changed)));+ host.host_tables().style_record_host.set(Some(callbacks));}#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena/main_thread_entries.rsindex ed358a0f50a..c897b8ed022 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena/main_thread_entries.rs@@ -136,6 +136,16 @@ pub unsafe extern "C" fn render_state_reinherit_anonymous_descendants(host.queue_change(crate::render_state::ArenaChange::ReinheritAnonymousDescendants(node));}+/// The anonymous boxes that give the text of the `display: contents` element `element` its style take it again, which+/// their layout nodes hear of once the host has its next job back.+#[unsafe(no_mangle)]+pub extern "C" fn render_state_reinherit_display_contents_text(host: &DocumentHost, element: u32) {+ let Some(element) = StyleNodeID::from_raw(element) else {+ return;+ };+ host.queue_change(crate::render_state::ArenaChange::ReinheritDisplayContentsText(element));+}+/// The viewport and the boxes of the root element and its body take the styles viewport propagation gives them, which/// their layout nodes hear of before the host goes on.///diff --git a/Libraries/LibWeb/Rust/src/layout/tree_builder.rs b/Libraries/LibWeb/Rust/src/layout/tree_builder.rsindex 5ac6d0c3c8d..432fdac6c53 100644--- a/Libraries/LibWeb/Rust/src/layout/tree_builder.rs+++ b/Libraries/LibWeb/Rust/src/layout/tree_builder.rs@@ -2929,6 +2929,9 @@ fn construct_principal_layout_node(NodeKind::InlineNode,);let wrapper_slot = wrapper.slot();+ if let Some(text) = update.style_node {+ host.arena_mut().note_display_contents_text_wrapper(wrapper_slot, text);+ }host.set_children_are_inline(wrapper_slot, true);host.attach_child(wrapper_slot, host.created(text_layout_node), NodeSlotId::INVALID);layout_node = wrapper_slot;diff --git a/Libraries/LibWeb/Rust/src/layout/tree_mutation.rs b/Libraries/LibWeb/Rust/src/layout/tree_mutation.rsindex 347087ef27a..777570cf219 100644--- a/Libraries/LibWeb/Rust/src/layout/tree_mutation.rs+++ b/Libraries/LibWeb/Rust/src/layout/tree_mutation.rs@@ -40,6 +40,11 @@ enum OwedHostCall {row: NodeSlotId,attach_resources: bool,},+ /// A kept box, whose row took a style the arena derived.+ ShellStyleDamaged {+ row: NodeSlotId,+ damage: u32,+ },}/// What a tree build or a layout write owes the host, gathered while it runs and resolved as it ends (see@@ -79,6 +84,13 @@ impl OwedHostWork {attach_resources,}}+ OwedHostCall::ShellStyleDamaged { row, damage } => DueHostCall::ShellStyleDamaged {+ facts: crate::layout::host_tables::ShellFacts {+ id: row,+ kind: arena.node_kind_if_live(row)?,+ },+ damage,+ },})}).collect();@@ -103,6 +115,10 @@ enum DueHostCall {derived: bool,attach_resources: bool,},+ ShellStyleDamaged {+ facts: crate::layout::host_tables::ShellFacts,+ damage: u32,+ },}/// What a change to the layout tree owes the host, resolved against the arena it changed as it ended (see@@ -138,6 +154,9 @@ impl HostWorkDue {derived,attach_resources,} => tell_shell_of_style_change(main_thread, facts, record, payloads, derived, attach_resources),+ DueHostCall::ShellStyleDamaged { facts, damage } => {+ tell_shell_of_style_damage(main_thread, facts, damage);+ }}}}@@ -155,7 +174,7 @@ fn tell_shell_of_style_change(let Some(host_tables) = main_thread.host_tables() else {return;};- let Some((context, shell_style_changed)) = host_tables.shell_style_changed_host.get() else {+ let Some(callbacks) = host_tables.style_record_host.get() else {return;};// A row owed its style resources gets its shell now: the shell is what loads them, and a shell made later by the@@ -174,8 +193,8 @@ fn tell_shell_of_style_change(// SAFETY: The engine and shell remain live. Native style-store mutation has finished before the host can reenter// Rust through its resource consumers.unsafe {- shell_style_changed(- context,+ (callbacks.shell_style_changed)(+ callbacks.context,shell.as_ptr(),record,payloads.as_ptr().cast(),@@ -185,6 +204,25 @@ fn tell_shell_of_style_change(};}+/// Tells the layout node of the row `facts` describes, made now if nothing made one, what the move of the row to its+/// style damages.+fn tell_shell_of_style_damage(main_thread: &MainThread, facts: crate::layout::host_tables::ShellFacts, damage: u32) {+ if facts.kind == NodeKind::Unset {+ return;+ }+ let Some(host_tables) = main_thread.host_tables() else {+ return;+ };+ let Some(callbacks) = host_tables.style_record_host.get() else {+ return;+ };+ let Some(shell) = std::ptr::NonNull::new(host_tables.shell_of(facts)) else {+ return;+ };+ // SAFETY: The engine and shell remain live, and the host has its job back.+ unsafe { (callbacks.shell_style_damaged)(callbacks.context, shell.as_ptr(), damage) };+}+impl HostCalls<'_> {/// Frees the subtree `root` heads, and owes the host the destruction of what its rows held that the host owns the/// memory of.@@ -206,6 +244,10 @@ impl HostCalls<'_> {pub(crate) fn shell_style_changed(self, row: NodeSlotId, attach_resources: bool) {self.0.owe(OwedHostCall::ShellStyleChanged { row, attach_resources });}++ pub(crate) fn shell_style_damaged(self, row: NodeSlotId, damage: u32) {+ self.0.owe(OwedHostCall::ShellStyleDamaged { row, damage });+ }}#[must_use = "an unplaced layout node must be attached or freed"]diff --git a/Libraries/LibWeb/Rust/src/render_state.rs b/Libraries/LibWeb/Rust/src/render_state.rsindex 252d67d2eff..858364c6eab 100644--- a/Libraries/LibWeb/Rust/src/render_state.rs+++ b/Libraries/LibWeb/Rust/src/render_state.rs@@ -356,6 +356,8 @@ pub(crate) enum ArenaChange {/// [`crate::layout::LayoutNodeArena::reinherit_anonymous_descendants`]), which owes their layout/// nodes the records they take, paid once the job that applies it is done.ReinheritAnonymousDescendants(crate::layout::node_data::NodeSlotId),+ /// The anonymous boxes that give the text of a `display: contents` element its style take it again.+ ReinheritDisplayContentsText(crate::css::style::tree::StyleNodeID),/// A removed node's box leaves its parent's box in place, or the parent is marked for a rebuild, as the render state/// finds the boxes (see [`crate::layout::box_removal`]), which owes the host what it pays once the job that applies/// it is done.@@ -409,6 +411,11 @@ impl ArenaChange {);}}+ Self::ReinheritDisplayContentsText(element) => owed.push(+ crate::layout::layout_changes::LayoutWrite::ReinheritDisplayContentsText { element }+ .apply(arena)+ .host_work,+ ),Self::RemoveBox(removal) => removal.apply(arena, owed),Self::Paint(change) => change.apply(arena),Self::Style(change) => change.apply(state.engine_mut()),@@ -434,6 +441,7 @@ impl ArenaChange {| Self::Paint(_)| Self::DetachForRemoval(_)| Self::ReinheritAnonymousDescendants(_)+ | Self::ReinheritDisplayContentsText(_)| Self::RemoveBox(_) => false,}}@@ -447,9 +455,11 @@ impl ArenaChange {Self::Layout(change) => (false, change.may_move_facts()),Self::Style(change) => (change.may_move_facts(), change.may_move_facts()),Self::Engine(write) => (write.may_move_facts(), write.may_move_facts()),- Self::DetachForRemoval(_) | Self::ReinheritAnonymousDescendants(_) | Self::RemoveBox(_) | Self::Rule(_) => {- (true, true)- }+ Self::DetachForRemoval(_)+ | Self::ReinheritAnonymousDescendants(_)+ | Self::ReinheritDisplayContentsText(_)+ | Self::RemoveBox(_)+ | Self::Rule(_) => (true, true),};Moves {rows: self.row_write(),@@ -465,7 +475,7 @@ impl ArenaChange {Self::Layout(change) => change.row_write(),Self::Paint(change) => change.row_write(),Self::DetachForRemoval(_) | Self::RemoveBox(_) => RowWrite::Identities,- Self::ReinheritAnonymousDescendants(_) => RowWrite::NamedStyles,+ Self::ReinheritAnonymousDescendants(_) | Self::ReinheritDisplayContentsText(_) => RowWrite::NamedStyles,Self::Style(_) | Self::Engine(_) | Self::Rule(_) => RowWrite::None,}}@@ -576,7 +586,9 @@ impl ChangeQueue {ArenaChange::Layout(crate::layout::layout_changes::LayoutChange::SetNodeStyle { node, .. }) => {self.styled_rows.borrow_mut().insert(*node);}- ArenaChange::ReinheritAnonymousDescendants(_) => self.restyles_anonymous_rows.set(true),+ ArenaChange::ReinheritAnonymousDescendants(_) | ArenaChange::ReinheritDisplayContentsText(_) => {+ self.restyles_anonymous_rows.set(true);+ }_ => {}}let (moves, change) = (self.moves.get(), change.moves());diff --git a/Tests/LibWeb/Ref/expected/display-contents-text-takes-element-style-ref.html b/Tests/LibWeb/Ref/expected/display-contents-text-takes-element-style-ref.htmlnew file mode 100644index 00000000000..df1e0d9c885--- /dev/null+++ b/Tests/LibWeb/Ref/expected/display-contents-text-takes-element-style-ref.html@@ -0,0 +1,4 @@+<!DOCTYPE html>+<div style="color: green">Sample text</div>+<div style="color: green">Sample text</div>+<div style="color: green">Sample text</div>diff --git a/Tests/LibWeb/Ref/input/display-contents-text-takes-element-style.html b/Tests/LibWeb/Ref/input/display-contents-text-takes-element-style.htmlnew file mode 100644index 00000000000..ff21ffc4bca--- /dev/null+++ b/Tests/LibWeb/Ref/input/display-contents-text-takes-element-style.html@@ -0,0 +1,20 @@+<!DOCTYPE html>+<html class="reftest-wait">+<link rel="match" href="../expected/display-contents-text-takes-element-style-ref.html">+<div id="host" style="color: red">Sample text</div>+<div><span id="contents" style="display: contents; color: red">Sample text</span></div>+<div id="block-slot-host"><span id="slotted-contents" style="display: contents; color: red">Sample text</span></div>+<script>+ document.getElementById("host").attachShadow({ mode: "open" }).innerHTML = `<slot style="color: green"></slot>`;+ document.getElementById("block-slot-host").attachShadow({ mode: "open" }).innerHTML = `<slot style="display: block"></slot>`;+ const nextFrame = () => new Promise(resolve => requestAnimationFrame(resolve));+ (async () => {+ await nextFrame();+ await nextFrame();+ document.getElementById("host").style.color = "blue";+ document.getElementById("contents").style.color = "green";+ document.getElementById("slotted-contents").style.color = "green";+ document.documentElement.classList.remove("reftest-wait");+ })();+</script>+</html>