Skip to content

Truly independent web browser

LibWeb: Learn of the first paint of text from the layout node arena

Andreas Kling7c1acddf71a7
diff --git a/Libraries/LibWeb/DOM/CharacterData.cpp b/Libraries/LibWeb/DOM/CharacterData.cpp
index 52f243ac89d..e25fd4530df 100644
--- a/Libraries/LibWeb/DOM/CharacterData.cpp
+++ b/Libraries/LibWeb/DOM/CharacterData.cpp
@@ -22,7 +22,6 @@
#include <LibWeb/Editing/EditingHistory.h>
#include <LibWeb/Editing/SpellingMarkers.h>
#include <LibWeb/Editing/WritingSuggestionController.h>
-#include <LibWeb/PaintTiming/PaintTiming.h>
#include <LibWeb/Selection/Selection.h>
namespace Web::DOM {
@@ -234,9 +233,6 @@ WebIDL::ExceptionOr<void> CharacterData::replace_data(size_t offset, size_t coun
if (auto* parent = this->parent())
parent->set_needs_layout_tree_update(true, SetNeedsLayoutTreeUpdateReason::WhitespaceTextBoxChange);
}
- // NB: Paint timing stops looking at text that is all white space, which this text no longer is.
- if (whitespace_only_changed && is_connected() && !m_data.is_ascii_whitespace())
- PaintTiming::text_node_may_be_painted_for_the_first_time(as<Text>(*this));
}
bump_character_data_version();
diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cpp
index 5c35f01ad61..efc813ad95e 100644
--- a/Libraries/LibWeb/DOM/Node.cpp
+++ b/Libraries/LibWeb/DOM/Node.cpp
@@ -102,7 +102,6 @@
#include <LibWeb/MathML/MathMLElement.h>
#include <LibWeb/Namespace.h>
#include <LibWeb/Page/Page.h>
-#include <LibWeb/PaintTiming/PaintTiming.h>
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/SVG/SVGElement.h>
#include <LibWeb/SVG/SVGTitleElement.h>
@@ -2697,9 +2696,6 @@ void Node::inserted()
if (auto* text = as_if<Text>(*this); text && text->style_node_id() == 0)
CSS::record_text_connected(*text);
- if (auto* text = as_if<Text>(*this); text && is_connected())
- PaintTiming::text_node_may_be_painted_for_the_first_time(*text);
-
if (auto* element = as_if<Element>(*this)) {
// The content an element clones into its shadow tree from its own insertion steps lands under
// a root that connects only when this walk reaches it, so no subtree arrival covered it.
diff --git a/Libraries/LibWeb/PaintTiming/DocumentPaintTimingState.h b/Libraries/LibWeb/PaintTiming/DocumentPaintTimingState.h
index ff1c6717b63..bf7f77f3f03 100644
--- a/Libraries/LibWeb/PaintTiming/DocumentPaintTimingState.h
+++ b/Libraries/LibWeb/PaintTiming/DocumentPaintTimingState.h
@@ -10,6 +10,7 @@
#include <AK/Optional.h>
#include <AK/Utf16String.h>
#include <AK/Vector.h>
+#include <LibCompositing/RustFFI.h>
#include <LibGC/Ptr.h>
#include <LibGC/RootHashMap.h>
#include <LibGC/RootVector.h>
@@ -83,10 +84,16 @@ struct DocumentPaintTimingState {
// NB: Only whether an element is in the document's set of elements with rendered text is ever asked, so each
// element knows whether it is in it. See Element::is_in_set_of_elements_with_rendered_text().
- // NB: The text nodes of the document that have not been painted yet, which are looked at as each frame is
- // painted, so that the user agent knows when it paints a Text node for the first time. A text node is in
- // here once, however often it is inserted.
- OrderedHashTable<GC::Ref<DOM::Text>> text_nodes_pending_first_paint;
+ // NB: The user agent learns that it paints a Text node for the first time from the layout nodes of text nodes: the
+ // layout node arena notes each text layout node that was given new rendered text, as one made for an inserted
+ // text node or one whose text changed is, and the notes are taken as each frame is painted. These are the
+ // taken text layout nodes that were not paintable yet but may be once their style or layout changes, by slot.
+ // A slot whose layout node is gone is dropped the next time the list is looked at, so the list holds nothing of
+ // a removed node.
+ Vector<Compositing::RustFFI::NodeSlotId> text_boxes_pending_first_paint;
+
+ // NB: Whether the layout node arena was told to stop noting text layout nodes, once nothing reports them.
+ bool stopped_noting_text_boxes { false };
// https://w3c.github.io/largest-contentful-paint/#current-largest-contentful-paint-candidate
// A current largest contentful paint candidate, a largest contentful paint candidate or null, initially null.
diff --git a/Libraries/LibWeb/PaintTiming/PaintTiming.cpp b/Libraries/LibWeb/PaintTiming/PaintTiming.cpp
index 6f1685ae136..1381531fb96 100644
--- a/Libraries/LibWeb/PaintTiming/PaintTiming.cpp
+++ b/Libraries/LibWeb/PaintTiming/PaintTiming.cpp
@@ -5,6 +5,7 @@
*/
#include <AK/NeverDestroyed.h>
+#include <AK/QuickSort.h>
#include <LibGC/RootVector.h>
#include <LibWeb/CSS/ComputedValues.h>
#include <LibWeb/CSS/FontComputer.h>
@@ -423,15 +424,6 @@ void process_an_image_that_finished_loading(DOM::Element& element, ImageRequestI
});
}
-void text_node_may_be_painted_for_the_first_time(DOM::Text& text)
-{
- // OPTIMIZATION: A text node that nothing would report once it is painted is not looked at.
- auto& document = text.document();
- if (!tracks_painted_images_and_text(document))
- return;
- document.paint_timing_state().text_nodes_pending_first_paint.set(text);
-}
-
// NB: The element whose box is the containing block of the given text box.
static GC::Ptr<DOM::Element> element_which_determines_the_containing_block_of(Layout::Node const& text_box)
{
@@ -457,16 +449,28 @@ void mark_paint_timing(DOM::Document& document)
auto& state = document.paint_timing_state();
auto& reported_paints = state.set_of_previously_reported_paints;
+ auto* host = document.layout_node_arena().host();
+
// OPTIMIZATION: Nothing reports the images and text nodes that are painted from now on.
- if (!tracks_painted_images_and_text(document)) {
+ auto tracks_images_and_text = tracks_painted_images_and_text(document);
+ if (!tracks_images_and_text) {
state.images_pending_rendering.clear();
- state.text_nodes_pending_first_paint.clear();
+ state.text_boxes_pending_first_paint.clear();
+ if (!state.stopped_noting_text_boxes) {
+ Layout::ForcedReadScope read { document };
+ Layout::RustFFI::layout_stop_noting_text_rows_for_first_paint(host, read);
+ state.stopped_noting_text_boxes = true;
+ }
}
+ // OPTIMIZATION: The layout node arena knows without being asked whether it noted any text layout node since the
+ // last frame, so a frame that made none and changed no text asks nothing about text.
+ auto may_have_noted_text_boxes = tracks_images_and_text && Layout::RustFFI::layout_text_rows_may_await_first_paint(host);
+
// OPTIMIZATION: Nothing below reports anything once first paint and first contentful paint have been reported,
// unless an image or a text node may be painted for the first time.
if (reported_paints.contains(first_paint_name()) && reported_paints.contains(first_contentful_paint_name())
- && state.images_pending_rendering.is_empty() && state.text_nodes_pending_first_paint.is_empty())
+ && state.images_pending_rendering.is_empty() && state.text_boxes_pending_first_paint.is_empty() && !may_have_noted_text_boxes)
return;
// AD-HOC: Nothing is painted for a document whose initial paint is deferred until its fonts load.
@@ -508,13 +512,43 @@ void mark_paint_timing(DOM::Document& document)
return true;
});
+ // NB: The text layout nodes the layout node arena noted since the last frame join the ones that were not paintable
+ // yet. The arena hands each one out once, so a slot is in the list twice only if it was pending already.
+ auto& text_boxes = state.text_boxes_pending_first_paint;
+ if (may_have_noted_text_boxes) {
+ auto pending_count = text_boxes.size();
+ Layout::RustFFI::layout_take_text_rows_for_first_paint(host, &checker.read(), &text_boxes, [](void* context, Compositing::RustFFI::NodeSlotId slot) {
+ static_cast<Vector<Compositing::RustFFI::NodeSlotId>*>(context)->append(slot);
+ });
+ if (pending_count != 0 && text_boxes.size() != pending_count) {
+ quick_sort(text_boxes, [](auto a, auto b) { return a.index < b.index; });
+ size_t unique_count = 0;
+ for (size_t i = 0; i < text_boxes.size(); ++i) {
+ if (unique_count == 0 || text_boxes[unique_count - 1].index != text_boxes[i].index)
+ text_boxes[unique_count++] = text_boxes[i];
+ }
+ text_boxes.shrink(unique_count);
+ }
+ }
+
// NB: This is when the user agent paints a Text node for the first time.
- GC::RootVector<GC::Ref<DOM::Text>> text_nodes_no_longer_pending;
- auto is_no_longer_pending = [&](GC::Ref<DOM::Text> text) {
- if (!text->is_connected() || &text->document() != &document)
+ text_boxes.remove_all_matching([&](Compositing::RustFFI::NodeSlotId slot) {
+ // NB: A text node whose layout node is gone has its new layout node noted once it gets one.
+ auto const* text_box = document.layout_node_arena().node_if_live(checker.read(), slot);
+ if (!text_box)
+ return true;
+ auto* text = as_if<DOM::Text>(const_cast<DOM::Node*>(text_box->dom_node()));
+ if (!text || !text->is_connected() || &text->document() != &document)
+ return true;
+
+ // OPTIMIZATION: Once an element is in the set of elements with rendered text, the text nodes it owns are never
+ // read, so a text node whose element is in it already is not looked at again. Its layout node
+ // is noted again if its text changes, or if it is rebuilt, as it is when the node moves.
+ auto element = element_which_determines_the_containing_block_of(*text_box);
+ if (!element || element->is_in_set_of_elements_with_rendered_text())
return true;
- auto const* text_box = text->layout_node(checker.read());
- if (!text_box || !checker.is_paintable(*text_box, PaintableChecker::CheckAncestorOpacity::Yes)) {
+
+ if (!checker.is_paintable(*text_box, PaintableChecker::CheckAncestorOpacity::Yes)) {
// OPTIMIZATION: Text that is all white space and paints nothing, often in a box without fragments, is not
// looked at again until its data changes to something else.
return !is_non_empty(text->data().utf16_view());
@@ -525,23 +559,14 @@ void mark_paint_timing(DOM::Document& document)
// FIXME: - If text will not be painted due to the font face being in its font block period, then return.
// - Let element be the Element which determines the containing block of text.
- auto element = element_which_determines_the_containing_block_of(*text_box);
- if (!element)
- return true;
+ // NB: The element was found above.
// - Append text to element's set of owned text nodes.
// NB: The set of owned text nodes is only read for the elements that are appended to paintedTextNodes below,
// in this frame, so only their text nodes are kept.
- if (!element->is_in_set_of_elements_with_rendered_text())
- painted_text_nodes.ensure(*element).append(text);
+ painted_text_nodes.ensure(*element).append(*text);
return true;
- };
- for (auto text : state.text_nodes_pending_first_paint) {
- if (is_no_longer_pending(text))
- text_nodes_no_longer_pending.append(text);
- }
- for (auto text : text_nodes_no_longer_pending)
- state.text_nodes_pending_first_paint.remove(text);
+ });
// 6. For each Element element in doc's descendants:
// OPTIMIZATION: Only the elements that got their first owned text nodes in this frame can be appended below.
@@ -667,7 +692,6 @@ void DocumentPaintTimingState::visit_edges(GC::Cell::Visitor& visitor)
{
for (auto& record : images_pending_rendering)
visitor.visit(record.element);
- visitor.visit(text_nodes_pending_first_paint);
}
extern "C" {
diff --git a/Libraries/LibWeb/PaintTiming/PaintTiming.h b/Libraries/LibWeb/PaintTiming/PaintTiming.h
index d1371a39a75..56c1a283509 100644
--- a/Libraries/LibWeb/PaintTiming/PaintTiming.h
+++ b/Libraries/LibWeb/PaintTiming/PaintTiming.h
@@ -19,10 +19,6 @@ void process_an_image_that_finished_loading(DOM::Element&, ImageRequestInfo);
ImageRequestInfo image_request_info(Utf16String url, GC::Ptr<HTML::DecodedImageData const>);
-// NB: Lets paint timing know of a connected text node that may be painted for the first time, as it was inserted or
-// its data changed from white space to something else.
-void text_node_may_be_painted_for_the_first_time(DOM::Text&);
-
// https://w3c.github.io/paint-timing/#mark-paint-timing
void mark_paint_timing(DOM::Document&);
diff --git a/Libraries/LibWeb/Rust/src/layout/first_paint_text.rs b/Libraries/LibWeb/Rust/src/layout/first_paint_text.rs
new file mode 100644
index 00000000000..98f181e6dfb
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/layout/first_paint_text.rs
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The text rows paint timing has not looked at yet, which is how it learns that it paints a text node for the first
+//! time without the host noting anything as a text node is inserted or its data changes. The arena notes a text row
+//! each time the row is given rendered text it did not have, which every row a tree build makes is once, and a row is
+//! again when what it renders changes. Paint timing takes the rows once a frame is laid out, and the host knows from a
+//! flag the arena shares with it whether there are any, so a frame that made no text rows asks nothing.
+
+use super::LayoutNodeArena;
+use super::node_data::{NodeKind, NodeSlotId};
+use crate::fork::ForkReset;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+/// The fewest rows the noted rows are compacted at, whose dead and repeated rows are dropped as they grow while paint
+/// timing takes none, as it does for a document that renders no frames.
+const FEWEST_ROWS_TO_COMPACT: usize = 4096;
+
+#[derive(Default)]
+struct NotedRows {
+ rows: Vec<NodeSlotId>,
+ /// How many rows the rows are compacted at, once they grow to it.
+ compact_at: usize,
+}
+
+/// The text rows of the arena that were given new rendered text since paint timing last took them.
+#[derive(Clone, Default)]
+pub(crate) struct FirstPaintTextRows {
+ /// A fork starts with no rows: paint timing takes the rows of the state the host writes.
+ noted: ForkReset<NotedRows>,
+ /// Whether paint timing will never take the rows again, which it says once it reports nothing more about text.
+ stopped: bool,
+ /// Raised while any row is noted, which the host reads without asking.
+ any_noted: Arc<AtomicBool>,
+}
+
+impl FirstPaintTextRows {
+ pub(crate) fn share_any_noted_flag(&mut self, flag: Arc<AtomicBool>) {
+ self.any_noted = flag;
+ }
+
+ /// Gives a fork a flag of its own, which no host reads, and stops the fork noting rows, which paint timing never
+ /// takes from it.
+ pub(crate) fn detach_any_noted_flag_for_fork(&mut self) {
+ self.any_noted = Arc::default();
+ self.stopped = true;
+ }
+}
+
+impl LayoutNodeArena {
+ /// Notes that the row `id` was given rendered text it did not have, for paint timing to look at.
+ pub(super) fn note_text_row_for_first_paint(&mut self, id: NodeSlotId) {
+ if self.first_paint_text_rows.stopped || self.data(id).kind.get() != NodeKind::TextNode {
+ return;
+ }
+ let mut noted = std::mem::take(&mut *self.first_paint_text_rows.noted);
+ if noted.rows.len() >= noted.compact_at.max(FEWEST_ROWS_TO_COMPACT) {
+ noted.rows.retain(|&row| self.slot_is_live(row));
+ noted.rows.sort_unstable_by_key(|row| row.index);
+ noted.rows.dedup();
+ noted.compact_at = noted.rows.len() * 2;
+ }
+ if noted.rows.is_empty() {
+ self.first_paint_text_rows.any_noted.store(true, Ordering::Relaxed);
+ }
+ noted.rows.push(id);
+ *self.first_paint_text_rows.noted = noted;
+ }
+
+ /// Takes the text rows noted since the last take that are still live, each as the row its text node is bound to,
+ /// which is the text node's layout node, once and in the order of their slot ids.
+ pub(crate) fn take_text_rows_for_first_paint(&mut self) -> Vec<NodeSlotId> {
+ let noted = std::mem::take(&mut *self.first_paint_text_rows.noted);
+ self.first_paint_text_rows.any_noted.store(false, Ordering::Relaxed);
+ let mut rows: Vec<NodeSlotId> = noted
+ .rows
+ .into_iter()
+ .filter_map(|row| self.node_style_node(row))
+ .map(|text| self.bound_row(text))
+ .filter(|&row| self.slot_is_live(row) && self.data(row).kind.get() == NodeKind::TextNode)
+ .collect();
+ rows.sort_unstable_by_key(|row| row.index);
+ rows.dedup();
+ rows
+ }
+
+ /// Stops noting text rows for paint timing, which will never take them again.
+ pub(crate) fn stop_noting_text_rows_for_first_paint(&mut self) {
+ self.first_paint_text_rows.stopped = true;
+ *self.first_paint_text_rows.noted = NotedRows::default();
+ self.first_paint_text_rows.any_noted.store(false, Ordering::Relaxed);
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
index 0bc9029b718..fa7d81067cb 100644
--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
@@ -1294,6 +1294,8 @@ pub(crate) struct LayoutNodeArena {
/// as if `text_nodes_enrolled_for_content_sync` held them: a row in it is enrolled while it is live and has not
/// rendered its text yet. See [`Self::enroll_built_text_rows_for_content_sync`].
built_text_rows_awaiting_sync: ForkVec<NodeSlotId>,
+ /// The text rows given new rendered text since paint timing last took them.
+ pub(super) first_paint_text_rows: super::first_paint_text::FirstPaintTextRows,
/// The scroll containers a running tree build gave a style, which may be where scroll
/// snapping happens once the build is over.
built_scroll_containers: Vec<NodeSlotId>,
@@ -1411,6 +1413,7 @@ impl LayoutNodeArena {
pending_updates_escape_partial_relayout: false,
text_nodes_enrolled_for_content_sync: Default::default(),
built_text_rows_awaiting_sync: Default::default(),
+ first_paint_text_rows: Default::default(),
built_scroll_containers: Default::default(),
image_resources_owed_to_host: Default::default(),
owned_image_providers: Default::default(),
@@ -3130,6 +3133,7 @@ impl LayoutNodeArena {
let mut fork = self.clone();
fork.style_engine = ArenaStyleEngine(engine);
fork.svg_paint_resources.detach_enrolled_flag_for_fork();
+ fork.first_paint_text_rows.detach_any_noted_flag_for_fork();
fork.first_letter_styles_derived = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(
self.first_letter_styles_derived
.load(std::sync::atomic::Ordering::Relaxed),
@@ -3146,6 +3150,14 @@ impl LayoutNodeArena {
self.first_letter_styles_derived = flag;
}
+ /// Shares with the host the flag raised while any text row waits for paint timing to look at it.
+ pub(crate) fn share_text_rows_noted_for_first_paint(
+ &mut self,
+ flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
+ ) {
+ self.first_paint_text_rows.share_any_noted_flag(flag);
+ }
+
/// Gives the row at `index` the style record `record`, answering the one it held. A row whose record changes no
/// longer holds the image resources it was owed for the old one.
fn replace_style_record(&mut self, index: usize, record: u64) -> u64 {
@@ -5690,6 +5702,7 @@ impl LayoutNodeArena {
}
state.content = Some(content);
drop(state);
+ self.note_text_row_for_first_paint(id);
let parent = self.data(id).parent.get();
if !parent.is_invalid() && super::node_facts::has_flag(self.data(parent), NodeFlag::Anonymous) {
self.derive_flex_or_grid_item_flags(parent);
diff --git a/Libraries/LibWeb/Rust/src/layout/mod.rs b/Libraries/LibWeb/Rust/src/layout/mod.rs
index 196375351d7..7650193d829 100644
--- a/Libraries/LibWeb/Rust/src/layout/mod.rs
+++ b/Libraries/LibWeb/Rust/src/layout/mod.rs
@@ -17,6 +17,7 @@ pub(crate) mod box_alignment;
pub mod commit;
pub(crate) mod counters;
pub(crate) mod fc_run_cache;
+pub(crate) mod first_paint_text;
pub(crate) mod flex_formatting_context;
pub mod formatting_context;
pub(crate) mod fragment_overflow;
diff --git a/Libraries/LibWeb/Rust/src/layout/shell_reads.rs b/Libraries/LibWeb/Rust/src/layout/shell_reads.rs
index 53ca0321ab6..03494ea9f3f 100644
--- a/Libraries/LibWeb/Rust/src/layout/shell_reads.rs
+++ b/Libraries/LibWeb/Rust/src/layout/shell_reads.rs
@@ -174,6 +174,41 @@ pub extern "C" fn layout_rows_may_be_contentful(host: &DocumentHost, read: &Begu
!host.host_tables().image_observer_sets.borrow().is_empty() || rows.any_row_may_be_contentful()
}
+/// Whether a text row of `host`'s document may have been given new rendered text since paint timing last took the text
+/// rows, which it answers without asking the render state: it errs towards yes while a frame flies.
+#[unsafe(no_mangle)]
+pub extern "C" fn layout_text_rows_may_await_first_paint(host: &DocumentHost) -> bool {
+ host.text_rows_may_await_first_paint()
+}
+
+/// Hands `push_row` each text row of `host`'s document that was given new rendered text since the last take, once and
+/// as the layout node of its text node (see [`crate::layout::LayoutNodeArena::take_text_rows_for_first_paint`]).
+///
+/// # Safety
+///
+/// `push_row` must be safe to call with `context`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn layout_take_text_rows_for_first_paint(
+ host: &DocumentHost,
+ read: &BegunRead,
+ context: *mut c_void,
+ push_row: unsafe extern "C" fn(*mut c_void, NodeSlotId),
+) {
+ let rows = read_arena(host, read, (), |arena, ()| arena.take_text_rows_for_first_paint());
+ for row in rows {
+ // SAFETY: The caller vouches for calling push_row with context.
+ unsafe { push_row(context, row) };
+ }
+}
+
+/// Stops noting the text rows of `host`'s document for paint timing, which will never take them again.
+#[unsafe(no_mangle)]
+pub extern "C" fn layout_stop_noting_text_rows_for_first_paint(host: &DocumentHost, read: &BegunRead) {
+ read_arena(host, read, (), |arena, ()| {
+ arena.stop_noting_text_rows_for_first_paint();
+ });
+}
+
/// The content size of the committed box of the row the element with `style_node` is bound to, or none where the
/// element has no row or its row no committed box. It makes no layout node, so a host callback a layout round makes
/// on the render owner may ask it.
diff --git a/Libraries/LibWeb/Rust/src/render_state.rs b/Libraries/LibWeb/Rust/src/render_state.rs
index 367cc05d962..b4332134e19 100644
--- a/Libraries/LibWeb/Rust/src/render_state.rs
+++ b/Libraries/LibWeb/Rust/src/render_state.rs
@@ -77,6 +77,9 @@ impl RenderState {
arena
.arena_mut()
.share_first_letter_styles_derived(shared.first_letter_styles_derived);
+ arena
+ .arena_mut()
+ .share_text_rows_noted_for_first_paint(shared.text_rows_noted_for_first_paint);
arena.arena_mut().set_style_engine(engine);
Self {
arena,
diff --git a/Libraries/LibWeb/Rust/src/render_state/document_host.rs b/Libraries/LibWeb/Rust/src/render_state/document_host.rs
index 76cafd78523..c792f92c2f3 100644
--- a/Libraries/LibWeb/Rust/src/render_state/document_host.rs
+++ b/Libraries/LibWeb/Rust/src/render_state/document_host.rs
@@ -1121,6 +1121,13 @@ impl DocumentHost {
self.shared.first_letter_styles_derived.load(Ordering::Relaxed)
}
+ /// Whether some text row may wait for paint timing to look at it, where no frame flies whose layout may give a row
+ /// new rendered text.
+ pub(crate) fn text_rows_may_await_first_paint(&self) -> bool {
+ self.layout_waits_for_no_frame().is_none()
+ || self.shared.text_rows_noted_for_first_paint.load(Ordering::Relaxed)
+ }
+
/// Whether some element may have random base values to keep, which only then is worth asking the render state.
pub(crate) fn element_random_base_values_may_exist(&self) -> bool {
self.shared.element_random_base_values_exist.load(Ordering::Relaxed)
diff --git a/Libraries/LibWeb/Rust/src/render_state/owner.rs b/Libraries/LibWeb/Rust/src/render_state/owner.rs
index a3eb00bc77a..aefedb2db03 100644
--- a/Libraries/LibWeb/Rust/src/render_state/owner.rs
+++ b/Libraries/LibWeb/Rust/src/render_state/owner.rs
@@ -46,6 +46,8 @@ pub(crate) struct SharedWithHost {
/// The flag the state's arena raises once any `::first-letter` box takes a style derived from the element
/// containing its letter, and never lowers.
pub(super) first_letter_styles_derived: Arc<AtomicBool>,
+ /// The flag the state's arena raises while any text row waits for paint timing to look at it.
+ pub(super) text_rows_noted_for_first_paint: Arc<AtomicBool>,
/// The flag the state's style engine raises while it keeps any row's container effects for the host.
pub(super) container_effects_held: Arc<AtomicBool>,
/// The versions the state's style engine mints declaration blocks from, which the host mints from as well.
diff --git a/Tests/LibWeb/Text/expected/LargestContentfulPaint/text-shown-after-it-was-inserted.txt b/Tests/LibWeb/Text/expected/LargestContentfulPaint/text-shown-after-it-was-inserted.txt
new file mode 100644
index 00000000000..315ac4af20c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/LargestContentfulPaint/text-shown-after-it-was-inserted.txt
@@ -0,0 +1,3 @@
+Entries before the text is shown: 0
+Entry for the transparent text: true
+Entry for the hidden text: true
diff --git a/Tests/LibWeb/Text/input/LargestContentfulPaint/text-shown-after-it-was-inserted.html b/Tests/LibWeb/Text/input/LargestContentfulPaint/text-shown-after-it-was-inserted.html
new file mode 100644
index 00000000000..e6e205d2e1f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/LargestContentfulPaint/text-shown-after-it-was-inserted.html
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<div id="transparent" style="font-size: 40px; opacity: 0"></div>
+<div id="hidden" style="font-size: 40px; visibility: hidden"></div>
+<script>
+ asyncTest(async done => {
+ const entries = [];
+ const observer = new PerformanceObserver(list => entries.push(...list.getEntries()));
+ observer.observe({ type: "largest-contentful-paint", buffered: true });
+
+ // The text is laid out while it is not paintable, and is painted for the first time once only the style of
+ // its element changed.
+ const transparent = document.getElementById("transparent");
+ const hidden = document.getElementById("hidden");
+ transparent.textContent = "This text is transparent at first";
+ hidden.textContent = "This text is hidden at first, and the largest";
+ await animationFrame();
+ await animationFrame();
+ entries.push(...observer.takeRecords());
+ println(`Entries before the text is shown: ${entries.length}`);
+
+ transparent.style.opacity = "1";
+ await animationFrame();
+ await animationFrame();
+ entries.push(...observer.takeRecords());
+ println(`Entry for the transparent text: ${entries.some(entry => entry.element === transparent)}`);
+
+ hidden.style.visibility = "visible";
+ await animationFrame();
+ await animationFrame();
+ entries.push(...observer.takeRecords());
+ println(`Entry for the hidden text: ${entries.some(entry => entry.element === hidden)}`);
+ done();
+ });
+</script>