Skip to content

Truly independent web browser

LibWeb: Implement Largest Contentful Paint

Andreas Klingad2d8098cd2c
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index bac6eb0f667..80e148e55a7 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -725,6 +725,7 @@ set(SOURCES
Internals/XRTest.cpp
IntersectionObserver/IntersectionObserver.cpp
IntersectionObserver/IntersectionObserverEntry.cpp
+ LargestContentfulPaint/LargestContentfulPaint.cpp
Layout/Box.cpp
Layout/ImageProvider.cpp
Layout/LayoutRustBridge.cpp
diff --git a/Libraries/LibWeb/DOM/CharacterData.cpp b/Libraries/LibWeb/DOM/CharacterData.cpp
index e29929509bc..4572e78e3e9 100644
--- a/Libraries/LibWeb/DOM/CharacterData.cpp
+++ b/Libraries/LibWeb/DOM/CharacterData.cpp
@@ -18,6 +18,7 @@
#include <LibWeb/DOM/Text.h>
#include <LibWeb/Editing/EditingHistory.h>
#include <LibWeb/Editing/SpellingMarkers.h>
+#include <LibWeb/PaintTiming/PaintTiming.h>
#include <LibWeb/Selection/Selection.h>
namespace Web::DOM {
@@ -199,6 +200,10 @@ WebIDL::ExceptionOr<void> CharacterData::replace_data(size_t offset, size_t coun
set_needs_layout_tree_update(true, SetNeedsLayoutTreeUpdateReason::CharacterDataReplaceData);
else if (auto* parent = this->parent())
parent->set_needs_layout_tree_update(true, SetNeedsLayoutTreeUpdateReason::CharacterDataReplaceData);
+
+ // NB: Paint timing stops looking at text that is all white space, which this text no longer is.
+ if (!m_data.is_ascii_whitespace())
+ PaintTiming::text_node_may_be_painted_for_the_first_time(as<Text>(*this));
}
}
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index aa4714a468c..791cde75d85 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -938,6 +938,7 @@ void Document::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
m_style_scope.visit_edges(visitor);
+ m_paint_timing_state.visit_edges(visitor);
m_commit_messages->visit_edges(visitor);
for (auto const& import : m_pending_css_import_rules)
import->visit_edges(visitor);
diff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.h
index 35e7ea56e37..3db85a51779 100644
--- a/Libraries/LibWeb/DOM/Element.h
+++ b/Libraries/LibWeb/DOM/Element.h
@@ -859,6 +859,11 @@ public:
ProximityToTheViewport proximity_to_the_viewport() const;
void determine_proximity_to_the_viewport(Layout::BegunRead const& read);
+
+ // https://w3c.github.io/paint-timing/#set-of-elements-with-rendered-text
+ bool is_in_set_of_elements_with_rendered_text() const { return m_is_in_set_of_elements_with_rendered_text; }
+ void append_to_set_of_elements_with_rendered_text() { m_is_in_set_of_elements_with_rendered_text = true; }
+ void remove_from_set_of_elements_with_rendered_text() { m_is_in_set_of_elements_with_rendered_text = false; }
bool is_relevant_to_the_user();
// https://drafts.csswg.org/css-contain-2/#skips-its-contents
@@ -1103,6 +1108,7 @@ private:
bool m_uses_document_global_custom_element_registry : 1 { false };
bool m_has_name : 1 { false };
mutable bool m_style_attribute_is_dirty : 1 { false };
+ bool m_is_in_set_of_elements_with_rendered_text : 1 { false };
// The child indices the element remembers, or zero for those not counted yet, and the generation of its parent's
// child list they were counted in; zero for none.
diff --git a/Libraries/LibWeb/DOM/EventDispatcher.cpp b/Libraries/LibWeb/DOM/EventDispatcher.cpp
index 2f17dfa95c4..29965db25a3 100644
--- a/Libraries/LibWeb/DOM/EventDispatcher.cpp
+++ b/Libraries/LibWeb/DOM/EventDispatcher.cpp
@@ -225,6 +225,14 @@ bool EventDispatcher::dispatch(GC::Ref<EventTarget> target, Event& event, bool l
// 1. Set event’s dispatch flag.
event.set_dispatched(true);
+ // https://w3c.github.io/largest-contentful-paint/#sec-modifications-DOM
+ // If target's relevant global object is a Window object, event's type is scroll and its isTrusted is true, set
+ // target's relevant global object's has dispatched scroll event to true.
+ if (event.is_trusted() && event.type() == HTML::EventNames::scroll) {
+ if (auto* window = EventTiming::relevant_window_of_event_target(*target))
+ window->set_has_dispatched_scroll_event();
+ }
+
// https://w3c.github.io/event-timing/#sec-modifications-DOM
// OPTIMIZATION: Only trusted events of some types are timed, so nothing else needs to look up the window.
GC::Ptr<EventTiming::PerformanceEventTiming> timing_entry;
diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cpp
index fb6f502a6c5..fa25c83699c 100644
--- a/Libraries/LibWeb/DOM/Node.cpp
+++ b/Libraries/LibWeb/DOM/Node.cpp
@@ -97,6 +97,7 @@
#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>
@@ -2405,6 +2406,10 @@ void Node::set_document(Document& document)
if (element->style_uses_if_css_function() || element->style_uses_custom_function() || element->style_depends_on_viewport_metrics())
document.add_element_with_viewport_dependent_style(*element);
element->on_document_changed(old_document, document);
+
+ // NB: The set of elements with rendered text is the old document's, and the element is not in the new
+ // document's.
+ element->remove_from_set_of_elements_with_rendered_text();
}
}
@@ -2789,6 +2794,9 @@ 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/Forward.h b/Libraries/LibWeb/Forward.h
index 732328c330c..12e5f8ba39e 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -979,6 +979,12 @@ class Notification;
}
+namespace Web::LargestContentfulPaint {
+
+class LargestContentfulPaint;
+
+}
+
namespace Web::PaintTiming {
class PerformancePaintTiming;
diff --git a/Libraries/LibWeb/HTML/HTMLImageElement.cpp b/Libraries/LibWeb/HTML/HTMLImageElement.cpp
index 319774e13fd..15236280001 100644
--- a/Libraries/LibWeb/HTML/HTMLImageElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLImageElement.cpp
@@ -51,6 +51,7 @@
#include <LibWeb/Layout/RenderDocument.h>
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/Namespace.h>
+#include <LibWeb/PaintTiming/PaintTiming.h>
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/Painting/PaintFacts.h>
#include <LibWeb/Platform/EventLoopPlugin.h>
@@ -967,8 +968,10 @@ void HTMLImageElement::update_the_image_data_impl(bool restart_animations, bool
m_current_request->set_current_url(document(), *url_string);
// 3. If maybe omit events is not set or previousURL is not equal to urlString, then fire an event named load at the img element.
- if (!maybe_omit_events || previous_url != *url_string)
+ if (!maybe_omit_events || previous_url != *url_string) {
+ associated_image_request_became_completely_available(*m_current_request);
dispatch_event(DOM::Event::create(HTML::relevant_global_object(*this), HTML::EventNames::load));
+ }
});
// 8. Abort the update the image data algorithm.
@@ -1127,8 +1130,10 @@ after_step_7:
if (restart_animations)
restart_the_animation();
m_current_request->set_current_url(document(), *url_string);
- if (!maybe_omit_events || previous_url != *url_string)
+ if (!maybe_omit_events || previous_url != *url_string) {
+ associated_image_request_became_completely_available(*m_current_request);
dispatch_event(DOM::Event::create(HTML::relevant_global_object(*this), HTML::EventNames::load));
+ }
});
return;
}
@@ -1299,8 +1304,10 @@ void HTMLImageElement::add_callbacks_to_image_request(GC::Ref<ImageRequest> imag
set_needs_layout_update_or_repaint_after_image_data_change();
// 4. If maybe omit events is not set or previousURL is not equal to urlString, then fire an event named load at the img element.
- if (!maybe_omit_events || previous_url != url_string)
+ if (!maybe_omit_events || previous_url != url_string) {
+ associated_image_request_became_completely_available(*image_request);
dispatch_event(create_event_for_element(*this, HTML::EventNames::load));
+ }
m_load_event_delayer.clear();
}));
@@ -1459,6 +1466,7 @@ void HTMLImageElement::react_to_changes_in_the_environment()
set_needs_layout_update_or_repaint_after_image_data_change();
// 7. Fire an event named load at the img element.
+ associated_image_request_became_completely_available(*image_request);
dispatch_event(create_event_for_element(*this, HTML::EventNames::load));
});
};
@@ -1832,4 +1840,12 @@ Optional<CSSPixelFraction> HTMLImageElement::intrinsic_aspect_ratio() const
return {};
}
+// https://w3c.github.io/paint-timing/#sec-modifications-dom
+void HTMLImageElement::associated_image_request_became_completely_available(ImageRequest const& image_request)
+{
+ // When an Element element's associated image request has become completely available, run the algorithm to process
+ // an image that finished loading passing in element and its associated image request as inputs.
+ PaintTiming::process_an_image_that_finished_loading(*this, PaintTiming::image_request_info(image_request.current_url(), image_request.image_data()));
+}
+
}
diff --git a/Libraries/LibWeb/HTML/HTMLImageElement.h b/Libraries/LibWeb/HTML/HTMLImageElement.h
index 5ff270d0038..ecefb4764af 100644
--- a/Libraries/LibWeb/HTML/HTMLImageElement.h
+++ b/Libraries/LibWeb/HTML/HTMLImageElement.h
@@ -126,6 +126,8 @@ public:
virtual void visit_edges(Cell::Visitor&) override;
private:
+ void associated_image_request_became_completely_available(ImageRequest const&);
+
CSSPixelSize density_corrected_natural_width_and_height() const;
struct Dimensions {
double width { 0 };
diff --git a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
index bdf7e84fe93..f3f025644b6 100644
--- a/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
+++ b/Libraries/LibWeb/HTML/HTMLVideoElement.cpp
@@ -36,6 +36,7 @@
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Layout/Box.h>
#include <LibWeb/Page/Page.h>
+#include <LibWeb/PaintTiming/PaintTiming.h>
#include <LibWeb/Painting/PaintFacts.h>
#include <LibWeb/PictureInPicture/PictureInPictureController.h>
#include <LibWeb/PictureInPicture/PictureInPictureWindow.h>
@@ -299,7 +300,7 @@ WebIDL::ExceptionOr<void> HTMLVideoElement::determine_element_poster_frame(Optio
m_load_event_delayer.emplace(document());
// 7. If an image is thus obtained, the poster frame is that image. Otherwise, there is no poster frame.
- fetch_algorithms_input.process_response = [weak_self = GC::Weak(*this)](auto response) {
+ fetch_algorithms_input.process_response = [weak_self = GC::Weak(*this), poster_url = request->url()](auto response) {
if (!weak_self)
return;
auto& self = *weak_self;
@@ -321,19 +322,29 @@ WebIDL::ExceptionOr<void> HTMLVideoElement::determine_element_poster_frame(Optio
return;
}
- auto on_image_data_read = GC::create_function(GC::Heap::the(), [weak_self](ByteBuffer image_data) {
+ auto on_image_data_read = GC::create_function(GC::Heap::the(), [weak_self, poster_url](ByteBuffer image_data) {
if (!weak_self)
return;
// 6. If an image is thus obtained, the poster frame is that image. Otherwise, there is no poster frame.
(void)Platform::ImageCodecPlugin::the().decode_image(
image_data,
- [weak_self](Web::Platform::DecodedImage& image) -> ErrorOr<void> {
+ [weak_self, poster_url](Web::Platform::DecodedImage& image) -> ErrorOr<void> {
if (!weak_self)
return {};
RefPtr<Gfx::Bitmap> poster_frame;
if (!image.frames.is_empty())
poster_frame = move(image.frames[0].bitmap);
+ Optional<CSSPixelSize> natural_size;
+ if (poster_frame)
+ natural_size = CSSPixelSize { poster_frame->width(), poster_frame->height() };
finalize(*weak_self, move(poster_frame));
+
+ // https://w3c.github.io/paint-timing/#sec-modifications-dom
+ // When an Element element's associated image request has become completely available, run the
+ // algorithm to process an image that finished loading passing in element and its associated image
+ // request as inputs.
+ if (natural_size.has_value())
+ PaintTiming::process_an_image_that_finished_loading(*weak_self, { .url = Utf16String::from_utf8(poster_url.serialize()), .natural_size = natural_size });
return {};
},
[weak_self](auto&) {
diff --git a/Libraries/LibWeb/HTML/Window.h b/Libraries/LibWeb/HTML/Window.h
index f29edbba83e..47831843e7d 100644
--- a/Libraries/LibWeb/HTML/Window.h
+++ b/Libraries/LibWeb/HTML/Window.h
@@ -318,6 +318,10 @@ public:
EventTiming::WindowEventTimingState& event_timing_state() { return m_event_timing_state; }
+ // https://w3c.github.io/largest-contentful-paint/#has-dispatched-scroll-event
+ bool has_dispatched_scroll_event() const { return m_has_dispatched_scroll_event; }
+ void set_has_dispatched_scroll_event() { m_has_dispatched_scroll_event = true; }
+
private:
Window();
@@ -406,6 +410,10 @@ private:
GC::Ptr<External> m_external;
EventTiming::WindowEventTimingState m_event_timing_state;
+
+ // https://w3c.github.io/largest-contentful-paint/#has-dispatched-scroll-event
+ // Each Window has has dispatched scroll event, a boolean which is initially set to false.
+ bool m_has_dispatched_scroll_event { false };
};
void run_animation_frame_callbacks(DOM::Document&, double now);
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
index 4210f1e5375..5ff3e5ae07e 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
@@ -64,6 +64,7 @@
#include <LibWeb/IndexedDB/IDBFactory.h>
#include <LibWeb/IndexedDB/Internal/Algorithms.h>
#include <LibWeb/Infra/SerializedURL.h>
+#include <LibWeb/LargestContentfulPaint/LargestContentfulPaint.h>
#include <LibWeb/Loader/ResourceLoader.h>
#include <LibWeb/NavigationTiming/PerformanceNavigationTiming.h>
#include <LibWeb/Page/Page.h>
diff --git a/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h b/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h
index b4defcd8105..cdabf8492a6 100644
--- a/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h
+++ b/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h
@@ -20,13 +20,14 @@ inline bool is_supported_for_global(SupportedPerformanceEntryTypeGlobals globals
}
// Please keep these in alphabetical order based on the entry type :^)
-#define ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::event, EventTiming::EventEntryTypeRegistry, WindowOnly) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::first_input, EventTiming::FirstInputEntryTypeRegistry, WindowOnly) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::mark, UserTiming::PerformanceMark, WindowAndWorker) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::measure, UserTiming::PerformanceMeasure, WindowAndWorker) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::navigation, NavigationTiming::PerformanceNavigationTiming, WindowOnly) \
- __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::paint, PaintTiming::PerformancePaintTiming, WindowOnly) \
+#define ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES \
+ __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::event, EventTiming::EventEntryTypeRegistry, WindowOnly) \
+ __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::first_input, EventTiming::FirstInputEntryTypeRegistry, WindowOnly) \
+ __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::largest_contentful_paint, LargestContentfulPaint::LargestContentfulPaint, WindowOnly) \
+ __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::mark, UserTiming::PerformanceMark, WindowAndWorker) \
+ __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::measure, UserTiming::PerformanceMeasure, WindowAndWorker) \
+ __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::navigation, NavigationTiming::PerformanceNavigationTiming, WindowOnly) \
+ __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::paint, PaintTiming::PerformancePaintTiming, WindowOnly) \
__ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::resource, ResourceTiming::PerformanceResourceTiming, WindowAndWorker)
}
diff --git a/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.cpp b/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.cpp
new file mode 100644
index 00000000000..2da631b7164
--- /dev/null
+++ b/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.cpp
@@ -0,0 +1,384 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/DOM/Document.h>
+#include <LibWeb/DOM/Element.h>
+#include <LibWeb/DOM/Text.h>
+#include <LibWeb/HTML/LocalNavigable.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/Window.h>
+#include <LibWeb/LargestContentfulPaint/LargestContentfulPaint.h>
+#include <LibWeb/Layout/Node.h>
+#include <LibWeb/PaintTiming/PaintTiming.h>
+#include <LibWeb/Painting/BoxModelMetrics.h>
+#include <LibWeb/Painting/BoxViews.h>
+#include <LibWeb/PerformanceTimeline/EntryTypes.h>
+
+namespace Web::LargestContentfulPaint {
+
+GC_DEFINE_ALLOCATOR(LargestContentfulPaint);
+
+GC::Ref<LargestContentfulPaint> LargestContentfulPaint::create(PaintTiming::PaintTimingInfo paint_timing_info, WebIDL::UnsignedLong size, Utf16String url, Utf16String id, HighResolutionTime::DOMHighResTimeStamp load_time, GC::Ref<DOM::Element> element)
+{
+ return GC::Heap::the().allocate<LargestContentfulPaint>(paint_timing_info, size, move(url), move(id), load_time, element);
+}
+
+// https://w3c.github.io/largest-contentful-paint/#sec-largest-contentful-paint-interface
+LargestContentfulPaint::LargestContentfulPaint(PaintTiming::PaintTimingInfo paint_timing_info, WebIDL::UnsignedLong size, Utf16String url, Utf16String id, HighResolutionTime::DOMHighResTimeStamp load_time, GC::Ref<DOM::Element> element)
+ // The name attribute's getter must return the empty string.
+ // The startTime attribute's getter must return the value of this's renderTime.
+ // The duration attribute's getter must return 0.
+ : PerformanceTimeline::PerformanceEntry(Utf16String {}, PaintTiming::default_paint_timestamp(paint_timing_info), 0)
+ , PaintTiming::PaintTimingMixin(paint_timing_info)
+ , m_size(size)
+ , m_load_time(load_time)
+ , m_id(move(id))
+ , m_url(move(url))
+ , m_element(element)
+{
+}
+
+LargestContentfulPaint::~LargestContentfulPaint() = default;
+
+Utf16FlyString const& LargestContentfulPaint::entry_type() const
+{
+ // The entryType attribute's getter must return the DOMString "largest-contentful-paint".
+ return PerformanceTimeline::EntryTypes::largest_contentful_paint;
+}
+
+// https://w3c.github.io/largest-contentful-paint/#dom-largestcontentfulpaint-rendertime
+HighResolutionTime::DOMHighResTimeStamp LargestContentfulPaint::render_time() const
+{
+ // The renderTime attribute must return the default paint timestamp given this's paint timing info.
+ return PaintTiming::default_paint_timestamp(paint_timing_info());
+}
+
+// https://w3c.github.io/largest-contentful-paint/#dom-largestcontentfulpaint-element
+GC::Ptr<DOM::Element> LargestContentfulPaint::element() const
+{
+ // 1. If this's element is not exposed for paint timing given null, return null.
+ if (!m_element || !PaintTiming::is_exposed_for_paint_timing(*m_element, nullptr))
+ return nullptr;
+
+ // 2. Return this's element.
+ return m_element;
+}
+
+void LargestContentfulPaint::visit_edges(GC::Cell::Visitor& visitor)
+{
+ Base::visit_edges(visitor);
+ visitor.visit(m_element);
+}
+
+// https://w3c.github.io/largest-contentful-paint/#effective-visual-size-result
+struct EffectiveVisualSizeResult {
+ double size { 0 };
+ double width { 0 };
+ double height { 0 };
+};
+
+static CSSPixelRect content_box_of(DOM::Element const& element, CSSPixelRect border_box)
+{
+ Layout::ForcedReadScope read { element.document() };
+ auto const* layout_node = element.layout_node(read);
+ if (!layout_node || !Painting::has_committed_box(*layout_node))
+ return border_box;
+ auto box_model = Painting::box_model(*layout_node);
+ auto left = box_model.border.left + box_model.padding.left;
+ auto top = box_model.border.top + box_model.padding.top;
+ auto right = box_model.border.right + box_model.padding.right;
+ auto bottom = box_model.border.bottom + box_model.padding.bottom;
+ return CSSPixelRect {
+ border_box.x() + left,
+ border_box.y() + top,
+ max(CSSPixels(0), border_box.width() - left - right),
+ max(CSSPixels(0), border_box.height() - top - bottom),
+ };
+}
+
+// https://w3c.github.io/largest-contentful-paint/#effective-visual-size
+static Optional<EffectiveVisualSizeResult> effective_visual_size(CSSPixelRect const& intersection_rect, Optional<PaintTiming::ImageRequestInfo> const& image_request, DOM::Element const& element, DOM::Document const& document, CSSPixelRect const& bounding_client_rect)
+{
+ // 1. Let width be intersectionRect's width, rounded up to the nearest integer.
+ auto width = ceil(intersection_rect.width().to_double());
+
+ // 2. Let height be intersectionRect's height, rounded up to the nearest integer.
+ auto height = ceil(intersection_rect.height().to_double());
+
+ // 3. Let size be width * height.
+ auto size = width * height;
+
+ // 4. Let root be document's browsing context's top-level browsing context's active document.
+ // NB: The top-level browsing context may be in another process, so this uses the active document of the local
+ // root of document's navigable.
+ auto navigable = document.navigable();
+ if (!navigable)
+ return {};
+ auto root = navigable->local_root()->active_document();
+ if (!root || !root->navigable())
+ return {};
+
+ // 5. Let rootWidth be root's visual viewport's width, excluding any scrollbars.
+ // 6. Let rootHeight be root's visual viewport's height, excluding any scrollbars.
+ auto root_size = root->navigable()->viewport_rect().size();
+ auto root_width = root_size.width().to_double();
+ auto root_height = root_size.height().to_double();
+
+ // 7. If size is equal to rootWidth times rootHeight, return null.
+ if (size == root_width * root_height)
+ return {};
+
+ // 8. If imageRequest is not null, run the following steps to adjust for image position and upscaling:
+ if (image_request.has_value()) {
+ // FIXME: 1. If imageRequest's response's content length in bytes is less than size * 0.004, then return null.
+
+ // 2. Let concreteDimensions be imageRequest's concrete object size within element.
+ // 3. Let visibleDimensions be concreteDimensions, adjusted for positioning by object-position or
+ // background-position and element's content box.
+ // 4. Let clientContentRect be the smallest DOMRectReadOnly containing visibleDimensions with element's
+ // transforms applied.
+ // FIXME: Find the concrete object size and position of the image within the element. This takes the whole
+ // content box of the element instead.
+ auto client_content_rect = content_box_of(element, bounding_client_rect);
+
+ // 5. Let intersectingClientContentRect be the intersection of clientContentRect with intersectionRect.
+ auto intersecting_client_content_rect = client_content_rect.intersected(intersection_rect);
+
+ // 6. Set width to intersectingClientContentRect's width, rounded up to the nearest integer.
+ width = ceil(intersecting_client_content_rect.width().to_double());
+
+ // 7. Set height to intersectingClientContentRect's height, rounded up to the nearest integer.
+ height = ceil(intersecting_client_content_rect.height().to_double());
+
+ // 8. Set size to width * height.
+ size = width * height;
+
+ // 9. Let naturalArea be imageRequest's natural width * imageRequest's natural height.
+ double natural_area = 0;
+ if (auto const& natural_size = image_request->natural_size; natural_size.has_value())
+ natural_area = natural_size->width().to_double() * natural_size->height().to_double();
+
+ // 10. If naturalArea is 0, then return null.
+ if (natural_area == 0)
+ return {};
+
+ // 11. Let boundingClientArea be clientContentRect's width * clientContentRect's height.
+ auto bounding_client_area = client_content_rect.width().to_double() * client_content_rect.height().to_double();
+
+ // 12. Let scaleFactor be boundingClientArea / naturalArea.
+ auto scale_factor = bounding_client_area / natural_area;
+
+ // 13. If scaleFactor is greater than 1, then divide size by scaleFactor.
+ if (scale_factor > 1)
+ size /= scale_factor;
+ }
+
+ // 9. Return an effective visual size result with size set to size, width set to width, and height set to height.
+ return EffectiveVisualSizeResult { .size = size, .width = width, .height = height };
+}
+
+// https://w3c.github.io/largest-contentful-paint/#compute-a-new-largest-contentful-paint-candidate
+static Optional<PaintTiming::LargestContentfulPaintCandidate> compute_a_new_largest_contentful_paint_candidate(DOM::Document& document, Vector<PaintTiming::PendingImageRecord> const& painted_images, PaintTiming::PaintedTextNodes const& painted_text_nodes, Optional<PaintTiming::LargestContentfulPaintCandidate> const& current_candidate)
+{
+ // 1. Let currentSize be currentCandidate's size if currentCandidate is not null or 0 otherwise.
+ auto current_size = current_candidate.has_value() ? current_candidate->size : 0;
+
+ // 2. Let largestSize be currentSize.
+ auto largest_size = current_size;
+
+ // 3. Let newCandidate be null.
+ Optional<PaintTiming::LargestContentfulPaintCandidate> new_candidate;
+
+ auto navigable = document.navigable();
+ if (!navigable)
+ return {};
+ CSSPixelRect viewport_rect { {}, navigable->viewport_rect().size() };
+
+ // 4. For each record of paintedImages:
+ for (auto const& record : painted_images) {
+ // 1. Let imageElement be record's element.
+ auto image_element = record.element;
+
+ // 2. If imageElement is not exposed for paint timing, given document, continue.
+ if (!PaintTiming::is_exposed_for_paint_timing(*image_element, document))
+ continue;
+
+ // 3. Let intersectionRect be the value returned by the intersection rect algorithm using imageElement as the
+ // target and viewport as the root.
+ auto bounding_client_rect = image_element->bounding_client_rect_assuming_layout_clean();
+ auto intersection_rect = bounding_client_rect.intersected(viewport_rect);
+
+ // 4. Let result be the effective visual size of imageElement given intersectionRect and record's request.
+ auto result = effective_visual_size(intersection_rect, record.request, *image_element, document, bounding_client_rect);
+
+ // 5. If result is null, continue.
+ if (!result.has_value())
+ continue;
+
+ // 6. If result's size is less than or equal to largestSize, continue.
+ if (result->size <= largest_size)
+ continue;
+
+ // 7. Set largestSize to result's size.
+ largest_size = result->size;
+
+ // 8. Set newCandidate to be a new largest contentful paint candidate with the following values:
+ new_candidate = PaintTiming::LargestContentfulPaintCandidate {
+ // 1. element set to imageElement.
+ .element = image_element,
+ // 2. size set to result's size.
+ .size = result->size,
+ // 3. width set to result's width.
+ .width = result->width,
+ // 4. height set to result's height.
+ .height = result->height,
+ // 5. request set to record's request.
+ .request = record.request,
+ // 6. loadTime set to record's loadTime.
+ .load_time = record.load_time,
+ };
+ }
+
+ // 5. For each textNode of paintedTextNodes,
+ Layout::ForcedReadScope read { document };
+ auto rect_to_viewport_transform = Painting::rect_to_viewport_transform(document, document.visual_context_tree());
+ for (auto const& [text_node, owned_text_nodes] : painted_text_nodes) {
+ // 1. If textNode is not exposed for paint timing, given document, continue.
+ if (!PaintTiming::is_exposed_for_paint_timing(*text_node, document))
+ continue;
+
+ // 2. If textNode has alpha channel value <=0 or opacity value <=0:
+ auto const* layout_node = text_node->layout_node(read);
+ if (!layout_node)
+ continue;
+ if (layout_node->color().alpha() == 0 || layout_node->opacity() <= 0) {
+ // 1. If textNode's text-shadow value is none, textNode's stroke-color value is transparent and textNode's
+ // stroke-image value is none, continue.
+ // FIXME: Check stroke-color and stroke-image once we support text strokes.
+ if (layout_node->text_shadow().is_empty())
+ continue;
+ }
+
+ // 3. Let intersectionRect be the union of the border boxes of all Text nodes in textNode's set of owned text
+ // nodes, intersected with the visual viewport.
+ CSSPixelRect text_rect;
+ for (auto const& text : owned_text_nodes) {
+ auto const* text_layout_node = text->layout_node(read);
+ if (!text_layout_node)
+ continue;
+ auto rect = PaintTiming::client_rect_of_box(*text_layout_node, rect_to_viewport_transform);
+ if (rect.is_empty())
+ continue;
+ text_rect = text_rect.is_empty() ? rect : text_rect.united(rect);
+ }
+ auto intersection_rect = text_rect.intersected(viewport_rect);
+
+ // 4. Let result be the effective visual size of textNode given intersectionRect and null.
+ auto result = effective_visual_size(intersection_rect, {}, *text_node, document, {});
+
+ // 5. If result is null, continue.
+ if (!result.has_value())
+ continue;
+
+ // 6. If result's size is less than or equal to largestSize, continue.
+ if (result->size <= largest_size)
+ continue;
+
+ // 7. Set largestSize to result's size.
+ largest_size = result->size;
+
+ // 8. Set newCandidate to be a new largest contentful paint candidate with the following values:
+ new_candidate = PaintTiming::LargestContentfulPaintCandidate {
+ // 1. element set to textNode.
+ .element = text_node,
+ // 2. size set to result's size.
+ .size = result->size,
+ // 3. width set to result's width.
+ .width = result->width,
+ // 4. height set to result's height.
+ .height = result->height,
+ // 5. request set to null.
+ .request = {},
+ // 6. loadTime set to 0.
+ .load_time = 0,
+ };
+ }
+
+ // 6. If newCandidate is not null and currentSize is greater than 0:
+ if (new_candidate.has_value() && current_size > 0) {
+ // 1. If newCandidate's width minus currentCandidate's width is less than or equal to 3, and newCandidate's
+ // height minus currentCandidate's height is less than or equal to 3, return null.
+ if (new_candidate->width - current_candidate->width <= 3 && new_candidate->height - current_candidate->height <= 3)
+ return {};
+ }
+
+ // 7. Return newCandidate.
+ return new_candidate;
+}
+
+// https://w3c.github.io/largest-contentful-paint/#create-a-largestcontentfulpaint-entry
+static GC::Ref<LargestContentfulPaint> create_a_largest_contentful_paint_entry(PaintTiming::LargestContentfulPaintCandidate const& candidate, PaintTiming::PaintTimingInfo const& paint_timing_info)
+{
+ // 1. Let url be the empty string.
+ Utf16String url;
+
+ // 2. If candidate's request is not null, set url to be candidate's request's request URL.
+ if (candidate.request.has_value())
+ url = candidate.request->url;
+
+ // 3. Let entry be a new LargestContentfulPaint entry with document's relevant realm, whose paint timing info is
+ // paintTimingInfo, with its
+ // - size set to candidate's size,
+ // - url set to url,
+ // - id set to candidate's element's element id,
+ // - loadTime set to candidate's loadTime,
+ // - and element set to candidate's element.
+ Utf16String id;
+ if (auto const& element_id = candidate.element->id(); element_id.has_value())
+ id = element_id->to_utf16_string();
+ auto size = static_cast<WebIDL::UnsignedLong>(clamp(candidate.size, 0.0, static_cast<double>(NumericLimits<WebIDL::UnsignedLong>::max())));
+
+ // 4. Return entry.
+ return LargestContentfulPaint::create(paint_timing_info, size, move(url), move(id), candidate.load_time, candidate.element);
+}
+
+// https://w3c.github.io/largest-contentful-paint/#report-largest-contentful-paint
+void report_largest_contentful_paint(DOM::Document& document, PaintTiming::PaintTimingInfo const& paint_timing_info, Vector<PaintTiming::PendingImageRecord> const& painted_images, PaintTiming::PaintedTextNodes const& painted_text_nodes)
+{
+ // NOTE: Each pending image record in paintedImages and text element in paintedTextNodes will only be reported
+ // exactly once, from mark paint timing, for the first paint where the element is considered paintable (i.e.
+ // has opacity and visibility) and contentful (i.e. image resource or blocking fonts are sufficiently loaded).
+
+ // 1. Let window be document’s relevant global object.
+ auto& window = HTML::relevant_window(document);
+
+ // 2. If either of window's has dispatched scroll event or has dispatched input event is true, return.
+ if (window.has_dispatched_scroll_event() || window.event_timing_state().has_dispatched_input_event)
+ return;
+
+ // 3. Let newCandidate be the result of computing a new largest contentful paint candidate given document,
+ // paintedImages, paintedTextNodes, and document's current largest contentful paint candidate.
+ auto& state = document.paint_timing_state();
+ auto new_candidate = compute_a_new_largest_contentful_paint_candidate(document, painted_images, painted_text_nodes, state.current_largest_contentful_paint_candidate);
+
+ // 4. If newCandidate is null, return.
+ if (!new_candidate.has_value())
+ return;
+
+ // 5. Set document's current largest contentful paint candidate to newCandidate.
+ state.current_largest_contentful_paint_candidate = new_candidate;
+
+ // 6. Let entry be the result of creating a LargestContentfulPaint entry with newCandidate, paintTimingInfo, and
+ // document.
+ auto entry = create_a_largest_contentful_paint_entry(*new_candidate, paint_timing_info);
+
+ // 7. Queue the PerformanceEntry entry.
+ window.queue_performance_entry(entry);
+ window.add_performance_entry(entry, HTML::WindowOrWorkerGlobalScopeMixin::CheckIfPerformanceBufferIsFull::Yes);
+}
+
+}
diff --git a/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.h b/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.h
new file mode 100644
index 00000000000..395d4b79487
--- /dev/null
+++ b/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Forward.h>
+#include <LibWeb/PaintTiming/DocumentPaintTimingState.h>
+#include <LibWeb/PaintTiming/PaintTimingMixin.h>
+#include <LibWeb/PerformanceTimeline/PerformanceEntry.h>
+#include <LibWebCommon/WebIDL/Types.h>
+
+namespace Web::LargestContentfulPaint {
+
+// https://w3c.github.io/largest-contentful-paint/#sec-largest-contentful-paint-interface
+class LargestContentfulPaint final
+ : public PerformanceTimeline::PerformanceEntry
+ , public PaintTiming::PaintTimingMixin {
+ WEB_WRAPPABLE(LargestContentfulPaint, PerformanceTimeline::PerformanceEntry);
+ GC_DECLARE_ALLOCATOR(LargestContentfulPaint);
+
+public:
+ static GC::Ref<LargestContentfulPaint> create(PaintTiming::PaintTimingInfo, WebIDL::UnsignedLong size, Utf16String url, Utf16String id, HighResolutionTime::DOMHighResTimeStamp load_time, GC::Ref<DOM::Element>);
+
+ virtual ~LargestContentfulPaint() override;
+
+ // NOTE: These three functions are answered by the registry for the given entry type.
+ // https://w3c.github.io/timing-entrytypes-registry/#registry
+
+ // https://w3c.github.io/timing-entrytypes-registry/#dfn-availablefromtimeline
+ static PerformanceTimeline::AvailableFromTimeline available_from_timeline() { return PerformanceTimeline::AvailableFromTimeline::No; }
+
+ // https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
+ static Optional<u64> max_buffer_size() { return 150; }
+
+ // https://w3c.github.io/timing-entrytypes-registry/#dfn-should-add-entry
+ virtual PerformanceTimeline::ShouldAddEntry should_add_entry(Optional<PerformanceTimeline::PerformanceObserverInit const&> = {}) const override { return PerformanceTimeline::ShouldAddEntry::Yes; }
+
+ virtual Utf16FlyString const& entry_type() const override;
+
+ HighResolutionTime::DOMHighResTimeStamp load_time() const { return m_load_time; }
+ HighResolutionTime::DOMHighResTimeStamp render_time() const;
+ WebIDL::UnsignedLong size() const { return m_size; }
+ Utf16String const& id() const { return m_id; }
+ Utf16String const& url() const { return m_url; }
+ GC::Ptr<DOM::Element> element() const;
+
+private:
+ LargestContentfulPaint(PaintTiming::PaintTimingInfo, WebIDL::UnsignedLong size, Utf16String url, Utf16String id, HighResolutionTime::DOMHighResTimeStamp load_time, GC::Ref<DOM::Element>);
+
+ virtual void visit_edges(GC::Cell::Visitor&) override;
+
+ // https://w3c.github.io/largest-contentful-paint/#largestcontentfulpaint-size
+ WebIDL::UnsignedLong m_size { 0 };
+
+ // https://w3c.github.io/largest-contentful-paint/#largestcontentfulpaint-loadtime
+ HighResolutionTime::DOMHighResTimeStamp m_load_time { 0 };
+
+ // https://w3c.github.io/largest-contentful-paint/#largestcontentfulpaint-id
+ Utf16String m_id;
+
+ // https://w3c.github.io/largest-contentful-paint/#largestcontentfulpaint-url
+ Utf16String m_url;
+
+ // https://w3c.github.io/largest-contentful-paint/#largestcontentfulpaint-element
+ GC::Ptr<DOM::Element> m_element;
+};
+
+// https://w3c.github.io/largest-contentful-paint/#report-largest-contentful-paint
+void report_largest_contentful_paint(DOM::Document&, PaintTiming::PaintTimingInfo const&, Vector<PaintTiming::PendingImageRecord> const& painted_images, PaintTiming::PaintedTextNodes const& painted_text_nodes);
+
+}
diff --git a/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.idl b/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.idl
new file mode 100644
index 00000000000..d4bf895f381
--- /dev/null
+++ b/Libraries/LibWeb/LargestContentfulPaint/LargestContentfulPaint.idl
@@ -0,0 +1,13 @@
+// https://w3c.github.io/largest-contentful-paint/#sec-largest-contentful-paint-interface
+[Exposed=Window]
+interface LargestContentfulPaint : PerformanceEntry {
+ readonly attribute DOMHighResTimeStamp loadTime;
+ readonly attribute DOMHighResTimeStamp renderTime;
+ readonly attribute unsigned long size;
+ readonly attribute DOMString id;
+ readonly attribute DOMString url;
+ readonly attribute Element? element;
+ [Default] object toJSON();
+};
+
+LargestContentfulPaint includes PaintTimingMixin;
diff --git a/Libraries/LibWeb/Layout/Node.cpp b/Libraries/LibWeb/Layout/Node.cpp
index 0e5ebcb5fbd..4d0776128a0 100644
--- a/Libraries/LibWeb/Layout/Node.cpp
+++ b/Libraries/LibWeb/Layout/Node.cpp
@@ -28,6 +28,7 @@
#include <LibWeb/Layout/TextNode.h>
#include <LibWeb/Layout/Viewport.h>
#include <LibWeb/Page/Page.h>
+#include <LibWeb/PaintTiming/PaintTiming.h>
#include <LibWeb/Painting/BoxViews.h>
#include <LibWeb/Painting/PaintFacts.h>
#include <LibWeb/Painting/ScrollSnap.h>
@@ -253,6 +254,29 @@ void NodeWithStyle::ImageObserver::image_style_value_did_update(CSS::ImageStyleV
{
VERIFY(m_owner);
Painting::push_layer_image_paint_facts(*m_owner);
+ report_to_paint_timing_if_available();
+}
+
+void NodeWithStyle::ImageObserver::set_observes_background_image_of(DOM::Element& element, bool reported_to_paint_timing)
+{
+ m_background_image_element = element;
+ m_reported_to_paint_timing = reported_to_paint_timing;
+ report_to_paint_timing_if_available();
+}
+
+// https://w3c.github.io/paint-timing/#sec-modifications-CSS
+void NodeWithStyle::ImageObserver::report_to_paint_timing_if_available()
+{
+ // Whenever an image request in an Element element's associated background image requests becomes completely
+ // available, run the algorithm to process an image that finished loading with element and image request as
+ // inputs.
+ if (!m_background_image_element || m_reported_to_paint_timing || !m_resource)
+ return;
+ auto image_data = decoded_image_data();
+ if (!image_data)
+ return;
+ m_reported_to_paint_timing = true;
+ PaintTiming::process_an_image_that_finished_loading(*m_background_image_element, PaintTiming::image_request_info(Utf16String::from_utf8(m_resource->url().serialize()), image_data));
}
NodeWithStyle::~NodeWithStyle()
@@ -278,9 +302,29 @@ void NodeWithStyle::rebuild_image_observers(Vector<RefPtr<CSS::CursorStyleValue
return make<ImageObserver>(*this, *image_to_observe);
};
+ // NB: A background image the old observers told paint timing of is not told of again.
+ auto background_image_was_reported_to_paint_timing = [&](CSS::ImageStyleValue const& image) {
+ auto const* old_observers = image_observers();
+ if (!old_observers)
+ return false;
+ for (auto const& old_observer : old_observers->background_layers) {
+ if (old_observer && &old_observer->image() == &image && old_observer->reported_to_paint_timing())
+ return true;
+ }
+ return false;
+ };
+
+ auto* background_image_element = as_if<DOM::Element>(dom_node());
+ if (!background_image_element && is_generated_for_pseudo_element())
+ background_image_element = pseudo_element_generator().ptr();
+
auto new_observers = make<ImageObserverSlots>();
- for (auto const& image : background_images())
- new_observers->background_layers.append(observer_for(image.ptr()));
+ for (auto const& image : background_images()) {
+ auto observer = observer_for(image.ptr());
+ if (observer && background_image_element)
+ observer->set_observes_background_image_of(*background_image_element, background_image_was_reported_to_paint_timing(observer->image()));
+ new_observers->background_layers.append(move(observer));
+ }
for (auto const& image : mask_images())
new_observers->mask_layers.append(observer_for(image.ptr()));
for (auto const& cursor_style_value : cursor_style_values)
diff --git a/Libraries/LibWeb/Layout/Node.h b/Libraries/LibWeb/Layout/Node.h
index 4d9f53610ac..596f20ed69e 100644
--- a/Libraries/LibWeb/Layout/Node.h
+++ b/Libraries/LibWeb/Layout/Node.h
@@ -17,6 +17,7 @@
#include <AK/kmalloc.h>
#include <LibGC/Cell.h>
#include <LibGC/Root.h>
+#include <LibGC/Weak.h>
#include <LibWeb/CSS/ComputedValues.h>
#include <LibWeb/CSS/StyleEngineIdentifiers.h>
#include <LibWeb/CSS/StyleValues/AbstractImageStyleValue.h>
@@ -327,9 +328,22 @@ public:
virtual void image_style_value_did_update(CSS::ImageStyleValue&) override;
+ CSS::ImageStyleValue const& image() const { return m_image; }
+
+ // https://w3c.github.io/paint-timing/#associated-background-image-requests
+ // NB: The element whose associated background image requests have the image request this observes, and
+ // whether paint timing was told that it became completely available.
+ void set_observes_background_image_of(DOM::Element&, bool reported_to_paint_timing);
+ bool reported_to_paint_timing() const { return m_reported_to_paint_timing; }
+
private:
+ void report_to_paint_timing_if_available();
+
WeakPtr<NodeWithStyle> m_owner;
NonnullRefPtr<CSS::ImageStyleValue const> m_image;
+ // NB: The image may finish decoding beside a frame in flight, which the owner's box can't be read from.
+ GC::Weak<DOM::Element> m_background_image_element;
+ bool m_reported_to_paint_timing { false };
};
// The image resources a node's style asks for, which the layout arena's host tables hold by the
diff --git a/Libraries/LibWeb/PaintTiming/DocumentPaintTimingState.h b/Libraries/LibWeb/PaintTiming/DocumentPaintTimingState.h
index c49d4d29511..7b353354355 100644
--- a/Libraries/LibWeb/PaintTiming/DocumentPaintTimingState.h
+++ b/Libraries/LibWeb/PaintTiming/DocumentPaintTimingState.h
@@ -7,14 +7,88 @@
#pragma once
#include <AK/HashTable.h>
+#include <AK/Optional.h>
#include <AK/Utf16String.h>
+#include <AK/Vector.h>
+#include <LibGC/ConservativeHashMap.h>
+#include <LibGC/ConservativeVector.h>
+#include <LibGC/Ptr.h>
+#include <LibWeb/Forward.h>
+#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>
+#include <LibWebCommon/PixelUnits.h>
namespace Web::PaintTiming {
+// https://html.spec.whatwg.org/multipage/images.html#image-request
+// NB: What paint timing needs to know about an image request.
+struct ImageRequestInfo {
+ Utf16String url;
+
+ // https://html.spec.whatwg.org/multipage/images.html#img-req-data
+ // NB: The natural dimensions of the image data, which an image request has once it is available.
+ Optional<CSSPixelSize> natural_size;
+};
+
+// https://w3c.github.io/paint-timing/#pending-image-record
+struct PendingImageRecord {
+ // element, an Element
+ GC::Ref<DOM::Element> element;
+
+ // request, an image request
+ ImageRequestInfo request;
+
+ // loadTime, a DOMHighResTimeStamp
+ HighResolutionTime::DOMHighResTimeStamp load_time { 0 };
+};
+
+// https://w3c.github.io/largest-contentful-paint/#largest-contentful-paint-candidate
+struct LargestContentfulPaintCandidate {
+ // element, an element
+ GC::Ref<DOM::Element> element;
+
+ // size, a number
+ double size { 0 };
+
+ // width, a number
+ double width { 0 };
+
+ // height, a number
+ double height { 0 };
+
+ // request, a Request or null
+ Optional<ImageRequestInfo> request;
+
+ // loadTime, a number
+ HighResolutionTime::DOMHighResTimeStamp load_time { 0 };
+};
+
+// NB: The elements that get a text node in their set of owned text nodes for the first time as a frame is painted,
+// with those text nodes.
+using PaintedTextNodes = GC::OrderedConservativeHashMap<GC::Ref<DOM::Element>, GC::ConservativeVector<GC::Ref<DOM::Text>>>;
+
struct DocumentPaintTimingState {
// https://w3c.github.io/paint-timing/#set-of-previously-reported-paints
// Each Document has a set of previously reported paints, which is an ordered set of strings, initially empty.
OrderedHashTable<Utf16String> set_of_previously_reported_paints;
+
+ // https://w3c.github.io/paint-timing/#images-pending-rendering
+ // Each Document has an images pending rendering, which is a list of pending image records, initially empty.
+ Vector<PendingImageRecord> images_pending_rendering;
+
+ // https://w3c.github.io/paint-timing/#set-of-elements-with-rendered-text
+ // 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;
+
+ // 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.
+ Optional<LargestContentfulPaintCandidate> current_largest_contentful_paint_candidate;
+
+ void visit_edges(GC::Cell::Visitor&);
};
}
diff --git a/Libraries/LibWeb/PaintTiming/PaintTiming.cpp b/Libraries/LibWeb/PaintTiming/PaintTiming.cpp
index cf1fa1f822d..f038249e56f 100644
--- a/Libraries/LibWeb/PaintTiming/PaintTiming.cpp
+++ b/Libraries/LibWeb/PaintTiming/PaintTiming.cpp
@@ -5,6 +5,7 @@
*/
#include <AK/NeverDestroyed.h>
+#include <LibGC/ConservativeVector.h>
#include <LibWeb/CSS/ComputedValues.h>
#include <LibWeb/CSS/FontComputer.h>
#include <LibWeb/CSS/StyleValues/BackgroundSizeStyleValue.h>
@@ -13,6 +14,8 @@
#include <LibWeb/CSS/StyleValues/StyleValueList.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/DOM/Element.h>
+#include <LibWeb/DOM/Text.h>
+#include <LibWeb/HTML/DecodedImageData.h>
#include <LibWeb/HTML/HTMLCanvasElement.h>
#include <LibWeb/HTML/HTMLInputElement.h>
#include <LibWeb/HTML/HTMLVideoElement.h>
@@ -20,6 +23,7 @@
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWeb/LargestContentfulPaint/LargestContentfulPaint.h>
#include <LibWeb/Layout/Box.h>
#include <LibWeb/Layout/TextNode.h>
#include <LibWeb/Layout/Viewport.h>
@@ -233,7 +237,7 @@ static bool paints_non_default_content(Layout::Node const& node)
return border_is_painted(node_with_style->border_left()) || border_is_painted(node_with_style->border_top()) || border_is_painted(node_with_style->border_right()) || border_is_painted(node_with_style->border_bottom());
}
-static CSSPixelRect client_rect_of_box(Layout::Node const& node, Layout::RustFFI::FfiRectToViewportTransform const& rect_to_viewport_transform)
+CSSPixelRect client_rect_of_box(Layout::Node const& node, Layout::RustFFI::FfiRectToViewportTransform const& rect_to_viewport_transform)
{
if (!node.is_text_node())
return Painting::bounding_client_rect(node, rect_to_viewport_transform);
@@ -276,10 +280,16 @@ public:
m_rect_to_viewport_transform = Painting::rect_to_viewport_transform(document, document.visual_context_tree());
}
+ Layout::BegunRead const& read() const { return m_read; }
Layout::Viewport const* viewport() const { return m_scrolling_area.has_value() ? m_viewport : nullptr; }
+ enum class CheckAncestorOpacity {
+ No,
+ Yes,
+ };
+
// https://w3c.github.io/paint-timing/#paintable
- bool is_paintable(Layout::Node const& node) const
+ bool is_paintable(Layout::Node const& node, CheckAncestorOpacity check_ancestor_opacity) const
{
if (!viewport())
return false;
@@ -296,7 +306,12 @@ public:
return false;
// - el and all of its ancestors' used opacity is greater than zero.
- // NB: The subtrees of boxes with an opacity of zero are not looked at.
+ if (check_ancestor_opacity == CheckAncestorOpacity::Yes) {
+ for (auto const* ancestor = &node; ancestor; ancestor = ancestor->parent_ptr()) {
+ if (auto const* ancestor_with_style = as_if<Layout::NodeWithStyle>(*ancestor); ancestor_with_style && ancestor_with_style->opacity() <= 0)
+ return false;
+ }
+ }
// - el's paintable bounding rect intersects with the scrolling area of the document.
// https://w3c.github.io/paint-timing/#paintable-bounding-rect
@@ -337,10 +352,10 @@ static PaintedContent find_painted_content(PaintableChecker const& checker, Pain
if (auto const* node_with_style = as_if<Layout::NodeWithStyle>(node); node_with_style && node_with_style->opacity() <= 0)
return TraversalDecision::SkipChildrenAndContinue;
- if (!result.has_non_default_content && paints_non_default_content(node) && checker.is_paintable(node))
+ if (!result.has_non_default_content && paints_non_default_content(node) && checker.is_paintable(node, PaintableChecker::CheckAncestorOpacity::No))
result.has_non_default_content = true;
- if (is_contentful(node) && checker.is_paintable(node)) {
+ if (is_contentful(node) && checker.is_paintable(node, PaintableChecker::CheckAncestorOpacity::No)) {
result.has_non_default_content = true;
result.has_contentful_content = true;
return TraversalDecision::Break;
@@ -357,6 +372,67 @@ static PaintedContent find_painted_content(PaintableChecker const& checker, Pain
return result;
}
+// NB: Largest contentful paint is the only user of the images pending rendering and of the text nodes that are
+// painted, and it reports nothing once the window has dispatched a scroll event or an input event.
+// FIXME: Keep tracking these for element timing, once it is implemented.
+static bool tracks_painted_images_and_text(DOM::Document& document)
+{
+ if (!document.browsing_context())
+ return false;
+ auto window = document.window();
+ if (!window)
+ return false;
+ return !window->has_dispatched_scroll_event() && !window->event_timing_state().has_dispatched_input_event;
+}
+
+// https://w3c.github.io/paint-timing/#process-an-image-that-finished-loading
+void process_an_image_that_finished_loading(DOM::Element& element, ImageRequestInfo image_request)
+{
+ // 1. Let root be element's root.
+ // 2. If root is not a Document, return.
+ auto* root = as_if<DOM::Document>(element.root());
+ if (!root)
+ return;
+
+ // OPTIMIZATION: An image that nothing would report once it is painted is not recorded.
+ if (!tracks_painted_images_and_text(*root))
+ return;
+
+ // 3. Let now be the current high resolution time given element's relevant global object.
+ auto now = HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(element));
+
+ // 4. Let record be a pending image record with element element, request imageRequest and loadTime now.
+ // 5. Add record to root's images pending rendering.
+ root->paint_timing_state().images_pending_rendering.append({
+ .element = element,
+ .request = move(image_request),
+ .load_time = now,
+ });
+}
+
+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)
+{
+ for (auto const* box = static_cast<Layout::Node const*>(text_box.containing_block()); box; box = box->parent_ptr()) {
+ if (auto const* element = as_if<DOM::Element>(box->dom_node()))
+ return const_cast<DOM::Element*>(element);
+ if (box->is_generated_for_pseudo_element()) {
+ if (auto generator = box->pseudo_element_generator())
+ return const_cast<DOM::Element*>(generator.ptr());
+ }
+ }
+ return nullptr;
+}
+
// https://w3c.github.io/paint-timing/#mark-paint-timing
void mark_paint_timing(DOM::Document& document)
{
@@ -365,10 +441,19 @@ void mark_paint_timing(DOM::Document& document)
if (!document.browsing_context())
return;
- auto& reported_paints = document.paint_timing_state().set_of_previously_reported_paints;
+ auto& state = document.paint_timing_state();
+ auto& reported_paints = state.set_of_previously_reported_paints;
- // OPTIMIZATION: Nothing below reports anything once first paint and first contentful paint have been reported.
- if (reported_paints.contains(first_paint_name()) && reported_paints.contains(first_contentful_paint_name()))
+ // OPTIMIZATION: Nothing reports the images and text nodes that are painted from now on.
+ if (!tracks_painted_images_and_text(document)) {
+ state.images_pending_rendering.clear();
+ state.text_nodes_pending_first_paint.clear();
+ }
+
+ // 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())
return;
// AD-HOC: Nothing is painted for a document whose initial paint is deferred until its fonts load.
@@ -384,17 +469,84 @@ void mark_paint_timing(DOM::Document& document)
.implementation_defined_presentation_time = {},
};
- // FIXME: 3. Let paintedImages be a new ordered set
- // FIXME: 4. Let paintedTextNodes be a new ordered set
- // FIXME: 5. For each record in doc's images pending rendering list:
- // 1. If record's request is available and ready to be painted, then run the following steps:
- // 1. Append record to paintedImages.
- // 2. Remove record from doc's images pending rendering list.
- // FIXME: 6. For each Element element in doc's descendants:
- // 1. If element is contained in doc's set of elements with rendered text, continue.
- // 2. If element's set of owned text nodes is empty, continue.
- // 3. Append element to doc's set of elements with rendered text.
- // 4. Append element to paintedTextNodes.
+ // 3. Let paintedImages be a new ordered set
+ GC::ConservativeVector<PendingImageRecord> painted_images;
+
+ // 4. Let paintedTextNodes be a new ordered set
+ PaintedTextNodes painted_text_nodes;
+
+ // 5. For each record in doc's images pending rendering list:
+ state.images_pending_rendering.remove_all_matching([&](PendingImageRecord& record) {
+ // AD-HOC: An image whose element left the document is never painted.
+ if (!record.element->is_connected() || &record.element->document() != &document)
+ return true;
+
+ // 1. If record's request is available and ready to be painted, then run the following steps:
+ // NB: The request is available, as the record was made once it was. The image is ready to be painted once its
+ // element is paintable.
+ auto const* layout_node = record.element->layout_node(checker.read());
+ if (!layout_node || !checker.is_paintable(*layout_node, PaintableChecker::CheckAncestorOpacity::Yes))
+ return false;
+
+ // 1. Append record to paintedImages.
+ painted_images.append(record);
+
+ // 2. Remove record from doc's images pending rendering list.
+ return true;
+ });
+
+ // NB: This is when the user agent paints a Text node for the first time.
+ GC::ConservativeVector<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)
+ return true;
+ auto const* text_box = text->layout_node(checker.read());
+ if (!text_box) {
+ // OPTIMIZATION: Text that is all white space paints nothing, and is not looked at again until its data
+ // changes to something else.
+ return !is_non_empty(text->data().utf16_view());
+ }
+ if (!checker.is_paintable(*text_box, PaintableChecker::CheckAncestorOpacity::Yes))
+ return false;
+
+ // https://w3c.github.io/paint-timing/#sec-modifications-dom
+ // When the user agent paints a Text node text for the first time, it should execute the following steps:
+ // 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;
+
+ // - 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);
+ 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.
+ for (auto& it : painted_text_nodes) {
+ auto& element = it.key;
+
+ // 1. If element is contained in doc's set of elements with rendered text, continue.
+ // 2. If element's set of owned text nodes is empty, continue.
+ // NB: Both were checked as the text nodes were appended.
+
+ // 3. Append element to doc's set of elements with rendered text.
+ element->append_to_set_of_elements_with_rendered_text();
+
+ // 4. Append element to paintedTextNodes.
+ // NB: The element is in paintedTextNodes already.
+ }
// 7. Let reportedPaints be the document's set of previously reported paints.
// FIXME: 8. Let frameTimingInfo be document's current frame timing info.
@@ -402,12 +554,15 @@ void mark_paint_timing(DOM::Document& document)
// 10. Let flushPaintTimings be the following steps:
auto flush_paint_timings = [&] {
- // NB: The boxes are looked at once for both first paint and first contentful paint.
+ // NB: The boxes are looked at once for both first paint and first contentful paint, and not at all once both
+ // have been reported.
PaintedContent already_found {
.has_non_default_content = reported_paints.contains(first_paint_name()),
.has_contentful_content = reported_paints.contains(first_contentful_paint_name()),
};
- auto painted_content = find_painted_content(checker, already_found);
+ auto painted_content = already_found.has_non_default_content && already_found.has_contentful_content
+ ? already_found
+ : find_painted_content(checker, already_found);
// 1. If reportedPaints does not contain "first-paint", and the user agent is configured to mark first paint,
// then report paint timing given document, "first-paint", and paintTimingInfo.
@@ -425,8 +580,9 @@ void mark_paint_timing(DOM::Document& document)
report_paint_timing(document, first_contentful_paint_name(), paint_timing_info);
}
- // FIXME: 3. Report largest contentful paint given document, paintTimingInfo, paintedImages and
- // paintedTextNodes.
+ // 3. Report largest contentful paint given document, paintTimingInfo, paintedImages and paintedTextNodes.
+ if (!painted_images.is_empty() || !painted_text_nodes.is_empty())
+ LargestContentfulPaint::report_largest_contentful_paint(document, paint_timing_info, painted_images, painted_text_nodes);
// FIXME: 4. Report element timing given document, paintTimingInfo, paintedImages and paintedTextNodes.
// FIXME: 5. If frameTimingInfo is not null, then queue a long animation frame entry given document,
@@ -439,6 +595,18 @@ void mark_paint_timing(DOM::Document& document)
flush_paint_timings();
}
+ImageRequestInfo image_request_info(Utf16String url, GC::Ptr<HTML::DecodedImageData const> image_data)
+{
+ ImageRequestInfo info { .url = move(url), .natural_size = {} };
+ if (image_data) {
+ auto width = image_data->intrinsic_width();
+ auto height = image_data->intrinsic_height();
+ if (width.has_value() && height.has_value())
+ info.natural_size = CSSPixelSize { *width, *height };
+ }
+ return info;
+}
+
// https://w3c.github.io/paint-timing/#report-paint-timing
void report_paint_timing(DOM::Document& document, Utf16String const& paint_type, PaintTimingInfo const& paint_timing_info)
{
@@ -484,4 +652,13 @@ bool is_exposed_for_paint_timing(DOM::Element const& element, GC::Ptr<DOM::Docum
return true;
}
+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);
+ if (current_largest_contentful_paint_candidate.has_value())
+ visitor.visit(current_largest_contentful_paint_candidate->element);
+}
+
}
diff --git a/Libraries/LibWeb/PaintTiming/PaintTiming.h b/Libraries/LibWeb/PaintTiming/PaintTiming.h
index 807a925a846..a103fb90922 100644
--- a/Libraries/LibWeb/PaintTiming/PaintTiming.h
+++ b/Libraries/LibWeb/PaintTiming/PaintTiming.h
@@ -8,16 +8,30 @@
#include <AK/Utf16String.h>
#include <LibWeb/Forward.h>
+#include <LibWeb/PaintTiming/DocumentPaintTimingState.h>
#include <LibWeb/PaintTiming/PaintTimingMixin.h>
+#include <LibWeb/Painting/BoxViews.h>
namespace Web::PaintTiming {
+// https://w3c.github.io/paint-timing/#process-an-image-that-finished-loading
+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&);
// https://w3c.github.io/paint-timing/#report-paint-timing
void report_paint_timing(DOM::Document&, Utf16String const& paint_type, PaintTimingInfo const&);
+// NB: The client rect of the given box, which for a text box is the union of the rects of its fragments.
+CSSPixelRect client_rect_of_box(Layout::Node const&, Layout::RustFFI::FfiRectToViewportTransform const&);
+
// https://w3c.github.io/paint-timing/#exposed-for-paint-timing
bool is_exposed_for_paint_timing(DOM::Element const&, GC::Ptr<DOM::Document const>);
diff --git a/Libraries/LibWeb/SVG/SVGImageElement.cpp b/Libraries/LibWeb/SVG/SVGImageElement.cpp
index a0c2b5e1000..a5c4696afe7 100644
--- a/Libraries/LibWeb/SVG/SVGImageElement.cpp
+++ b/Libraries/LibWeb/SVG/SVGImageElement.cpp
@@ -19,6 +19,7 @@
#include <LibWeb/HTML/SharedResourceRequest.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
#include <LibWeb/Namespace.h>
+#include <LibWeb/PaintTiming/PaintTiming.h>
#include <LibWeb/Painting/PaintFacts.h>
#include <LibWeb/SVG/SVGDecodedImageData.h>
@@ -114,6 +115,14 @@ void SVGImageElement::fetch_the_document(URL::URL const& url)
Painting::push_replaced_image_paint_facts(*this, *this);
set_needs_layout_update(DOM::SetNeedsLayoutReason::SVGImageElementFetchTheDocument);
+ // https://w3c.github.io/paint-timing/#sec-modifications-dom
+ // When an Element element's associated image request has become completely available, run the algorithm
+ // to process an image that finished loading passing in element and its associated image request as
+ // inputs.
+ // NB: A request that finishes after href has changed is no longer the element's image request.
+ if (m_resource_request.ptr() == resource_request.ptr())
+ PaintTiming::process_an_image_that_finished_loading(*this, PaintTiming::image_request_info(Utf16String::from_utf8(resource_request->url().serialize()), resource_request->image_data()));
+
dispatch_event(DOM::Event::create(HTML::EventNames::load,
HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this))));
},
diff --git a/Libraries/LibWeb/idl_files.cmake b/Libraries/LibWeb/idl_files.cmake
index 49ff77d65cc..c1ac03b7886 100644
--- a/Libraries/LibWeb/idl_files.cmake
+++ b/Libraries/LibWeb/idl_files.cmake
@@ -411,6 +411,7 @@ libweb_js_bindings(Internals/WebUI)
libweb_js_bindings(Internals/XRTest)
libweb_js_bindings(IntersectionObserver/IntersectionObserver)
libweb_js_bindings(IntersectionObserver/IntersectionObserverEntry)
+libweb_js_bindings(LargestContentfulPaint/LargestContentfulPaint)
libweb_js_bindings(MathML/MathMLAnchorElement)
libweb_js_bindings(MathML/MathMLElement)
libweb_js_bindings(MediaCapabilitiesAPI/MediaCapabilities)
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index f94506d7ea0..7bcd6898360 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -851,6 +851,7 @@ Text/input/wpt-import/resource-timing/initiator-type/img-srcset.html
Text/input/wpt-import/resource-timing/initiator-type/picture.html
Text/input/wpt-import/resource-timing/object-not-found-adds-entry.html
Text/input/wpt-import/resource-timing/status-codes-create-entry.html
+Text/input/wpt-import/largest-contentful-paint/element-only-when-fully-active.html
Text/input/wpt-import/webvtt/parsing/file-parsing/tests/ids.html
Text/input/wpt-import/webvtt/parsing/file-parsing/tests/timings-too-short.html
Text/input/wpt-import/webvtt/parsing/file-parsing/tests/whitespace-chars.html
diff --git a/Tests/LibWeb/Text/expected/LargestContentfulPaint/svg-image-href-changed-while-loading.txt b/Tests/LibWeb/Text/expected/LargestContentfulPaint/svg-image-href-changed-while-loading.txt
new file mode 100644
index 00000000000..907590b1023
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/LargestContentfulPaint/svg-image-href-changed-while-loading.txt
@@ -0,0 +1 @@
+Entries:
diff --git a/Tests/LibWeb/Text/expected/LargestContentfulPaint/text-adopted-into-another-document.txt b/Tests/LibWeb/Text/expected/LargestContentfulPaint/text-adopted-into-another-document.txt
new file mode 100644
index 00000000000..9c6e3305a0a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/LargestContentfulPaint/text-adopted-into-another-document.txt
@@ -0,0 +1,2 @@
+Entry in the first document: true
+Entry in the second document: true
diff --git a/Tests/LibWeb/Text/expected/LargestContentfulPaint/white-space-filled-in-while-hidden.txt b/Tests/LibWeb/Text/expected/LargestContentfulPaint/white-space-filled-in-while-hidden.txt
new file mode 100644
index 00000000000..c474e1774d2
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/LargestContentfulPaint/white-space-filled-in-while-hidden.txt
@@ -0,0 +1,2 @@
+Entry for the filled in text: true
+Entry id: target, size is not zero: true
diff --git a/Tests/LibWeb/Text/expected/PerformanceObserver/PerformanceObserver-supportedEntryTypes.txt b/Tests/LibWeb/Text/expected/PerformanceObserver/PerformanceObserver-supportedEntryTypes.txt
index b72ade22bbf..552e62f252e 100644
--- a/Tests/LibWeb/Text/expected/PerformanceObserver/PerformanceObserver-supportedEntryTypes.txt
+++ b/Tests/LibWeb/Text/expected/PerformanceObserver/PerformanceObserver-supportedEntryTypes.txt
@@ -1,4 +1,4 @@
-PerformanceObserver.supportedEntryTypes: event,first-input,mark,measure,navigation,paint,resource
+PerformanceObserver.supportedEntryTypes: event,first-input,largest-contentful-paint,mark,measure,navigation,paint,resource
PerformanceObserver.supportedEntryTypes instanceof Array: true
Object.isFrozen(PerformanceObserver.supportedEntryTypes): true
PerformanceObserver.supportedEntryTypes === PerformanceObserver.supportedEntryTypes: true
diff --git a/Tests/LibWeb/Text/expected/all-window-properties.txt b/Tests/LibWeb/Text/expected/all-window-properties.txt
index 9dbc767d8c4..fc76e13f556 100644
--- a/Tests/LibWeb/Text/expected/all-window-properties.txt
+++ b/Tests/LibWeb/Text/expected/all-window-properties.txt
@@ -300,6 +300,7 @@ IntersectionObserverEntry
Iterator
KeyboardEvent
KeyframeEffect
+LargestContentfulPaint
Location
Lock
LockManager
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/element-only-when-fully-active.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/element-only-when-fully-active.txt
new file mode 100644
index 00000000000..595dc386200
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/element-only-when-fully-active.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Only expose element attribute for fully active documents
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/first-paint-equals-lcp-text.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/first-paint-equals-lcp-text.txt
new file mode 100644
index 00000000000..1049c3bb2ea
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/first-paint-equals-lcp-text.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass FCP and LCP are the same when there is a single text element in the page.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/image-full-viewport.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/image-full-viewport.txt
new file mode 100644
index 00000000000..fec308454fe
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/image-full-viewport.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass The intersectionRect of an img element overflowing is computed correctly
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/image-removed-after-paint.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/image-removed-after-paint.txt
new file mode 100644
index 00000000000..68da358e562
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/image-removed-after-paint.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Element removed after LCP entry should reflect in entry.element
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/invisible-images-composited-1.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/invisible-images-composited-1.txt
new file mode 100644
index 00000000000..04955915d2b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/invisible-images-composited-1.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Images with opacity: 0, visibility: hidden, or display: none are not observable by LargestContentfulPaint.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/invisible-images-composited-2.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/invisible-images-composited-2.txt
new file mode 100644
index 00000000000..04955915d2b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/invisible-images-composited-2.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Images with opacity: 0, visibility: hidden, or display: none are not observable by LargestContentfulPaint.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/invisible-images.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/invisible-images.txt
new file mode 100644
index 00000000000..04955915d2b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/invisible-images.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Images with opacity: 0, visibility: hidden, or display: none are not observable by LargestContentfulPaint.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/modified-text-not-reconsidered.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/modified-text-not-reconsidered.txt
new file mode 100644
index 00000000000..61807534716
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/modified-text-not-reconsidered.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Text element should not be reconsidered as LCP after text content changes.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-mathml.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-mathml.txt
new file mode 100644
index 00000000000..c118e41a7be
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-mathml.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Element rendered by MathML is observable
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-random-namespace.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-random-namespace.txt
new file mode 100644
index 00000000000..9455f1e1cb4
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-random-namespace.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Element created with different namespace is observable
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-svg-data-uri-background-image.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-svg-data-uri-background-image.txt
new file mode 100644
index 00000000000..4c568436054
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-svg-data-uri-background-image.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Data-URI background SVG image is observable.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-svg-data-uri-image.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-svg-data-uri-image.txt
new file mode 100644
index 00000000000..d00159bf8ea
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-svg-data-uri-image.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Same-origin image is observable.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-text.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-text.txt
new file mode 100644
index 00000000000..fd9f58d9149
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/observe-text.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Text element is observable as a LargestContentfulPaint candidate.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/resized-image-not-reconsidered.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/resized-image-not-reconsidered.txt
new file mode 100644
index 00000000000..9535c4426d7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/resized-image-not-reconsidered.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Resized image should not be reconsidered as LCP
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/supported-lcp-type.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/supported-lcp-type.txt
new file mode 100644
index 00000000000..bf3d0dca243
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/supported-lcp-type.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass supportedEntryTypes contains 'largest-contentful-paint'.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/text-fragment-union.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/text-fragment-union.txt
new file mode 100644
index 00000000000..c58ed10af79
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/text-fragment-union.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Text fragment union: wrapped text LCP size reflects the union of all line boxes.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/text-with-display-style.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/text-with-display-style.txt
new file mode 100644
index 00000000000..37ee5d82e13
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/text-with-display-style.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Text with display style is observable.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/toJSON.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/toJSON.txt
new file mode 100644
index 00000000000..74062627a3b
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/toJSON.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Test toJSON() in LargestContentfulPaint.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/transparent-text-with-shadow.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/transparent-text-with-shadow.txt
new file mode 100644
index 00000000000..45aadc74fb4
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/transparent-text-with-shadow.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Transparent text with shadow decoration should not be excluded from LCP.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/transparent-text.txt b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/transparent-text.txt
new file mode 100644
index 00000000000..3d0f0bfe532
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/largest-contentful-paint/transparent-text.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass Transparent text should not be LCP.
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/LargestContentfulPaint/svg-image-href-changed-while-loading.html b/Tests/LibWeb/Text/input/LargestContentfulPaint/svg-image-href-changed-while-loading.html
new file mode 100644
index 00000000000..b7eb1353f18
--- /dev/null
+++ b/Tests/LibWeb/Text/input/LargestContentfulPaint/svg-image-href-changed-while-loading.html
@@ -0,0 +1,37 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<svg width="200" height="200">
+ <image id="target" width="200" height="200"></image>
+</svg>
+<script>
+ asyncTest(async done => {
+ const server = httpTestServer();
+ const svg = size => `<svg xmlns="http://www.w3.org/2000/svg"${size ? ` width="${size}" height="${size}"` : ""}><rect width="100%" height="100%" fill="green"/></svg>`;
+ const echo = (path, size, delay) => server.createEcho("GET", path, {
+ status: 200,
+ headers: { "Content-Type": "image/svg+xml", "Cache-Control": "no-store" },
+ body: svg(size),
+ delay_ms: delay,
+ });
+ const slowURL = await echo("/svg-image-href-changed-while-loading-slow.svg", 200, 500);
+ const fastURL = await echo("/svg-image-href-changed-while-loading-fast.svg", null, 0);
+
+ const entries = [];
+ const observer = new PerformanceObserver(list => entries.push(...list.getEntries()));
+ observer.observe({ type: "largest-contentful-paint", buffered: true });
+
+ // The first request is still loading when href changes, so it is no longer the element's image request once
+ // it finishes, and is not reported. The second image has no natural size, so it is not reported either.
+ const target = document.getElementById("target");
+ target.setAttribute("href", slowURL);
+ target.setAttribute("href", fastURL);
+ await new Promise(resolve => setTimeout(resolve, 1000));
+ await animationFrame();
+ await animationFrame();
+ entries.push(...observer.takeRecords());
+
+ const urls = entries.filter(entry => entry.element === target).map(entry => entry.url.endsWith("-fast.svg") ? "fast" : entry.url.endsWith("-slow.svg") ? "slow" : entry.url);
+ println(`Entries: ${urls.join(", ")}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/LargestContentfulPaint/text-adopted-into-another-document.html b/Tests/LibWeb/Text/input/LargestContentfulPaint/text-adopted-into-another-document.html
new file mode 100644
index 00000000000..7cf9750fb76
--- /dev/null
+++ b/Tests/LibWeb/Text/input/LargestContentfulPaint/text-adopted-into-another-document.html
@@ -0,0 +1,37 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<p id="target" style="font-size: 40px">This text is painted in two documents</p>
+<script>
+ asyncTest(async done => {
+ const frame = document.createElement("iframe");
+ frame.srcdoc = "<!DOCTYPE html><body></body>";
+ await new Promise(resolve => {
+ frame.onload = resolve;
+ document.body.appendChild(frame);
+ });
+
+ // An entry may take several frames under load, so frames are waited for until it is there.
+ const waitForEntry = async (targetWindow, observer, entries) => {
+ for (let i = 0; i < 100 && !entries.some(entry => entry.element === target); ++i) {
+ await new Promise(resolve => targetWindow.requestAnimationFrame(() => targetWindow.setTimeout(resolve)));
+ entries.push(...observer.takeRecords());
+ }
+ return entries.some(entry => entry.element === target);
+ };
+
+ const target = document.getElementById("target");
+ const entries = [];
+ const observer = new PerformanceObserver(list => entries.push(...list.getEntries()));
+ observer.observe({ type: "largest-contentful-paint", buffered: true });
+ println(`Entry in the first document: ${await waitForEntry(window, observer, entries)}`);
+
+ // The element is in the first document's set of elements with rendered text, but not in the second's.
+ const frameWindow = frame.contentWindow;
+ const frameEntries = [];
+ const frameObserver = new frameWindow.PerformanceObserver(list => frameEntries.push(...list.getEntries()));
+ frameObserver.observe({ type: "largest-contentful-paint", buffered: true });
+ frame.contentDocument.body.appendChild(target);
+ println(`Entry in the second document: ${await waitForEntry(frameWindow, frameObserver, frameEntries)}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/LargestContentfulPaint/white-space-filled-in-while-hidden.html b/Tests/LibWeb/Text/input/LargestContentfulPaint/white-space-filled-in-while-hidden.html
new file mode 100644
index 00000000000..d73ec5e3d62
--- /dev/null
+++ b/Tests/LibWeb/Text/input/LargestContentfulPaint/white-space-filled-in-while-hidden.html
@@ -0,0 +1,27 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<div id="target" style="font-size: 40px; display: none"> </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 white space in the hidden element paints nothing, until its data is filled in and the element is shown.
+ const target = document.getElementById("target");
+ await animationFrame();
+ await animationFrame();
+
+ target.firstChild.data = "This text was filled in after it was inserted";
+ target.style.display = "block";
+ await animationFrame();
+ await animationFrame();
+ entries.push(...observer.takeRecords());
+
+ const entry = entries.find(entry => entry.element === target);
+ println(`Entry for the filled in text: ${entry !== undefined}`);
+ if (entry)
+ println(`Entry id: ${entry.id}, size is not zero: ${entry.size > 0}`);
+ done();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/images/green.svg b/Tests/LibWeb/Text/input/wpt-import/images/green.svg
new file mode 100644
index 00000000000..d91971f784b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/images/green.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="100" height="50">
+ <rect fill="lime" width="100" height="50"/>
+</svg>
diff --git a/Tests/LibWeb/Text/input/wpt-import/images/lcp-100x50.png b/Tests/LibWeb/Text/input/wpt-import/images/lcp-100x50.png
new file mode 100644
index 00000000000..0e4722139e3
Binary files /dev/null and b/Tests/LibWeb/Text/input/wpt-import/images/lcp-100x50.png differ
diff --git a/Tests/LibWeb/Text/input/wpt-import/images/lcp-133x106.png b/Tests/LibWeb/Text/input/wpt-import/images/lcp-133x106.png
new file mode 100644
index 00000000000..fb61e8db851
Binary files /dev/null and b/Tests/LibWeb/Text/input/wpt-import/images/lcp-133x106.png differ
diff --git a/Tests/LibWeb/Text/input/wpt-import/images/lcp-256x256.png b/Tests/LibWeb/Text/input/wpt-import/images/lcp-256x256.png
new file mode 100644
index 00000000000..944f10f8761
Binary files /dev/null and b/Tests/LibWeb/Text/input/wpt-import/images/lcp-256x256.png differ
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/element-only-when-fully-active.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/element-only-when-fully-active.html
new file mode 100644
index 00000000000..fb8f25c7b61
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/element-only-when-fully-active.html
@@ -0,0 +1,18 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>Largest Contentful Paint: element is only exposed for fully active documents.</title>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<iframe src="resources/iframe-stores-entry.html" id="ifr"></iframe>
+<script>
+ setup({"hide_test_state": true});
+ let t = async_test('Only expose element attribute for fully active documents');
+ window.triggerTest = t.step_func_done(entry => {
+ assert_not_equals(entry.element, null);
+ const iframe = document.getElementById('ifr');
+ iframe.remove();
+ assert_equals(entry.element, null);
+ });
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/first-paint-equals-lcp-text.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/first-paint-equals-lcp-text.html
new file mode 100644
index 00000000000..7a7f81fac44
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/first-paint-equals-lcp-text.html
@@ -0,0 +1,49 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>LargestContentfulPaint compared with FirstPaint and FirstContentfulPaint on single text page.</title>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script>
+ setup({"hide_test_state": true});
+ async_test(function (t) {
+ assert_implements(window.PerformancePaintTiming, "PerformancePaintTiming is not implemented");
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+ let firstPaintTime = 0;
+ let firstContentfulPaintTime = 0;
+ let largestContentfulPaintTime = 0;
+ const observer = new PerformanceObserver(
+ t.step_func(function(entryList) {
+ entryList.getEntries().forEach(entry => {
+ if (entry.name === 'first-paint') {
+ assert_equals(firstPaintTime, 0, 'Only one first-paint entry.');
+ assert_equals(entry.entryType, 'paint');
+ firstPaintTime = entry.startTime;
+ } else if (entry.name === 'first-contentful-paint') {
+ assert_equals(firstContentfulPaintTime, 0, 'Only one first-contentful-paint entry.');
+ assert_equals(entry.entryType, 'paint');
+ firstContentfulPaintTime = entry.startTime;
+ } else {
+ assert_equals(largestContentfulPaintTime, 0, 'Only one largest-contentful-paint entry.');
+ assert_equals(entry.entryType, 'largest-contentful-paint');
+ largestContentfulPaintTime = entry.renderTime;
+ }
+ // LCP fires necessarily after first-paint and first-contentful-paint.
+ if (largestContentfulPaintTime) {
+ assert_equals(firstContentfulPaintTime, largestContentfulPaintTime, 'FCP should equal LCP.');
+ // In PaintTiming spec, first-paint isn't a hard requirement, browsers can support
+ // first-contentful-paint only.
+ if (firstPaintTime) {
+ assert_less_than_equal(firstPaintTime, firstContentfulPaintTime, 'FP should be less than or equal to FCP.');
+ }
+ t.done();
+ }
+ });
+ })
+ );
+ observer.observe({type: 'largest-contentful-paint', buffered: true});
+ observer.observe({type: 'paint', buffered: true});
+ }, 'FCP and LCP are the same when there is a single text element in the page.');
+</script>
+<p>Text</p>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/image-full-viewport.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/image-full-viewport.html
new file mode 100644
index 00000000000..20d3e09b430
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/image-full-viewport.html
@@ -0,0 +1,45 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>Largest Contentful Paint: size when image overflows</title>
+<!-- In this test, an image with an intrinsic size of 100 x 50 is added, but
+ scaled up in order to overflow the viewport. It should not be reported. -->
+<body>
+<style>
+body {
+ margin: 0px;
+}
+</style>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="resources/largest-contentful-paint-helpers.js"></script>
+<script>
+ const viewportWidth = document.documentElement.clientWidth;
+ const viewportHeight = document.documentElement.clientHeight;
+ setup({"hide_test_state": true});
+ async_test(function (t) {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+ const beforeLoad = performance.now();
+ new PerformanceObserver(
+ t.step_func_done(function(entryList) {
+ assert_equals(entryList.getEntries().length, 1, 'Should have received only one entry!');
+ const entry = entryList.getEntries()[0];
+ if (entry.url)
+ assert_unreached('Should not have received an image entry!');
+ })
+ ).observe({type: 'largest-contentful-paint', buffered: true});
+ // Add an image, setting width and height equal to viewport.
+ img = document.createElement('img');
+ img.src = '../images/lcp-100x50.png';
+ img.id = 'image_id';
+ img.width = viewportWidth * 2;
+ img.height = viewportHeight * 2;
+ img.onload = () => {
+ const p = document.createElement('p');
+ p.innerHTML = 'a';
+ p.style = 'position: absolute; top: 10px; left: 10px;';
+ document.body.appendChild(p);
+ }
+ document.body.appendChild(img);
+ }, 'The intersectionRect of an img element overflowing is computed correctly');
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/image-removed-after-paint.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/image-removed-after-paint.html
new file mode 100644
index 00000000000..21d7e303fc8
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/image-removed-after-paint.html
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<title>LCP: element removed after image paints</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="resources/largest-contentful-paint-helpers.js"></script>
+<link rel="author" title="Shubham Gupta" href="mailto:[email protected]">
+<body>
+<script>
+promise_test(async (t) => {
+ const img = document.createElement('img');
+ img.src = '../images/blue.png';
+ img.id = 'test-image';
+ document.body.appendChild(img);
+
+ const { promise, resolve } = Promise.withResolvers();
+ const observer = new PerformanceObserver((list) => {
+ resolve(list.getEntries()[0]);
+ });
+ observer.observe({ type: 'largest-contentful-paint', buffered: true });
+
+ const entry = await promise;
+
+ assert_not_equals(entry.element, null,
+ 'entry.element should be non-null when element is in DOM');
+
+ img.remove();
+ await raf();
+ await raf();
+
+ assert_equals(entry.element, null,
+ 'entry.element should be null after element is removed');
+}, 'Element removed after LCP entry should reflect in entry.element');
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/invisible-images-composited-1.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/invisible-images-composited-1.html
new file mode 100644
index 00000000000..61c12d9ef9c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/invisible-images-composited-1.html
@@ -0,0 +1,32 @@
+<!DOCTYPE HTML>
+<title>Largest Contentful Paint: invisible images are not observable</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="resources/invisible-images.js"></script>
+<style>
+ .opacity0 {
+ opacity: 0;
+ }
+ .visibilityHidden {
+ visibility: hidden;
+ }
+ .displayNone {
+ display: none;
+ }
+ .willChangeTransform {
+ will-change: transform;
+ }
+ .willChangeOpacity {
+ will-change: opacity;
+ }
+</style>
+<script>
+setup({"hide_test_state": true});
+</script>
+<img src='../images/blue.png' class='opacity0 willChangeTransform' id='opacity0-willChangeTransform'/>
+<img src='../images/green.png' class='visibilityHidden willChangeTransform' id='visibilityHidden'/>
+<img src='../images/red.png' class='displayNone willChangeTransform' id='displayNone'/>
+<img src='../images/blue.png' class='opacity0 willChangeOpacity' id='opacity0-willChangeOpacity'/>
+<div class='opacity0 composited'><img src='../images/yellow.png' id='divOpacity0'/></div>
+<div class='visibilityHidden composited'><img src='../images/yellow.png' id='divVisibilityHidden'/></div>
+<div class='displayNone composited'><img src='../images/yellow.png' id='divDisplayNone'/></div>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/invisible-images-composited-2.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/invisible-images-composited-2.html
new file mode 100644
index 00000000000..1a944f64ab6
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/invisible-images-composited-2.html
@@ -0,0 +1,26 @@
+<!DOCTYPE HTML>
+<title>Largest Contentful Paint: invisible images are not observable</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="resources/invisible-images.js"></script>
+<style>
+ .opacity0 {
+ opacity: 0;
+ }
+ .visibilityHidden {
+ visibility: hidden;
+ }
+ .displayNone {
+ display: none;
+ }
+ .composited {
+ will-change: transform;
+ }
+ img {
+ border: 2px solid black;
+ will-change: transform;
+ }
+</style>
+<div class='opacity0 composited'><img src='../images/yellow.png' id='divOpacity0'/></div>
+<div class='visibilityHidden composited'><img src='../images/yellow.png' id='divVisibilityHidden'/></div>
+<div class='displayNone composited'><img src='../images/yellow.png' id='divDisplayNone'/></div>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/invisible-images.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/invisible-images.html
new file mode 100644
index 00000000000..7a318d4b6fe
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/invisible-images.html
@@ -0,0 +1,22 @@
+<!DOCTYPE HTML>
+<title>Largest Contentful Paint: invisible images are not observable</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="resources/invisible-images.js"></script>
+<style>
+ .opacity0 {
+ opacity: 0;
+ }
+ .visibilityHidden {
+ visibility: hidden;
+ }
+ .displayNone {
+ display: none;
+ }
+</style>
+<img src='../images/blue.png' class='opacity0' id='opacity0'/>
+<img src='../images/green.png' class='visibilityHidden' id='visibilityHidden'/>
+<img src='../images/red.png' class='displayNone' id='displayNone'/>
+<div class='opacity0'><img src='../images/yellow.png' id='divOpacity0'/></div>
+<div class='visibilityHidden'><img src='../images/yellow.png' id='divVisibilityHidden'/></div>
+<div class='displayNone'><img src='../images/yellow.png' id='divDisplayNone'/></div>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/modified-text-not-reconsidered.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/modified-text-not-reconsidered.html
new file mode 100644
index 00000000000..4622be41192
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/modified-text-not-reconsidered.html
@@ -0,0 +1,68 @@
+<!doctype html>
+<meta charset="utf-8" />
+<title>Text element is not reconsidered as LCP after modification.</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<link rel="author" title="Shubham Gupta" href="mailto:[email protected]">
+
+<body>
+ <div id="text" style="position: absolute; width: auto; white-space: nowrap;">short</div>
+ <script>
+ promise_test(async (t) => {
+ // Set up an observer that looks for LCP entries for the text div,
+ // identified by its id.
+ const entries = [];
+ const observer = new PerformanceObserver((l) => {
+ entries.push(...l.getEntries().filter((e) => e.id == "text"));
+ });
+ observer.observe({ type: "largest-contentful-paint", buffered: true });
+
+ // Wait for the initial LCP entry to be emitted, and verify it's as expected.
+ await t.step_wait(() => entries.length > 0,
+ "Waiting for initial LCP entry to be emitted.");
+ assert_equals(entries.length, 1,
+ "There should be exactly one LCP entry.");
+ assert_equals(entries[0].id, "text",
+ "Entry id should match the text element.");
+ assert_equals(entries[0].entryType, "largest-contentful-paint",
+ "Entry type should be largest-contentful-paint.");
+ assert_equals(entries[0].url, "",
+ "Entry url should be empty for text.");
+
+ const element = document.getElementById("text");
+ const elementArea = element.clientWidth * element.clientHeight;
+ // The LCP size should approximately match the element's client area.
+ assert_greater_than_equal(entries[0].size, elementArea * 0.75,
+ `LCP size should cover most of the element area (size=${entries[0].size}, element=${elementArea}).`);
+ assert_less_than_equal(entries[0].size, elementArea * 1.25,
+ `LCP size should not significantly exceed the element area (size=${entries[0].size}, element=${elementArea}).`);
+
+ const initialSize = entries[0].size;
+
+ // Modify the text content — a longer text would produce a larger
+ // element area if the element were reconsidered for LCP.
+ element.textContent =
+ "much longer text that would increase the bounding rectangle if reconsidered";
+
+ // Wait for layout + paint cycles, then disconnect.
+ await new Promise((resolve) => {
+ requestAnimationFrame(() => {
+ t.step_timeout(() => {
+ observer.disconnect();
+ resolve();
+ }, 1000);
+ });
+ });
+
+ // Verify the element was not reconsidered — per spec each element
+ // is reported exactly once, even after modification.
+ assert_equals(entries.length, 1,
+ "There should still be exactly one LCP entry after text modification.");
+ assert_equals(entries[0].id, "text",
+ "Entry id should still be the original text element.");
+ assert_equals(entries[0].size, initialSize,
+ "LCP size should remain unchanged after text modification.");
+ }, "Text element should not be reconsidered as LCP after text content changes.");
+ </script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-mathml.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-mathml.html
new file mode 100644
index 00000000000..773eea2a9ef
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-mathml.html
@@ -0,0 +1,46 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>Largest Contentful Paint: observe element rendered by MathML</title>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="resources/largest-contentful-paint-helpers.js"></script>
+<style>
+mathml {
+ font-size: 12px;
+}
+</style>
+<script>
+ async_test(function (t) {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+ let beforeLoad;
+ const observer = new PerformanceObserver(
+ t.step_func_done(function(entryList) {
+ assert_equals(entryList.getEntries().length, 1);
+ const entry = entryList.getEntries()[0];
+ assert_equals(entry.entryType, 'largest-contentful-paint');
+ assert_greater_than_equal(entry.renderTime, beforeRender);
+ assert_approx_equals(entry.startTime, entry.renderTime, 0.001,
+ 'startTime should be equal to renderTime to the precision of 1 millisecond.');
+ assert_equals(entry.duration, 0);
+ // Some lower bound: height of at least 12 px.
+ // Width of at least 100 px.
+ assert_greater_than(entry.size, 1200);
+ assert_equals(entry.loadTime, 0);
+ assert_equals(entry.id, 'mathml');
+ assert_equals(entry.url, '');
+ assert_equals(entry.element, document.getElementById('mathml'));
+ })
+ );
+ observer.observe({type: 'largest-contentful-paint', buffered: true});
+ beforeRender = performance.now();
+ }, 'Element rendered by MathML is observable');
+</script>
+<math display="block">
+ <mrow>
+ <msup>
+ <mi id="mathml">This is important text! :)</mi>
+ </msup>
+ </mrow>
+</math>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-random-namespace.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-random-namespace.html
new file mode 100644
index 00000000000..2391eb6d983
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-random-namespace.html
@@ -0,0 +1,45 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>Largest Contentful Paint: observe element created in a random namespace</title>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="resources/largest-contentful-paint-helpers.js"></script>
+<style>
+ div {
+ display: block;
+ }
+</style>
+<script>
+ async_test(function (t) {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+ let beforeRender;
+ const observer = new PerformanceObserver(
+ t.step_func_done(function(entryList) {
+ assert_equals(entryList.getEntries().length, 1);
+ const entry = entryList.getEntries()[0];
+ assert_equals(entry.entryType, 'largest-contentful-paint');
+ assert_greater_than_equal(entry.renderTime, beforeRender);
+ assert_greater_than_equal(performance.now(), entry.renderTime);
+ assert_approx_equals(entry.startTime, entry.renderTime, 0.001,
+ 'startTime should be equal to renderTime to the precision of 1 millisecond.');
+ assert_equals(entry.duration, 0);
+ // Some lower bound: height of at least 12 px.
+ // Width of at least 100 px.
+ assert_greater_than(entry.size, 1200);
+ assert_equals(entry.loadTime, 0);
+ assert_equals(entry.url, '');
+ assert_equals(entry.id, 'my_text');
+ assert_equals(entry.element, document.getElementById("my_text"));
+ })
+ );
+ observer.observe({type: 'largest-contentful-paint', buffered: true});
+
+ const div = document.createElementNS("random", "div");
+ div.innerHTML = "This is important text! :)";
+ div.id = "my_text";
+ beforeRender = performance.now();
+ document.body.appendChild(div);
+ }, 'Element created with different namespace is observable');
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-svg-data-uri-background-image.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-svg-data-uri-background-image.html
new file mode 100644
index 00000000000..b7ef183a105
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-svg-data-uri-background-image.html
@@ -0,0 +1,41 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>Largest Contentful Paint: observe image.</title>
+<style>
+ #target {
+ background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="50"><rect fill="lime" width="100" height="50"/></svg>');
+ width: 100px;
+ height: 50px;
+ }
+</style>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="resources/largest-contentful-paint-helpers.js"></script>
+<script>
+ async_test(function (t) {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+ const beforeLoad = performance.now();
+ const observer = new PerformanceObserver(
+ t.step_func_done(function(entryList) {
+ assert_equals(entryList.getEntries().length, 1);
+ const entry = entryList.getEntries()[0];
+ let url = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"';
+ url += ' width="100" height="50"><rect fill="lime" width="100"';
+ url += ' height="50"/></svg>';
+ // green.svg is 100 by 50
+ const size = 100 * 50;
+ checkImage(entry, url, 'target', size, beforeLoad);
+ })
+ );
+ observer.observe({type: 'largest-contentful-paint', buffered: true});
+ t.step_timeout(() => {
+ assert_unreached("The image should have triggered an LCP entry.");
+ t.done();
+ }, 1000);
+ }, 'Data-URI background SVG image is observable.');
+</script>
+
+<div id="target" width="100" height="50"></div>
+</body>
+
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-svg-data-uri-image.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-svg-data-uri-image.html
new file mode 100644
index 00000000000..37e6c8cbb90
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-svg-data-uri-image.html
@@ -0,0 +1,29 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>Largest Contentful Paint: observe image.</title>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script src="resources/largest-contentful-paint-helpers.js"></script>
+<script>
+ async_test(function (t) {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+ const beforeLoad = performance.now();
+ const observer = new PerformanceObserver(
+ t.step_func_done(function(entryList) {
+ assert_equals(entryList.getEntries().length, 1);
+ const entry = entryList.getEntries()[0];
+ let url = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"';
+ url += ' width="100" height="50"><rect fill="lime" width="100"';
+ url += ' height="50"/></svg>';
+ // green.svg is 100 by 50
+ const size = 100 * 50;
+ checkImage(entry, url, 'image_id', size, beforeLoad);
+ })
+ );
+ observer.observe({type: 'largest-contentful-paint', buffered: true});
+ }, 'Same-origin image is observable.');
+</script>
+
+<img src='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="50"><rect fill="lime" width="100" height="50"/></svg>' id='image_id'/>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-text.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-text.html
new file mode 100644
index 00000000000..046497194af
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/observe-text.html
@@ -0,0 +1,54 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>Largest Contentful Paint: observe text.</title>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<style>
+p {
+ font-size: 12px;
+}
+</style>
+<script>
+ async_test(function (t) {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+ let beforeRender;
+ const observer = new PerformanceObserver(
+ t.step_func_done(function(entryList) {
+ assert_equals(entryList.getEntries().length, 1);
+ const entry = entryList.getEntries()[0];
+ assert_equals(entry.entryType, 'largest-contentful-paint');
+ assert_greater_than_equal(entry.renderTime, beforeRender);
+ assert_greater_than_equal(performance.now(), entry.renderTime);
+ assert_approx_equals(entry.startTime, entry.renderTime, 0.001,
+ 'startTime should be equal to renderTime to the precision of 1 millisecond.');
+
+ // PaintTimingMixin
+ if ("paintTime" in entry && entry.paintTime !== null) {
+ assert_greater_than_equal(entry.paintTime, beforeRender, 'paintTime should represent the time when the UA started painting');
+
+ if ("presentationTime" in entry && entry.presentationTime !== null) {
+ assert_greater_than(entry.presentationTime, entry.paintTime);
+ assert_equals(entry.presentationTime, entry.renderTime);
+ } else {
+ assert_equals(entry.renderTime, entry.paintTime);
+ }
+ }
+ assert_equals(entry.duration, 0);
+ // Some lower bound: height of at least 12 px.
+ // Width of at least 100 px.
+ // TODO: find a good way to bound text width.
+ assert_greater_than_equal(entry.size, 1200);
+ assert_equals(entry.loadTime, 0);
+ assert_equals(entry.id, 'my_text');
+ assert_equals(entry.url, '');
+ assert_equals(entry.element, document.getElementById('my_text'));
+ })
+ );
+ observer.observe({type: 'largest-contentful-paint', buffered: true});
+ beforeRender = performance.now();
+ }, 'Text element is observable as a LargestContentfulPaint candidate.');
+</script>
+
+<p id='my_text'>This is important text! :)</p>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resized-image-not-reconsidered.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resized-image-not-reconsidered.html
new file mode 100644
index 00000000000..bb2dd72ed06
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resized-image-not-reconsidered.html
@@ -0,0 +1,48 @@
+<!doctype html>
+<meta charset="utf-8" />
+<title>Resized Image Is Not Reconsidered as LCP.</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+
+<body>
+ <img src="../images/lcp-256x256.png" id="testpic" height="100" width="50" />
+ <script>
+ promise_test(async (t) => {
+ // Set up an observer that looks for LCP entries for the testpic,
+ // identified by its id.
+ const entries = [];
+ const observer = new PerformanceObserver((l) => {
+ entries.push(...l.getEntries().filter((e) => e.id == "testpic"));
+ });
+ observer.observe({ type: "largest-contentful-paint", buffered: true });
+
+ // Wait for the initial LCP entry to be emitted, and verify it's as expected.
+ await t.step_wait(() => entries.length > 0, "Waiting for initial LCP entry to be emitted.");
+ assert_equals(entries.length, 1);
+ assert_equals(entries[0].id, "testpic");
+ assert_equals(entries[0].size, 100 * 50);
+
+ // Now resize image, then wait, then observe that no additional
+ // entries are emitted.
+ document.getElementById("testpic").height = 150;
+
+ // Wait for the image to be resized - after a requestAnimationFrame
+ // cycle and 1 second, disconnect the observer.
+ await new Promise((resolve) => {
+ requestAnimationFrame(() => {
+ t.step_timeout(() => {
+ observer.disconnect();
+ resolve();
+ }, 1000);
+ });
+ });
+
+ // Verify that the image was not reconsidered as LCP: it's still
+ // the same entry, reflecting the initial size with width and height from
+ // the img tag.
+ assert_equals(entries.length, 1);
+ assert_equals(entries[0].id, "testpic");
+ assert_equals(entries[0].size, 100 * 50);
+ }, "Resized image should not be reconsidered as LCP");
+ </script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resources/iframe-stores-entry.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resources/iframe-stores-entry.html
new file mode 100644
index 00000000000..cd600254805
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resources/iframe-stores-entry.html
@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html>
+<body>
+<p>Text</p>
+<script>
+ const observer = new PerformanceObserver(entryList => {
+ window.parent.triggerTest(entryList.getEntries()[0]);
+ });
+ observer.observe({type: 'largest-contentful-paint', buffered: true});
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resources/invisible-images.js b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resources/invisible-images.js
new file mode 100644
index 00000000000..bad078e35f0
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resources/invisible-images.js
@@ -0,0 +1,22 @@
+async_test(t => {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+ const observer = new PerformanceObserver(
+ t.step_func(entryList => {
+ entryList.getEntries().forEach(entry => {
+ // May receive a text entry. Ignore that entry.
+ if (!entry.url) {
+ return;
+ }
+ // The images should not have caused an entry, so fail test.
+ assert_unreached('Should not have received an entry! Received one with id '
+ + entryList.getEntries()[0].id);
+ });
+ })
+ );
+ observer.observe({type: 'largest-contentful-paint', buffered: true});
+ // Images have been added but should not cause entries to be dispatched.
+ // Wait for 500ms and end test, ensuring no entry was created.
+ t.step_timeout(() => {
+ t.done();
+ }, 500);
+}, 'Images with opacity: 0, visibility: hidden, or display: none are not observable by LargestContentfulPaint.');
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resources/largest-contentful-paint-helpers.js b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resources/largest-contentful-paint-helpers.js
new file mode 100644
index 00000000000..b6a8a4f3244
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/resources/largest-contentful-paint-helpers.js
@@ -0,0 +1,149 @@
+const image_delay = 2000;
+const delay_pipe_value = image_delay / 1000;
+
+const await_with_timeout = async (delay, message, promise, cleanup = ()=>{}) => {
+ let timeout_id;
+ const timeout = new Promise((_, reject) => {
+ timeout_id = step_timeout(() =>
+ reject(new DOMException(message, "TimeoutError")), delay)
+ });
+ let result = null;
+ try {
+ result = await Promise.race([promise, timeout]);
+ clearTimeout(timeout_id);
+ } finally {
+ cleanup();
+ }
+ return result;
+};
+
+// Receives an image LargestContentfulPaint |entry| and checks |entry|'s attribute values.
+// The |timeLowerBound| parameter is a lower bound on the loadTime value of the entry.
+// The |options| parameter may contain some string values specifying the following:
+// * 'renderTimeIs0': the renderTime should be 0 (image does not pass Timing-Allow-Origin checks).
+// When not present, the renderTime should not be 0 (image passes the checks).
+// * 'sizeLowerBound': the |expectedSize| is only a lower bound on the size attribute value.
+// When not present, |expectedSize| must be exactly equal to the size attribute value.
+// * 'approximateSize': the |expectedSize| is only approximate to the size attribute value.
+// This option is mutually exclusive to 'sizeLowerBound'.
+function checkImage(entry, expectedUrl, expectedID, expectedSize, timeLowerBound, options = []) {
+ assert_equals(entry.name, '', "Entry name should be the empty string");
+ assert_equals(entry.entryType, 'largest-contentful-paint',
+ "Entry type should be largest-contentful-paint");
+ assert_equals(entry.duration, 0, "Entry duration should be 0");
+ // The entry's url can be truncated.
+ assert_equals(expectedUrl.substr(0, 100), entry.url.substr(0, 100),
+ `Expected URL ${expectedUrl} should at least start with the entry's URL ${entry.url}`);
+ assert_equals(entry.id, expectedID, "Entry ID matches expected one");
+ assert_equals(entry.element, document.getElementById(expectedID),
+ "Entry element is expected one");
+ if (options.includes('skip')) {
+ return;
+ }
+ assert_greater_than_equal(performance.now(), entry.renderTime,
+ 'renderTime should occur before the entry is dispatched to the observer.');
+ assert_approx_equals(entry.startTime, entry.renderTime, 0.001,
+ 'startTime should be equal to renderTime to the precision of 1 millisecond.');
+ if (options.includes('sizeLowerBound')) {
+ assert_greater_than(entry.size, expectedSize);
+ } else if (options.includes('approximateSize')) {
+ assert_approx_equals(entry.size, expectedSize, 1);
+ } else{
+ assert_equals(entry.size, expectedSize);
+ }
+
+ assert_greater_than_equal(entry.paintTime, timeLowerBound, 'paintTime should represent the time when the UA started painting');
+
+ // PaintTimingMixin
+ if ("presentationTime" in entry && entry.presentationTime !== null) {
+ assert_greater_than(entry.presentationTime, entry.paintTime);
+ assert_equals(entry.presentationTime, entry.renderTime);
+ } else {
+ assert_equals(entry.renderTime, entry.paintTime);
+ }
+
+ if (options.includes('animated')) {
+ assert_less_than(entry.renderTime, image_delay,
+ 'renderTime should be smaller than the delay applied to the second frame');
+ assert_greater_than(entry.renderTime, 0,
+ 'renderTime should be larger than 0');
+ }
+ else {
+ assert_between_inclusive(entry.loadTime, timeLowerBound, entry.renderTime,
+ 'loadTime should occur between the lower bound and the renderTime');
+ }
+}
+
+const load_and_observe = url => {
+ return new Promise(resolve => {
+ (new PerformanceObserver(entryList => {
+ for (let entry of entryList.getEntries()) {
+ if (entry.url == url) {
+ resolve(entryList.getEntries()[0]);
+ }
+ }
+ })).observe({ type: 'largest-contentful-paint', buffered: true });
+ const img = new Image();
+ img.id = 'image_id';
+ img.src = url;
+ document.body.appendChild(img);
+ });
+};
+
+const load_video_and_observe = url => {
+ return new Promise(resolve => {
+ (new PerformanceObserver(entryList => {
+ for (let entry of entryList.getEntries()) {
+ if (entry.url == url) {
+ resolve(entryList.getEntries()[0]);
+ }
+ }
+ })).observe({ type: 'largest-contentful-paint', buffered: true });
+ const video = document.createElement("video");
+ video.id = 'video_id';
+ video.src = url;
+ video.autoplay = true;
+ video.muted = true;
+ video.loop = true;
+ document.body.appendChild(video);
+ });
+};
+
+const getLCPStartTime = (identifier) => {
+ return new Promise(resolve => {
+ new PerformanceObserver((entryList, observer) => {
+ entryList.getEntries().forEach(e => {
+ if (e.url.includes(identifier)) {
+ resolve(e);
+ observer.disconnect();
+ }
+ });
+ }).observe({ type: 'largest-contentful-paint', buffered: true });
+ });
+}
+
+const getFCPStartTime = () => {
+ return performance.getEntriesByName('first-contentful-paint')[0];
+}
+
+const add_text = (text) => {
+ const paragraph = document.createElement('p');
+ paragraph.innerHTML = text;
+ document.body.appendChild(paragraph);
+}
+
+const loadImage = (url, shouldBeIgnoredForLCP = false) => {
+ return new Promise(function (resolve, reject) {
+ let image = document.createElement('img');
+ image.addEventListener('load', () => { resolve(image); });
+ image.addEventListener('error', reject);
+ image.src = url;
+ if (shouldBeIgnoredForLCP)
+ image.style.opacity = 0;
+ document.body.appendChild(image);
+ });
+}
+
+const raf = () => {
+ return new Promise(resolve => requestAnimationFrame(resolve));
+}
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/supported-lcp-type.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/supported-lcp-type.html
new file mode 100644
index 00000000000..46c77d7cb33
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/supported-lcp-type.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<head>
+<title>PerformanceObserver.supportedEntryTypes contains "largest-contentful-paint"</title>
+</head>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<script>
+test(() => {
+ if (typeof PerformanceObserver.supportedEntryTypes === "undefined")
+ assert_unreached("supportedEntryTypes is not supported.");
+ assert_greater_than(PerformanceObserver.supportedEntryTypes.indexOf("largest-contentful-paint"), -1,
+ "There should be an entry 'largest-contentful-paint' in PerformanceObserver.supportedEntryTypes");
+}, "supportedEntryTypes contains 'largest-contentful-paint'.");
+</script>
+</body>
+</html>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/text-fragment-union.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/text-fragment-union.html
new file mode 100644
index 00000000000..071189c8195
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/text-fragment-union.html
@@ -0,0 +1,55 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>Largest Contentful Paint: text fragment union across line wraps.</title>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<link rel="author" title="Shubham Gupta" href="mailto:[email protected]">
+<script>
+ promise_test(async (t) => {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+
+ // Create a text element narrow enough to force line wrapping across
+ // multiple fragments. Without correct union, only a single line's
+ // bounding box would be reported instead of all lines combined.
+ const div = document.createElement('div');
+ div.id = 'multi-line-text';
+ div.textContent =
+ 'This is a long text that wraps across several lines creating ' +
+ 'multiple layout fragments that must be unioned for correct LCP size calculation';
+ div.style.cssText = 'width: 250px; font-size: 24px; line-height: 1.5;';
+ document.body.appendChild(div);
+
+ await new Promise(resolve => {
+ new PerformanceObserver(
+ t.step_func((entryList, observer) => {
+ for (const entry of entryList.getEntries()) {
+ if (entry.id !== 'multi-line-text') continue;
+
+ assert_equals(entry.entryType, 'largest-contentful-paint',
+ 'Entry type should be largest-contentful-paint.');
+ assert_equals(entry.element, div,
+ 'Entry element should be multi-line-text div.');
+ assert_equals(entry.url, '', 'Entry url should be empty.');
+ assert_equals(entry.loadTime, 0, 'Entry loadTime should be 0.');
+
+ // With correct fragment union, the LCP size should reflect all
+ // line boxes — approximately the element's client area.
+ const elementArea = div.clientWidth * div.clientHeight;
+
+ // Single-fragment (broken union) would produce a much smaller
+ // size — roughly one line's worth. We use a lower bound
+ // to distinguish between union and single-line behavior.
+ assert_greater_than_equal(entry.size, elementArea * 0.65,
+ `LCP size should cover most of the element area (size=${entry.size}, element=${elementArea}).`);
+ assert_less_than_equal(entry.size, elementArea * 1.2,
+ `LCP size should not significantly exceed the element area (size=${entry.size}, element=${elementArea}).`);
+
+ observer.disconnect();
+ resolve();
+ }
+ })).observe({type: 'largest-contentful-paint', buffered: true});
+ });
+ }, 'Text fragment union: wrapped text LCP size reflects the union of all line boxes.');
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/text-with-display-style.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/text-with-display-style.html
new file mode 100644
index 00000000000..31836fd2ff2
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/text-with-display-style.html
@@ -0,0 +1,76 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>Largest Contentful Paint: observe text with display style.</title>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<style>
+#title {
+ display: flex;
+}
+</style>
+<h1 id='title'>I am a title!</h1>
+<script>
+ async_test(function (t) {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+ let beforeRender;
+ /* In this test, we first observe a header with style 'display: flex'.
+ * Once observed, we remove it and add a header with style 'display: grid'.
+ * And once that is observed, we remove it and add a header with style 'display: block'.
+ * At each step, we check the values of the entries received.
+ */
+ let observedFlex = false;
+ let observedGrid = false;
+ const observer = new PerformanceObserver(
+ t.step_func(function(entryList) {
+ assert_equals(entryList.getEntries().length, 1);
+ const entry = entryList.getEntries()[0];
+ assert_equals(entry.entryType, 'largest-contentful-paint');
+ assert_greater_than_equal(entry.renderTime, beforeRender);
+ assert_greater_than_equal(performance.now(), entry.renderTime);
+ assert_approx_equals(entry.startTime, entry.renderTime, 0.001,
+ 'startTime should be equal to renderTime to the precision of 1 millisecond.');
+ assert_equals(entry.duration, 0);
+ // TODO: find a good way to bound text size.
+ assert_greater_than_equal(entry.size, 500);
+ assert_equals(entry.url, '');
+ assert_equals(entry.loadTime, 0);
+ if (!observedFlex) {
+ observedFlex = true;
+ assert_equals(entry.id, 'title');
+ const title = document.getElementById('title');
+ assert_equals(entry.element, title);
+ // Remove 'display: flex' and add 'display: grid' text.
+ title.parentNode.removeChild(title);
+ const title2 = document.createElement('h1');
+ title2.id = 'title2';
+ title2.style = 'display: grid';
+ title2.innerHTML = 'I am a second title!';
+ document.body.appendChild(title2);
+ beforeRender = performance.now();
+ } else if (!observedGrid) {
+ observedGrid = true;
+ assert_equals(entry.id, 'title2');
+ const title2 = document.getElementById('title2');
+ assert_equals(entry.element, title2);
+ // Remove 'display: grid' and add 'display: block' text.
+ title2.parentNode.removeChild(title2);
+ const title3 = document.createElement('h1');
+ title3.id = 'title3';
+ title3.style = 'display: block';
+ title3.innerHTML = 'I am the third and last title!';
+ document.body.appendChild(title3);
+ beforeRender = performance.now();
+ } else {
+ assert_equals(entry.id, 'title3');
+ const title3 = document.getElementById('title3');
+ assert_equals(entry.element, title3);
+ t.done();
+ }
+ })
+ );
+ observer.observe({type: 'largest-contentful-paint', buffered: true});
+ beforeRender = performance.now();
+ }, 'Text with display style is observable.');
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/toJSON.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/toJSON.html
new file mode 100644
index 00000000000..56510cba4fb
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/toJSON.html
@@ -0,0 +1,40 @@
+<!DOCTYPE HTML>
+<meta charset=utf-8>
+<title>Largest Contentful Paint: toJSON</title>
+<body>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<p>Text!</p>
+<script>
+ async_test(function (t) {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+ const observer = new PerformanceObserver(
+ t.step_func_done(function(entryList) {
+ const entry = entryList.getEntries()[0];
+ assert_equals(typeof(entry.toJSON), 'function');
+ const json = entry.toJSON();
+ assert_equals(typeof(json), 'object');
+ const keys = [
+ // PerformanceEntry
+ 'name',
+ 'entryType',
+ 'startTime',
+ 'duration',
+ // LargestContentfulPaint
+ 'renderTime',
+ 'loadTime',
+ 'size',
+ 'id',
+ 'url',
+ ];
+ for (const key of keys) {
+ assert_equals(json[key], entry[key],
+ 'LargestContentfulPaint ${key} entry does not match its toJSON value');
+ }
+ assert_equals(json['element'], undefined, 'toJSON should not include element');
+ })
+ );
+ observer.observe({type: 'largest-contentful-paint', buffered: true});
+ }, 'Test toJSON() in LargestContentfulPaint.');
+</script>
+</body>
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/transparent-text-with-shadow.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/transparent-text-with-shadow.html
new file mode 100644
index 00000000000..cb0cab11bab
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/transparent-text-with-shadow.html
@@ -0,0 +1,47 @@
+<!DOCTYPE html>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<!--
+ Transparent text with shadow decoration should be eligible for LCP.
+-->
+<style>
+ .large-transparent {
+ font-size: 200px;
+ position: fixed;
+ top: 0;
+ left: 0;
+ padding: 0;
+ margin: 0;
+ pointer-events: none;
+ color: transparent;
+ z-index: -999;
+ text-shadow: green 5px 5px;
+ }
+</style>
+
+<body>
+ <img src='../images/lcp-133x106.png' id='image' />
+ <p id='larger_text' class='large-transparent'>fake LCP</p>
+
+ <script>
+ const LcpEntryPromise = (entry_id) => {
+ return new Promise(resolve => {
+ new PerformanceObserver((entryList, observer) => {
+ if (entryList.getEntries().filter(e => e.id == entry_id).length > 0) {
+ resolve(entryList.getEntries());
+ observer.disconnect();
+ }
+ }).observe({ type: 'largest-contentful-paint', buffered: true });
+ });
+ }
+
+ promise_test(async t => {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+
+ lcpEntries = await LcpEntryPromise('larger_text');
+
+ assert_equals(lcpEntries[lcpEntries.length - 1].id, 'larger_text',
+ "Transparent text with shadow decoration was included in LCP but not at correct place in timeline.");
+ }, "Transparent text with shadow decoration should not be excluded from LCP.")
+ </script>
+</body>
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/transparent-text.html b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/transparent-text.html
new file mode 100644
index 00000000000..bd165030e26
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/largest-contentful-paint/transparent-text.html
@@ -0,0 +1,48 @@
+<!DOCTYPE html>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<!--
+ Transparent text should not be eligible for LCP.
+-->
+<style>
+ .large-transparent {
+ font-size: 2000px;
+ position: fixed;
+ top: 0;
+ left: 0;
+ padding: 0;
+ margin: 0;
+ pointer-events: none;
+ color: transparent;
+ z-index: -999;
+ }
+</style>
+
+<body>
+ <img src='../images/lcp-133x106.png' id='lcp' />
+ <p id="fake_lcp" class='large-transparent'>fake LCP</p>
+
+ <script>
+ const LcpEntryListPromise = (t) => {
+ return new Promise(resolve => {
+ new PerformanceObserver((entryList, observer) => {
+ if (entryList.getEntries().length > 0) {
+ resolve(entryList.getEntries());
+
+ observer.disconnect();
+ }
+ }).observe({ type: 'largest-contentful-paint', buffered: true });
+ });
+ }
+
+ promise_test(async t => {
+ assert_implements(window.LargestContentfulPaint, "LargestContentfulPaint is not implemented");
+
+ lcpEntries = await LcpEntryListPromise();
+
+ assert_equals(lcpEntries.length, 1, "There should only be 1 entry.");
+
+ assert_true(lcpEntries[0].url.includes('lcp-133x106.png'), "The LCP entry should be the image.");
+ }, "Transparent text should not be LCP.")
+ </script>
+</body>
\ No newline at end of file