The headless browser for AI agents and web scraping
Batch intersection observer delivery by document
SGavrl8841c919dd74
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 42666227..91491655 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -8620,6 +8620,31 @@ globalThis.NodeFilter = {// element-root, and overflow-ancestor boxes from one prepared layout snapshot.globalThis.__intersectionObservers = [];let _intersectionRenderCheckpointPending = false;+const _intersectionDeliveryObservers = new Set();+let _intersectionDeliveryTaskPending = false;++function _scheduleIntersectionObserverDelivery(observer) {+ if (!observer._connected || !observer._records.length) return;+ _intersectionDeliveryObservers.add(observer);+ if (_intersectionDeliveryTaskPending) return;+ _intersectionDeliveryTaskPending = true;++ // IntersectionObserver has one task source per document. Deliver every+ // observer which became pending during the rendering update from that task;+ // posting one task per observer lets unrelated scheduler work split a single+ // document notification into seconds of staggered framework updates.+ _browserPostedTaskEnqueue(() => {+ _intersectionDeliveryTaskPending = false;+ const pending = [..._intersectionDeliveryObservers];+ _intersectionDeliveryObservers.clear();+ for (const current of pending) {+ if (!current._connected || !current._records.length) continue;+ const records = current.takeRecords();+ try { current._callback(records, current); } catch (e) {}+ }+ }, _schedulerPriorityRank["user-visible"] * 2);+}+function _scheduleIntersectionRenderCheckpoint() {if (!globalThis.__intersectionObservers.some(observer => observer._connected && observer._targets.size,@@ -8762,7 +8787,6 @@ globalThis.IntersectionObserver = class IntersectionObserver {this._previous = new Map();this._records = [];this._connected = true;- this._deliveryPending = false;globalThis.__intersectionObservers.push(this);}_rootBounds(measurements) {@@ -8882,17 +8906,9 @@ globalThis.IntersectionObserver = class IntersectionObserver {this._queueChanged(target, !!forceInitial, root, measurements);}}- if (!this._records.length || this._deliveryPending) return;- this._deliveryPending = true;- // The IntersectionObserver task source delivers after the rendering- // update and its microtask checkpoint. A Promise reaction delivers too- // early and changes takeRecords(), timer, and framework effect ordering.- _browserPostedTaskEnqueue(() => {- this._deliveryPending = false;- if (!this._connected || !this._records.length) return;- const records = this.takeRecords();- try { this._callback(records, this); } catch (e) {}- }, _schedulerPriorityRank["user-visible"] * 2);+ // Delivery remains a task after the rendering update and its microtask+ // checkpoint. The document-level queue batches all pending observers.+ _scheduleIntersectionObserverDelivery(this);}observe(el) {if (!el || this._targets.has(el)) return;@@ -8919,6 +8935,7 @@ globalThis.IntersectionObserver = class IntersectionObserver {this._targets.clear();this._previous.clear();this._records.length = 0;+ _intersectionDeliveryObservers.delete(this);const index = globalThis.__intersectionObservers.indexOf(this);if (index >= 0) globalThis.__intersectionObservers.splice(index, 1);}diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 6543471d..01d28fdc 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -9264,6 +9264,45 @@ mod tests {);}+ #[cfg(feature = "render")]+ #[tokio::test(flavor = "current_thread")]+ async fn intersection_observer_delivers_document_batch_before_callback_posted_tasks() {+ let dom = parse_html(+ r#"<html><body><div id="first"></div><div id="second"></div></body></html>"#,+ );+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(dom);+ rt.run_page_init();+ rt.execute_script(+ "intersection-document-delivery-batch",+ r#"+ globalThis.__intersectionDeliveryOrder = [];+ const first = new IntersectionObserver(() => {+ __intersectionDeliveryOrder.push("first-observer");+ scheduler.postTask(() => {+ __intersectionDeliveryOrder.push("callback-posted-task");+ }, { priority: "user-blocking" });+ });+ const second = new IntersectionObserver(() => {+ __intersectionDeliveryOrder.push("second-observer");+ });+ first.observe(document.getElementById("first"));+ second.observe(document.getElementById("second"));+ "#,+ )+ .unwrap();++ rt.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(+ rt.evaluate("__intersectionDeliveryOrder").unwrap(),+ serde_json::json!([+ "first-observer",+ "second-observer",+ "callback-posted-task",+ ])+ );+ }+#[cfg(feature = "render")]#[tokio::test(flavor = "current_thread")]async fn intersection_observer_element_root_uses_live_padding_box_and_scroll() {@@ -9653,6 +9692,43 @@ mod tests {);}+ #[cfg(feature = "render")]+ #[tokio::test(flavor = "current_thread")]+ async fn intersection_observer_recomputes_after_root_scroll() {+ let dom = parse_html(+ r#"<html style="margin:0"><body style="margin:0">+ <div style="height:150px"></div>+ <div id="target" style="height:20px"></div>+ <div style="height:300px"></div>+ </body></html>"#,+ );+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(dom);+ rt.set_viewport(200.0, 100.0);+ rt.run_page_init();+ rt.execute_script(+ "intersection-root-scroll",+ r#"+ globalThis.__rootScrollIoRecords = [];+ globalThis.__rootScrollIo = new IntersectionObserver(entries => {+ __rootScrollIoRecords.push(...entries.map(entry => [+ entry.isIntersecting,+ Math.round(entry.boundingClientRect.top),+ ]));+ });+ __rootScrollIo.observe(document.getElementById("target"));+ "#,+ )+ .unwrap();+ rt.run_event_loop_bounded(40).await.unwrap();+ rt.evaluate("window.scrollTo(0, 100)").unwrap();+ rt.run_event_loop_bounded(40).await.unwrap();+ assert_eq!(+ rt.evaluate("__rootScrollIoRecords").unwrap(),+ serde_json::json!([[false, 150], [true, 50]])+ );+ }+#[cfg(feature = "render")]#[test]fn scroll_into_view_aligns_the_root_viewport_and_clamps() {