Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(observers): preserve intersection target observation order

ldm0f7d21c8c711a
diff --git a/moli-renderer-v8/src/observer_runtime/mod.rs b/moli-renderer-v8/src/observer_runtime/mod.rs
index fd3daaf23..9526a9948 100644
--- a/moli-renderer-v8/src/observer_runtime/mod.rs
+++ b/moli-renderer-v8/src/observer_runtime/mod.rs
@@ -31,6 +31,7 @@ use crate::dom::native::{
DomHost, DomMutationEffects, DomMutationRecord, DomMutationRecordKind, NativeNodeId,
};
use crate::webidl;
+use indexmap::IndexSet;
use moli_css_parse::{normalize_root_margin, root_margin_components};
use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};
@@ -356,7 +357,8 @@ enum QueuedMutationRecordKind {
struct IntersectionObserverState {
observer: v8::Global<v8::Object>,
callback: callback::ObserverCallback,
- observed_targets: HashSet<NativeNodeId>,
+ // Preserve observation order; duplicate observe() leaves the position unchanged.
+ observed_targets: IndexSet<NativeNodeId>,
queued_entries: Vec<QueuedIntersectionEntry>,
last_reported_entries: HashMap<NativeNodeId, LastReportedIntersection>,
options: IntersectionObserverOptions,
@@ -660,7 +662,7 @@ impl ObserverStore {
IntersectionObserverState {
observer: v8::Global::new(scope, observer),
callback,
- observed_targets: HashSet::new(),
+ observed_targets: IndexSet::new(),
queued_entries: Vec::new(),
last_reported_entries: HashMap::new(),
options,
@@ -700,7 +702,7 @@ impl ObserverStore {
let Some(state) = self.intersection_observers.get_mut(&id) else {
return;
};
- state.observed_targets.remove(&target);
+ state.observed_targets.shift_remove(&target);
state
.queued_entries
.retain(|queued| queued.target != target);
diff --git a/moli-renderer-v8/src/script_vm/tests/intersection_target_order.rs b/moli-renderer-v8/src/script_vm/tests/intersection_target_order.rs
new file mode 100644
index 000000000..0219d2614
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/intersection_target_order.rs
@@ -0,0 +1,28 @@
+use super::*;
+
+#[tokio::test(flavor = "current_thread")]
+async fn intersection_observer_preserves_target_observation_order() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ let mut vm = new_storage_page_task_executor_test_vm("https://intersection-queues.test/");
+ let count: usize = vm
+ .eval(include_str!(
+ "../../../tests/fixtures/intersection-target-order.js"
+ ))
+ .unwrap()
+ .parse()
+ .unwrap();
+ assert_eq!(count, 3);
+ for index in 0..count {
+ let name = vm
+ .eval(&format!("__intersectionQueues.start({index})"))
+ .unwrap();
+ vm.advance_timers_until_deadline_for_test(&loader)
+ .await
+ .unwrap();
+ assert_eq!(
+ vm.eval("__intersectionQueues.result").unwrap(),
+ vm.eval("__intersectionQueues.expected").unwrap(),
+ "{name}"
+ );
+ }
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index a8082bc3e..2ade78dee 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -2162,3 +2162,5 @@ mod extracted;
mod navigation_timing_inheritance;
mod response_blob_mime;
+
+mod intersection_target_order;
diff --git a/moli-renderer-v8/tests/fixtures/intersection-target-order.js b/moli-renderer-v8/tests/fixtures/intersection-target-order.js
new file mode 100644
index 000000000..942838f93
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/intersection-target-order.js
@@ -0,0 +1,42 @@
+(() => {
+ const order = [8, 3, 10, 0, 9, 2, 11, 1, 6, 4, 7, 5];
+ const cases = [
+ ['duplicate observe and DOM reordering preserve observation order', '8,3,10,0,9,2,11,1,6,4,7,5'],
+ ['unobserve preserves survivors and re-observe appends targets', '8,10,0,9,2,11,1,4,7,5,3,6'],
+ ['disconnect clears the prior order before re-observation', '6,8,0'],
+ ];
+ globalThis.__intersectionQueues = {
+ result: null,
+ expected: null,
+ start(index) {
+ document.body.replaceChildren();
+ this.result = null;
+ this.expected = cases[index][1];
+ const targets = Array.from({length: 12}, (_, index) => {
+ const target = document.body.appendChild(document.createElement('div'));
+ target.id = String(index);
+ target.style.cssText = 'width:20px;height:20px';
+ return target;
+ });
+ const observer = new IntersectionObserver(entries => {
+ const batch = entries.map(entry => entry.target.id).join(',');
+ this.result = this.result === null ? batch : this.result + '|' + batch;
+ observer.disconnect();
+ });
+ order.forEach(index => observer.observe(targets[index]));
+ observer.observe(targets[3]);
+ if (index === 1) {
+ observer.unobserve(targets[3]);
+ observer.unobserve(targets[6]);
+ observer.observe(targets[3]);
+ observer.observe(targets[6]);
+ } else if (index === 2) {
+ observer.disconnect();
+ [6, 8, 0].forEach(index => observer.observe(targets[index]));
+ }
+ document.body.prepend(targets[5]);
+ return cases[index][0];
+ },
+ };
+ return cases.length;
+})();