Skip to content

Truly independent web browser

LibWeb: Implement VisibilityStateEntry

sideshowbarkerfdd3fc407e6f
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index cd7d5a4e02d..981b30eab8d 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -634,6 +634,7 @@ set(SOURCES
HTML/VideoPlaybackQuality.cpp
HTML/VideoTrack.cpp
HTML/VideoTrackList.cpp
+ HTML/VisibilityStateEntry.cpp
HTML/WebViewHints.cpp
HTML/Window.cpp
HTML/WindowEventHandlers.cpp
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index e48b5ea4a28..a66841cf08d 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -225,6 +225,7 @@
#include <LibWeb/HTML/StorageEvent.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/TextDirective.h>
+#include <LibWeb/HTML/VisibilityStateEntry.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
#include <LibWeb/HTML/WindowProxy.h>
@@ -5784,6 +5785,19 @@ void Document::media_element_audio_play_state_changed(Badge<HTML::HTMLMediaEleme
window->document_audio_play_state_changed({});
}
+// https://html.spec.whatwg.org/multipage/interaction.html#visibilitystateentry
+void Document::queue_a_new_visibility_state_entry(HTML::VisibilityState visibility_state, HighResolutionTime::DOMHighResTimeStamp timestamp)
+{
+ auto window = this->window();
+ if (!window)
+ return;
+
+ // https://w3c.github.io/performance-timeline/#dfn-queue-a-performanceentry
+ auto entry = HTML::VisibilityStateEntry::create(visibility_state, timestamp);
+ window->queue_performance_entry(entry);
+ window->add_performance_entry(entry, HTML::WindowOrWorkerGlobalScopeMixin::CheckIfPerformanceBufferIsFull::Yes);
+}
+
// https://html.spec.whatwg.org/multipage/interaction.html#update-the-visibility-state
void Document::update_the_visibility_state(HTML::VisibilityState visibility_state)
{
@@ -5795,8 +5809,9 @@ void Document::update_the_visibility_state(HTML::VisibilityState visibility_stat
m_visibility_state = visibility_state;
rendering_pending_document_changed(*this);
- // FIXME: 3. Queue a new VisibilityStateEntry whose visibility state is visibilityState and whose timestamp is the current
+ // 3. Queue a new VisibilityStateEntry whose visibility state is visibilityState and whose timestamp is the current
// high resolution time given document's relevant global object.
+ queue_a_new_visibility_state_entry(visibility_state, HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this)));
// FIXME: 4. Run the screen orientation change steps with document.
@@ -7846,7 +7861,8 @@ void Document::set_initial_visibility_state(HTML::VisibilityState visibility_sta
if (auto window = this->window(); window && &window->associated_document() == this)
window->document_visibility_state_changed({});
- // TODO: 2. Queue a new VisibilityStateEntry whose visibility state is document's visibility state and whose timestamp is 0.
+ // 2. Queue a new VisibilityStateEntry whose visibility state is document's visibility state and whose timestamp is 0.
+ queue_a_new_visibility_state_entry(m_visibility_state, 0);
// AD-HOC: Record the initial viewport and visual viewport state so that if the viewport changes before the
// first rendering update (e.g. in our fullscreen tests), change events are still fired.
diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.h
index 3e7e91ca44f..252c945af08 100644
--- a/Libraries/LibWeb/DOM/Document.h
+++ b/Libraries/LibWeb/DOM/Document.h
@@ -1900,6 +1900,8 @@ private:
bool update_is_fully_active() const;
bool compute_is_fully_active() const;
+ void queue_a_new_visibility_state_entry(HTML::VisibilityState, HighResolutionTime::DOMHighResTimeStamp timestamp);
+
// Records the document's viewport for the host to publish, or, given `committed`, commits the recording.
Optional<Painting::DisplayListRecording> start_recording(Layout::BegunRead const&, HTML::PaintConfig, Painting::PaintCommandCacheMode, Optional<Compositor::FlightPresentation>&& committed);
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index a1648722ccc..af63a2c037b 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -848,6 +848,7 @@ class ValidityState;
class VideoPlaybackQuality;
class VideoTrack;
class VideoTrackList;
+class VisibilityStateEntry;
class Window;
class WindowEnvironmentSettingsObject;
class WindowProxy;
diff --git a/Libraries/LibWeb/HTML/VisibilityStateEntry.cpp b/Libraries/LibWeb/HTML/VisibilityStateEntry.cpp
new file mode 100644
index 00000000000..7c739abf3a1
--- /dev/null
+++ b/Libraries/LibWeb/HTML/VisibilityStateEntry.cpp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibGC/Heap.h>
+#include <LibWeb/Bindings/Document.h>
+#include <LibWeb/HTML/VisibilityStateEntry.h>
+#include <LibWeb/PerformanceTimeline/EntryTypes.h>
+
+namespace Web::HTML {
+
+GC_DEFINE_ALLOCATOR(VisibilityStateEntry);
+
+// https://html.spec.whatwg.org/multipage/interaction.html#visibilitystateentry
+VisibilityStateEntry::VisibilityStateEntry(VisibilityState visibility_state, HighResolutionTime::DOMHighResTimeStamp timestamp)
+ // The name getter steps are to return this's visibility state.
+ // The startTime getter steps are to return this's timestamp.
+ // The duration getter steps are to return zero.
+ : PerformanceTimeline::PerformanceEntry(Bindings::idl_enum_to_string(visibility_state), timestamp, 0)
+{
+}
+
+VisibilityStateEntry::~VisibilityStateEntry() = default;
+
+GC::Ref<VisibilityStateEntry> VisibilityStateEntry::create(VisibilityState visibility_state, HighResolutionTime::DOMHighResTimeStamp timestamp)
+{
+ return GC::Heap::the().allocate<VisibilityStateEntry>(visibility_state, timestamp);
+}
+
+// https://html.spec.whatwg.org/multipage/interaction.html#dom-visibilitystateentry-entrytype
+Utf16FlyString const& VisibilityStateEntry::entry_type() const
+{
+ // The entryType getter steps are to return "visibility-state".
+ return PerformanceTimeline::EntryTypes::visibility_state;
+}
+
+}
diff --git a/Libraries/LibWeb/HTML/VisibilityStateEntry.h b/Libraries/LibWeb/HTML/VisibilityStateEntry.h
new file mode 100644
index 00000000000..c7beb9da1e1
--- /dev/null
+++ b/Libraries/LibWeb/HTML/VisibilityStateEntry.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/PerformanceTimeline/PerformanceEntry.h>
+#include <LibWebCommon/HTML/VisibilityState.h>
+
+namespace Web::HTML {
+
+// https://html.spec.whatwg.org/multipage/interaction.html#visibilitystateentry
+class VisibilityStateEntry final : public PerformanceTimeline::PerformanceEntry {
+ WEB_WRAPPABLE(VisibilityStateEntry, PerformanceTimeline::PerformanceEntry);
+ GC_DECLARE_ALLOCATOR(VisibilityStateEntry);
+
+public:
+ virtual ~VisibilityStateEntry() override;
+
+ static GC::Ref<VisibilityStateEntry> create(VisibilityState, HighResolutionTime::DOMHighResTimeStamp timestamp);
+
+ // 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::Yes; }
+
+ // https://w3c.github.io/timing-entrytypes-registry/#dfn-maxbuffersize
+ static Optional<u64> max_buffer_size() { return 50; }
+
+ // 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;
+
+private:
+ VisibilityStateEntry(VisibilityState, HighResolutionTime::DOMHighResTimeStamp timestamp);
+};
+
+}
diff --git a/Libraries/LibWeb/HTML/VisibilityStateEntry.idl b/Libraries/LibWeb/HTML/VisibilityStateEntry.idl
new file mode 100644
index 00000000000..48dfd7d05ff
--- /dev/null
+++ b/Libraries/LibWeb/HTML/VisibilityStateEntry.idl
@@ -0,0 +1,5 @@
+// https://html.spec.whatwg.org/multipage/interaction.html#visibilitystateentry
+[Exposed=Window]
+interface VisibilityStateEntry : PerformanceEntry {
+ [Default] object toJSON();
+};
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
index 11b0aad6b4b..a432ef9f7b5 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
@@ -54,6 +54,7 @@
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/Timer.h>
+#include <LibWeb/HTML/VisibilityStateEntry.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
#include <LibWeb/HTML/WindowProxy.h>
@@ -1140,6 +1141,12 @@ void WindowOrWorkerGlobalScopeMixin::queue_performance_entry(GC::Ref<Performance
// this function to add to the entry buffer, instead queuing the observer task, then adding to the entry
// buffer separately.
+ // OPTIMIZATION: The PerformanceObserver task delivers only what observers have buffered. An entry that no observer
+ // is interested in buffers nothing, so it doesn't queue the task. A document's initial visibility
+ // state entry, e.g., then doesn't queue a task for every new document.
+ if (interested_observers.is_empty())
+ return;
+
// 10. Queue the PerformanceObserver task with relevantGlobal as input.
queue_the_performance_observer_task();
}
diff --git a/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h b/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h
index cdabf8492a6..327db52cf50 100644
--- a/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h
+++ b/Libraries/LibWeb/HighResolutionTime/SupportedPerformanceTypes.h
@@ -28,6 +28,7 @@ inline bool is_supported_for_global(SupportedPerformanceEntryTypeGlobals globals
__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)
+ __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::resource, ResourceTiming::PerformanceResourceTiming, WindowAndWorker) \
+ __ENUMERATE_SUPPORTED_PERFORMANCE_ENTRY_TYPES(PerformanceTimeline::EntryTypes::visibility_state, HTML::VisibilityStateEntry, WindowOnly)
}
diff --git a/Libraries/LibWeb/PerformanceTimeline/EntryTypes.h b/Libraries/LibWeb/PerformanceTimeline/EntryTypes.h
index c502537e9ff..fababeef25c 100644
--- a/Libraries/LibWeb/PerformanceTimeline/EntryTypes.h
+++ b/Libraries/LibWeb/PerformanceTimeline/EntryTypes.h
@@ -22,7 +22,8 @@ namespace Web::PerformanceTimeline::EntryTypes {
__ENUMERATE_PERFORMANCE_TIMELINE_ENTRY_TYPE(measure, "measure") \
__ENUMERATE_PERFORMANCE_TIMELINE_ENTRY_TYPE(navigation, "navigation") \
__ENUMERATE_PERFORMANCE_TIMELINE_ENTRY_TYPE(paint, "paint") \
- __ENUMERATE_PERFORMANCE_TIMELINE_ENTRY_TYPE(resource, "resource")
+ __ENUMERATE_PERFORMANCE_TIMELINE_ENTRY_TYPE(resource, "resource") \
+ __ENUMERATE_PERFORMANCE_TIMELINE_ENTRY_TYPE(visibility_state, "visibility-state")
#define __ENUMERATE_PERFORMANCE_TIMELINE_ENTRY_TYPE(name, type) extern Utf16FlyString const& name;
ENUMERATE_PERFORMANCE_TIMELINE_ENTRY_TYPES
diff --git a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.cpp b/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.cpp
index dd081415937..7e4856a2e25 100644
--- a/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.cpp
+++ b/Libraries/LibWeb/PerformanceTimeline/PerformanceObserver.cpp
@@ -13,6 +13,7 @@
#include <LibWeb/Bindings/PerformanceObserverEntryList.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/HTML/Scripting/Environments.h>
+#include <LibWeb/HTML/VisibilityStateEntry.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
#include <LibWeb/HighResolutionTime/SupportedPerformanceTypes.h>
diff --git a/Libraries/LibWeb/idl_files.cmake b/Libraries/LibWeb/idl_files.cmake
index 664aed601c8..796de4816c2 100644
--- a/Libraries/LibWeb/idl_files.cmake
+++ b/Libraries/LibWeb/idl_files.cmake
@@ -382,6 +382,7 @@ libweb_js_bindings(HTML/VideoFrameRequestCallback)
libweb_js_bindings(HTML/VideoPlaybackQuality)
libweb_js_bindings(HTML/VideoTrack)
libweb_js_bindings(HTML/VideoTrackList)
+libweb_js_bindings(HTML/VisibilityStateEntry)
libweb_js_bindings(HTML/Window)
libweb_js_bindings(HTML/WindowDeprecated)
libweb_js_bindings(HTML/WindowLocalStorage)
diff --git a/Tests/LibWeb/Text/expected/HTML/visibility-state-entry.txt b/Tests/LibWeb/Text/expected/HTML/visibility-state-entry.txt
new file mode 100644
index 00000000000..ea07bca0b27
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/visibility-state-entry.txt
@@ -0,0 +1,9 @@
+Supported: true
+Initial: 1 visible startTime=0 duration=0
+toJSON: {"name":"visible","entryType":"visibility-state","startTime":0,"duration":0}
+After hiding and showing: 3
+VisibilityStateEntry visibility-state hidden startTime>0=true duration=0
+VisibilityStateEntry visibility-state visible startTime>0=true duration=0
+Ordered: true
+Observed: hidden, visible
+Iframe created while hidden: hidden@0
diff --git a/Tests/LibWeb/Text/expected/PerformanceObserver/PerformanceObserver-supportedEntryTypes.txt b/Tests/LibWeb/Text/expected/PerformanceObserver/PerformanceObserver-supportedEntryTypes.txt
index 552e62f252e..f66013cf7d5 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,largest-contentful-paint,mark,measure,navigation,paint,resource
+PerformanceObserver.supportedEntryTypes: event,first-input,largest-contentful-paint,mark,measure,navigation,paint,resource,visibility-state
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 9cecff5d60f..e7fe64baa5e 100644
--- a/Tests/LibWeb/Text/expected/all-window-properties.txt
+++ b/Tests/LibWeb/Text/expected/all-window-properties.txt
@@ -619,6 +619,7 @@ VideoTrack
VideoTrackList
ViewTimeline
ViewTransition
+VisibilityStateEntry
VisualViewport
WaveShaperNode
WeakMap
diff --git a/Tests/LibWeb/Text/input/HTML/visibility-state-entry.html b/Tests/LibWeb/Text/input/HTML/visibility-state-entry.html
new file mode 100644
index 00000000000..e47ce39a227
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/visibility-state-entry.html
@@ -0,0 +1,49 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ function describe(entry) {
+ return `${entry.constructor.name} ${entry.entryType} ${entry.name} startTime>0=${entry.startTime > 0} duration=${entry.duration}`;
+ }
+
+ promiseTest(async () => {
+ println(`Supported: ${PerformanceObserver.supportedEntryTypes.includes("visibility-state")}`);
+
+ let entries = performance.getEntriesByType("visibility-state");
+ println(`Initial: ${entries.length} ${entries[0].name} startTime=${entries[0].startTime} duration=${entries[0].duration}`);
+ println(`toJSON: ${JSON.stringify(entries[0].toJSON())}`);
+
+ const observed = [];
+ let resolveObserved;
+ const observedBoth = new Promise(resolve => (resolveObserved = resolve));
+ const observer = new PerformanceObserver(list => {
+ for (const entry of list.getEntries())
+ observed.push(entry.name);
+ if (observed.length >= 2)
+ resolveObserved();
+ });
+ observer.observe({ type: "visibility-state" });
+
+ await setSystemVisibilityState("hidden");
+ await setSystemVisibilityState("visible");
+
+ entries = performance.getEntriesByType("visibility-state");
+ println(`After hiding and showing: ${entries.length}`);
+ for (const entry of entries.slice(1))
+ println(describe(entry));
+ println(`Ordered: ${entries[1].startTime <= entries[2].startTime}`);
+
+ await observedBoth;
+ println(`Observed: ${observed.join(", ")}`);
+ observer.disconnect();
+
+ await setSystemVisibilityState("hidden");
+ const iframe = document.createElement("iframe");
+ const loaded = new Promise(resolve => iframe.addEventListener("load", resolve));
+ document.body.appendChild(iframe);
+ await loaded;
+ const iframeEntries = iframe.contentWindow.performance.getEntriesByType("visibility-state");
+ println(`Iframe created while hidden: ${iframeEntries.map(entry => `${entry.name}@${entry.startTime}`).join(", ")}`);
+ iframe.remove();
+ await setSystemVisibilityState("visible");
+ });
+</script>