The headless browser for AI agents and web scraping
fix(js): queue details toggle on open changes
lisa03142e0b63f94a1f
diff --git a/crates/obscura-cdp/tests/input_mouse_label_activation.rs b/crates/obscura-cdp/tests/input_mouse_label_activation.rsindex 54029cab..94833f9d 100644--- a/crates/obscura-cdp/tests/input_mouse_label_activation.rs+++ b/crates/obscura-cdp/tests/input_mouse_label_activation.rs@@ -15,7 +15,7 @@ async fn serve_fixture() -> String {let _ = socket.read(&mut buf).await.unwrap();// The labels carry their own boxes so a coordinate click has a target// regardless of inline-wrapper geometry.- let body = r#"<!doctype html><html><head><style>+ let body = r##"<!doctype html><html><head><style>html, body { margin: 0; font: 16px monospace }label, summary { display: block; width: 200px; height: 40px }</style></head><body>@@ -25,6 +25,8 @@ async fn serve_fixture() -> String {<input id="boxc" type="checkbox"><label id="off" for="boxd">d</label><input id="boxd" type="checkbox" disabled><details id="panel"><summary id="summary">More</summary><p>Content</p></details>+ <details id="link-panel"><summary><a id="summary-link" href="#target">Link</a></summary></details>+ <div id="target">Target</div><script>window.events = [];for (const id of ['boxa','boxb','boxc','boxd']) {@@ -34,7 +36,7 @@ async fn serve_fixture() -> String {}}</script>- </body></html>"#;+ </body></html>"##;let response = format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",body.len()@@ -149,6 +151,16 @@ async fn mouse_click_on_summary_toggles_details() {click_element(&mut ctx, 60, &sid, "#summary").await;let closed = evaluate(&mut ctx, 70, "document.getElementById('panel').open", &sid).await;assert_eq!(closed["result"]["value"], false);++ click_element(&mut ctx, 80, &sid, "#summary-link").await;+ let link_state = evaluate(+ &mut ctx,+ 90,+ "[document.getElementById('link-panel').open, location.hash]",+ &sid,+ )+ .await;+ assert_eq!(link_state["result"]["value"], json!([false, "#target"]));}#[tokio::test(flavor = "current_thread")]diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex 8933d8e4..d8f71585 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -3489,18 +3489,12 @@ const _forwardingLabels = new WeakSet();const _TRUSTED_ACTIVATION = Symbol('obscura.trustedActivation');const _pendingDetailsToggles = new WeakMap();-globalThis.__obscura_activateSummary = function(target) {- const summary = target.tagName === 'SUMMARY' ? target : target.closest?.('summary');- if (!summary || summary.parentElement?.tagName !== 'DETAILS') return false;- const interactive = target.closest?.(_INTERACTIVE);- if (interactive && summary.contains(interactive)) return false;- const details = summary.parentElement;- let firstSummary = details.firstElementChild;- while (firstSummary && firstSummary.tagName !== 'SUMMARY') firstSummary = firstSummary.nextElementSibling;- if (firstSummary !== summary) return false;- const oldState = details.open ? 'open' : 'closed';- const newState = details.open ? 'closed' : 'open';- details.open = !details.open;+function _queueDetailsToggle(details, oldOpen) {+ if (details.localName !== 'details') return;+ const newOpen = details.hasAttribute('open');+ if (oldOpen === newOpen) return;+ const oldState = oldOpen ? 'open' : 'closed';+ const newState = newOpen ? 'open' : 'closed';const pending = _pendingDetailsToggles.get(details);if (pending) {pending.newState = newState;@@ -3512,6 +3506,18 @@ globalThis.__obscura_activateSummary = function(target) {details.dispatchEvent(new ToggleEvent('toggle', states));}, 0);}+}++globalThis.__obscura_activateSummary = function(target) {+ const summary = target.tagName === 'SUMMARY' ? target : target.closest?.('summary');+ if (!summary || summary.parentElement?.tagName !== 'DETAILS') return false;+ const interactive = target.closest?.(_INTERACTIVE);+ if (interactive && summary.contains(interactive)) return false;+ const details = summary.parentElement;+ let firstSummary = details.firstElementChild;+ while (firstSummary && firstSummary.tagName !== 'SUMMARY') firstSummary = firstSummary.nextElementSibling;+ if (firstSummary !== summary) return false;+ details.open = !details.open;return true;};@@ -3567,7 +3573,7 @@ globalThis.__obscura_interactiveHost = function(el) {};// Frozen so page script can neither replace the helpers to suppress or fake// label activation, nor delete them and make later clicks throw.-for (const _name of ['__obscura_activateLabel', '__obscura_isDisabled',+for (const _name of ['__obscura_activateLabel', '__obscura_activateSummary', '__obscura_isDisabled','__obscura_labeledControl', '__obscura_interactiveHost','__obscura_inputChecked', '__obscura_setInputChecked','__obscura_inputIndeterminate', '__obscura_setInputIndeterminate']) {@@ -4276,6 +4282,9 @@ class Element extends Node {}setAttribute(n, v) {n = _htmlAttrName(this, n);+ const detailsWasOpen = this.localName === 'details' && n === 'open'+ ? this.hasAttribute('open')+ : null;const popoverPrev = (n === "popover") ? this.popover : undefined;const previousWindowName = (n === "id" || n === "name")? this.getAttribute(n)@@ -4283,6 +4292,7 @@ class Element extends Node {const observedOldValue = _attributeOldValuesWanted() ? this.getAttribute(n) : null;const value = String(v);_dom("set_attribute", this._nid, n + "\0" + value);+ if (detailsWasOpen !== null) _queueDetailsToggle(this, detailsWasOpen);if (n === "src" && this.localName === "iframe" && !this.hasAttribute('srcdoc')) {if (value && value !== "about:blank") this._loadIframeSrc(value);else this._resetIframeFrame();@@ -4324,8 +4334,12 @@ class Element extends Node {const value = String(v);_ns_validateQualifiedName(ns, n);const localName = n.includes(":") ? n.slice(n.indexOf(":") + 1) : n;+ const detailsWasOpen = this.localName === 'details' && ns === '' && localName === 'open'+ ? this.hasAttribute('open')+ : null;const observedOldValue = _attributeOldValuesWanted() ? this.getAttributeNS(ns, localName) : null;_dom("set_attribute_ns", this._nid, ns + "\0" + n + "\0" + value);+ if (detailsWasOpen !== null) _queueDetailsToggle(this, detailsWasOpen);if (_hasMutationObservers()) _queueAttributeMutationRecord(this, localName, ns || null, observedOldValue);// Namespace-aware writes can replace an attribute by namespace/local name// while changing its qualified name. Fall back to native reads afterwards@@ -4337,12 +4351,16 @@ class Element extends Node {removeAttribute(n) {n = _htmlAttrName(this, n);if (n === 'srcdoc' && this.localName === 'iframe' && !this.hasAttribute(n)) return;+ const detailsWasOpen = this.localName === 'details' && n === 'open'+ ? this.hasAttribute('open')+ : null;const popoverPrev = (n === "popover") ? this.popover : undefined;const previousWindowName = (n === "id" || n === "name")? this.getAttribute(n): null;const observedOldValue = _hasMutationObservers() ? this.getAttribute(n) : null;_dom("remove_attribute", this._nid, n);+ if (detailsWasOpen !== null) _queueDetailsToggle(this, detailsWasOpen);if (observedOldValue !== null) _queueAttributeMutationRecord(this, n, null, observedOldValue);if (this._nullNamespaceAttrs instanceof Map) {this._nullNamespaceAttrs.delete(n);@@ -4373,9 +4391,13 @@ class Element extends Node {removeAttributeNS(ns, n) {ns = String(ns == null ? "" : ns);n = String(n);+ const detailsWasOpen = this.localName === 'details' && ns === '' && n === 'open'+ ? this.hasAttribute('open')+ : null;if (ns === '' && n === 'srcdoc' && this.localName === 'iframe' && this.getAttributeNS(ns, n) === null) return;const observedOldValue = _hasMutationObservers() ? this.getAttributeNS(ns, n) : null;_dom("remove_attribute_ns", this._nid, ns + "\0" + n);+ if (detailsWasOpen !== null) _queueDetailsToggle(this, detailsWasOpen);if (observedOldValue !== null) _queueAttributeMutationRecord(this, n, ns || null, observedOldValue);this._nullNamespaceAttrs = null;if (ns === '' && n === 'srcdoc' && this.localName === 'iframe') this._loadIframeSrc(this.getAttribute('src') || 'about:blank');diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 6ab0f3ab..fa297ff4 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -18768,6 +18768,64 @@ mod tests {);}+ #[tokio::test(flavor = "current_thread")]+ async fn test_details_toggle_tracks_open_attribute_changes() {+ let mut rt = setup_runtime(r#"<details id="panel"><summary>More</summary></details>"#);+ let protected = rt+ .evaluate(+ r#"+ const helper = globalThis.__obscura_activateSummary;+ globalThis.toggleStates = [];+ document.getElementById('panel').addEventListener('toggle', event => {+ toggleStates.push([event.oldState, event.newState]);+ });+ return [!Reflect.set(globalThis, '__obscura_activateSummary', () => false),+ !Reflect.deleteProperty(globalThis, '__obscura_activateSummary'),+ globalThis.__obscura_activateSummary === helper];+ "#,+ )+ .unwrap();+ assert_eq!(protected, serde_json::json!([true, true, true]));++ rt.evaluate("document.getElementById('panel').open = true")+ .unwrap();+ rt.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(+ rt.evaluate("toggleStates").unwrap(),+ serde_json::json!([["closed", "open"]])+ );++ rt.evaluate("document.getElementById('panel').setAttribute('open', '')")+ .unwrap();+ rt.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(+ rt.evaluate("toggleStates").unwrap(),+ serde_json::json!([["closed", "open"]])+ );++ rt.evaluate("document.getElementById('panel').toggleAttribute('open')")+ .unwrap();+ rt.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(+ rt.evaluate("toggleStates").unwrap(),+ serde_json::json!([["closed", "open"], ["open", "closed"]])+ );++ rt.evaluate(+ "const panel = document.getElementById('panel'); panel.setAttributeNS(null, 'open', ''); panel.removeAttributeNS(null, 'open')",+ )+ .unwrap();+ rt.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(+ rt.evaluate("toggleStates").unwrap(),+ serde_json::json!([+ ["closed", "open"],+ ["open", "closed"],+ ["closed", "closed"]+ ])+ );+ }+#[test]fn test_label_click_activates_its_labeled_control() {let mut rt = setup_runtime(