Skip to content

The headless browser for AI agents and web scraping

fix(js,cdp): implement label activation behaviour

Vrejf968163d82c53
diff --git a/crates/obscura-cdp/src/domains/input.rs b/crates/obscura-cdp/src/domains/input.rs
index ca8e2f38..f2d5bd13 100644
--- a/crates/obscura-cdp/src/domains/input.rs
+++ b/crates/obscura-cdp/src/domains/input.rs
@@ -157,6 +157,7 @@ pub async fn handle(
if (!clickTarget) return;\
var tag = clickTarget.tagName;\
var type = (clickTarget.getAttribute && clickTarget.getAttribute('type') || '').toLowerCase();\
+ if (globalThis.__obscura_isDisabled(clickTarget)) return;\
var checkable = tag === 'INPUT' && (type === 'checkbox' || type === 'radio');\
var oldChecked = checkable ? !!clickTarget.checked : false;\
var radioStates = null;\
@@ -189,6 +190,12 @@ pub async fn handle(
try {{ clickTarget.dispatchEvent(globalThis.__obscura_markTrusted(new Event('change', {{bubbles:true}}))); }} catch(e) {{}}\
return;\
}}\
+ var labelHost = tag === 'LABEL' ? clickTarget : (clickTarget.closest ? clickTarget.closest('label') : null);\
+ var interactiveHost = globalThis.__obscura_interactiveHost(clickTarget);\
+ if (labelHost && !(interactiveHost && labelHost.contains(interactiveHost))) {{\
+ var ctl = globalThis.__obscura_labeledControl(labelHost);\
+ if (ctl && ctl !== clickTarget && globalThis.__obscura_activateLabel(labelHost, ctl, true)) {{ return; }}\
+ }}\
var link = clickTarget.closest ? clickTarget.closest('a[href]') : null;\
if (!link && tag === 'A' && clickTarget.getAttribute('href')) link = clickTarget;\
if (link) {{\
diff --git a/crates/obscura-cdp/tests/input_mouse_label_activation.rs b/crates/obscura-cdp/tests/input_mouse_label_activation.rs
new file mode 100644
index 00000000..99604169
--- /dev/null
+++ b/crates/obscura-cdp/tests/input_mouse_label_activation.rs
@@ -0,0 +1,158 @@
+#![cfg(feature = "render")]
+
+use obscura_cdp::dispatch::{dispatch, CdpContext};
+use obscura_cdp::types::CdpRequest;
+use serde_json::{json, Value};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+
+async fn serve_fixture() -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.unwrap();
+ let mut buf = [0u8; 2048];
+ 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>
+ html, body { margin: 0; font: 16px monospace }
+ label { display: block; width: 200px; height: 40px }
+ </style></head><body>
+ <label id="explicit" for="boxa">a</label><input id="boxa" type="checkbox">
+ <label id="implicit">b <input id="boxb" type="checkbox"></label>
+ <label id="deep" for="boxc"><span><b id="deep-text">c</b></span></label>
+ <input id="boxc" type="checkbox">
+ <label id="off" for="boxd">d</label><input id="boxd" type="checkbox" disabled>
+ <script>
+ window.events = [];
+ for (const id of ['boxa','boxb','boxc','boxd']) {
+ const el = document.getElementById(id);
+ for (const t of ['click','input','change']) {
+ el.addEventListener(t, e => window.events.push(id + ':' + t + ':' + e.isTrusted));
+ }
+ }
+ </script>
+ </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()
+ );
+ let _ = socket.write_all(response.as_bytes()).await;
+ });
+ format!("http://{addr}/")
+}
+
+async fn cdp(ctx: &mut CdpContext, id: u64, method: &str, params: Value, sid: &str) -> Value {
+ let response = dispatch(
+ &CdpRequest {
+ id,
+ method: method.to_string(),
+ params,
+ session_id: Some(sid.to_string()),
+ },
+ ctx,
+ )
+ .await;
+ assert!(response.error.is_none(), "CDP {method} failed: {:?}", response.error);
+ response.result.unwrap_or_else(|| json!({}))
+}
+
+async fn evaluate(ctx: &mut CdpContext, id: u64, expression: &str, sid: &str) -> Value {
+ cdp(
+ ctx,
+ id,
+ "Runtime.evaluate",
+ json!({"expression": expression, "returnByValue": true, "awaitPromise": true}),
+ sid,
+ )
+ .await
+}
+
+async fn setup() -> (CdpContext, String) {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let url = serve_fixture().await;
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let sid = "label-activation-session";
+ ctx.sessions.insert(sid.to_string(), page_id);
+ cdp(&mut ctx, 1, "Page.navigate", json!({"url": url, "waitUntil": "load"}), sid).await;
+ (ctx, sid.to_string())
+}
+
+/// Click the centre of `selector` the way a real pointer would.
+async fn click_element(ctx: &mut CdpContext, id: u64, sid: &str, selector: &str) {
+ let rect = evaluate(
+ ctx,
+ id,
+ &format!(
+ "JSON.stringify(document.querySelector('{selector}').getBoundingClientRect().toJSON())"
+ ),
+ sid,
+ )
+ .await;
+ let rect: Value = serde_json::from_str(rect["result"]["value"].as_str().unwrap()).unwrap();
+ let x = rect["x"].as_f64().unwrap() + rect["width"].as_f64().unwrap() / 2.0;
+ let y = rect["y"].as_f64().unwrap() + rect["height"].as_f64().unwrap() / 2.0;
+ for kind in ["mousePressed", "mouseReleased"] {
+ cdp(
+ ctx,
+ id + 1,
+ "Input.dispatchMouseEvent",
+ json!({"type": kind, "x": x, "y": y, "button": "left", "clickCount": 1}),
+ sid,
+ )
+ .await;
+ }
+}
+
+async fn state(ctx: &mut CdpContext, id: u64, sid: &str) -> Value {
+ let result = evaluate(
+ ctx,
+ id,
+ r#"JSON.stringify({
+ a: document.getElementById('boxa').checked,
+ b: document.getElementById('boxb').checked,
+ c: document.getElementById('boxc').checked,
+ d: document.getElementById('boxd').checked,
+ events: window.events.join(',')
+ })"#,
+ sid,
+ )
+ .await;
+ serde_json::from_str(result["result"]["value"].as_str().unwrap()).unwrap()
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn mouse_click_on_a_label_activates_its_control() {
+ let (mut ctx, sid) = setup().await;
+ click_element(&mut ctx, 10, &sid, "#explicit").await;
+ click_element(&mut ctx, 20, &sid, "#implicit").await;
+ let state = state(&mut ctx, 30, &sid).await;
+ assert_eq!(state["a"], true, "explicit for= label: {state}");
+ assert_eq!(state["b"], true, "implicit nested label: {state}");
+ assert_eq!(
+ state["events"],
+ "boxa:click:true,boxa:input:true,boxa:change:true,\
+ boxb:click:true,boxb:input:true,boxb:change:true",
+ "each control fires click, input, change once, in order: {state}"
+ );
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn mouse_click_deep_inside_a_label_activates_its_control() {
+ let (mut ctx, sid) = setup().await;
+ click_element(&mut ctx, 10, &sid, "#deep-text").await;
+ let state = state(&mut ctx, 20, &sid).await;
+ assert_eq!(state["c"], true, "click on a nested element resolves its label: {state}");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn mouse_click_on_a_label_for_a_disabled_control_does_nothing() {
+ let (mut ctx, sid) = setup().await;
+ click_element(&mut ctx, 10, &sid, "#off").await;
+ click_element(&mut ctx, 20, &sid, "#boxd").await;
+ let state = state(&mut ctx, 30, &sid).await;
+ assert_eq!(state["d"], false, "disabled control must not toggle: {state}");
+ assert_eq!(state["events"], "", "disabled control must dispatch nothing: {state}");
+}
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index d7e69040..66eda4ea 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -19,7 +19,8 @@
'__obscura_frameId', '__obscura_parentFrameId', '__obscura_frameWindows',
'__obscura_frameObjects', '__obscura_frameElements', '__obscura_deliverMessage',
'__obscura_liveFrameIds', '__obscura_forgetFrame',
- '__obscura_registerLinkedStylesheet',
+ '__obscura_registerLinkedStylesheet', '__obscura_activateLabel',
+ '__obscura_isDisabled', '__obscura_labeledControl', '__obscura_interactiveHost',
'__markParserScripts', '__obscura_hasPendingDynamicScripts',
'__obscura_hasPendingLoadDelayingScripts',
'__obscura_nextPendingTimeoutDelay',
@@ -2576,6 +2577,107 @@ function _htmlAttrName(el, n) {
// A submit button per the HTML spec: a <button> whose type is submit — the
// default, including when the type attribute is missing or invalid — or an
// <input> of type submit/image. Used to validate requestSubmit's submitter.
+// The HTML "labeled control" of a <label>: the element referenced by its `for`
+// attribute, or the first labelable descendant. Labelable elements per spec are
+// button, input (excluding type=hidden), meter, output, progress, select,
+// textarea.
+const _LABELABLE = 'button,input:not([type=hidden]),meter,output,progress,select,textarea';
+function _labeledControl(label) {
+ if (!label || label.tagName !== 'LABEL') return null;
+ // A present `for` attribute means association by ID only; an empty value
+ // associates nothing (no fallback to a descendant).
+ const forId = label.getAttribute ? label.getAttribute('for') : null;
+ if (forId !== null && forId !== undefined) {
+ if (forId === '') return null;
+ const doc = label.ownerDocument || globalThis.document;
+ const el = doc && doc.getElementById ? doc.getElementById(forId) : null;
+ if (!el) return null;
+ return el.matches && el.matches(_LABELABLE) ? el : null;
+ }
+ return label.querySelector ? label.querySelector(_LABELABLE) : null;
+}
+
+// Run a label's activation behaviour once, and report whether it ran. The set
+// of labels currently forwarding is closure-private, so a control that clicks
+// its own label from a click handler cannot recurse and page script can neither
+// read nor forge the state. Marking the label itself would leave an enumerable
+// property on a DOM node. The CDP click path shares this guard through the
+// non-enumerable __obscura_activateLabel helper, so both click paths apply the
+// same rule.
+// Interactive content inside a label has its own activation behaviour and
+// swallows the label's, so only a click landing on ordinary content forwards.
+// This is the HTML interactive-content set, which is not the labelable set:
+// meter, output and progress are labelable but inert, while an <a> counts only
+// with an href.
+const _INTERACTIVE = 'a[href],audio[controls],button,details,embed,iframe,'
+ + 'img[usemap],input:not([type=hidden]),select,textarea,video[controls]';
+
+const _forwardingLabels = new WeakSet();
+// Passed to click() only by label activation on behalf of a real input event,
+// so the forwarded control events keep the trustedness of the click that
+// caused them, as they do in a real browser. The symbol itself is
+// closure-private, so click() cannot be called with it directly, but
+// __obscura_activateLabel below will supply it on request, exactly as
+// __obscura_markTrusted already does for any event.
+const _TRUSTED_ACTIVATION = Symbol('obscura.trustedActivation');
+
+// Only these elements can be actually disabled. A `disabled` attribute on
+// anything else, which component libraries do put on plain <div>s, has no
+// effect on event dispatch.
+const _DISABLEABLE = 'button,input,select,textarea,optgroup,option,fieldset';
+// Of those, only the listed form-associated ones inherit disabled from an
+// ancestor <fieldset>.
+const _FIELDSET_DISABLEABLE = 'button,input,select,textarea';
+
+// Disabled per the HTML spec: the element's own attribute, or any disabled
+// <fieldset> ancestor. Walking every ancestor rather than the nearest one
+// matters because the exemption is narrow: only the descendants of a disabled
+// fieldset's *first <legend> child* escape, so a control can sit in an inner
+// fieldset's legend and still be disabled by an outer fieldset. Checking the
+// first legend child, not the first legend descendant, keeps a legend wrapped
+// in a div from granting the exemption.
+function _isActuallyDisabled(el) {
+ if (!el || !el.matches || !el.matches(_DISABLEABLE)) return false;
+ if (el.disabled || (el.hasAttribute && el.hasAttribute('disabled'))) return true;
+ if (!el.matches(_FIELDSET_DISABLEABLE)) return false;
+ let child = el;
+ let parent = el.parentElement;
+ while (parent) {
+ if (parent.tagName === 'FIELDSET' && parent.hasAttribute('disabled')) {
+ let firstLegend = null;
+ for (let c = parent.firstElementChild; c; c = c.nextElementSibling) {
+ if (c.tagName === 'LEGEND') { firstLegend = c; break; }
+ }
+ if (child !== firstLegend) return true;
+ }
+ child = parent;
+ parent = parent.parentElement;
+ }
+ return false;
+}
+
+globalThis.__obscura_activateLabel = function(label, control, trusted) {
+ if (!label || !control || _forwardingLabels.has(label)) return false;
+ if (_isActuallyDisabled(control) || typeof control.click !== 'function') return false;
+ _forwardingLabels.add(label);
+ try { control.click(trusted ? _TRUSTED_ACTIVATION : undefined); }
+ finally { _forwardingLabels.delete(label); }
+ return true;
+};
+// The CDP click path runs its own JS snippet, so it reaches the same rules
+// through these helpers rather than restating the selectors.
+globalThis.__obscura_isDisabled = function(el) { return _isActuallyDisabled(el); };
+globalThis.__obscura_labeledControl = function(label) { return _labeledControl(label); };
+globalThis.__obscura_interactiveHost = function(el) {
+ return el && el.closest ? el.closest(_INTERACTIVE) : null;
+};
+// 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',
+ '__obscura_labeledControl', '__obscura_interactiveHost']) {
+ Object.defineProperty(globalThis, _name, { writable: false, configurable: false });
+}
+
function _isSubmitButton(el) {
if (!el || typeof el.localName !== "string") return false;
const type = ((el.getAttribute && el.getAttribute("type")) || "").toLowerCase();
@@ -3436,7 +3538,74 @@ class Element extends Node {
return cache[name];
}
click() {
- const cancelled = !this.dispatchEvent(new MouseEvent("click", {bubbles: true, cancelable: true}));
+ // A label activating this control on behalf of a real input event passes a
+ // private token so the forwarded events stay trusted. Read from arguments
+ // to keep click.length at 0, as in a real browser.
+ const _trusted = arguments[0] === _TRUSTED_ACTIVATION;
+ // Pre-click activation steps (HTML spec): a checkbox/radio flips BEFORE the
+ // click event dispatches, so listeners observe the new state, and the change
+ // is reverted if the event is cancelled. This mirrors the CDP mouse path in
+ // obscura-cdp/src/domains/input.rs, which already implements it; without it
+ // el.click() dispatched an event but never toggled the control.
+ const _tag = this.tagName;
+ const _type = ((this.getAttribute && this.getAttribute('type')) || '').toLowerCase();
+ const _checkable = _tag === 'INPUT' && (_type === 'checkbox' || _type === 'radio')
+ && !_isActuallyDisabled(this);
+ // A disabled form control has no activation behaviour and dispatches no
+ // click event at all.
+ if (_isActuallyDisabled(this) && _tag !== 'LABEL') {
+ return;
+ }
+ let _oldChecked = false, _radioStates = null;
+ if (_checkable) {
+ _oldChecked = !!this.checked;
+ if (_type === 'radio') {
+ const _name = this.getAttribute('name') || '';
+ if (_name) {
+ _radioStates = [];
+ const _all = (this.ownerDocument || globalThis.document).querySelectorAll('input');
+ for (let i = 0; i < _all.length; i++) {
+ const r = _all[i];
+ if (((r.getAttribute('type') || '').toLowerCase()) !== 'radio') continue;
+ if ((r.getAttribute('name') || '') !== _name || r.form !== this.form) continue;
+ _radioStates.push([r, !!r.checked]);
+ if (r !== this) r.checked = false;
+ }
+ }
+ this.checked = true;
+ } else {
+ this.checked = !_oldChecked;
+ }
+ }
+ const _clickEvent = new MouseEvent("click", {bubbles: true, cancelable: true});
+ if (_trusted) globalThis.__obscura_markTrusted(_clickEvent);
+ const cancelled = !this.dispatchEvent(_clickEvent);
+ if (cancelled) {
+ if (_radioStates) { for (let i = 0; i < _radioStates.length; i++) _radioStates[i][0].checked = _radioStates[i][1]; }
+ else if (_checkable) this.checked = _oldChecked;
+ return;
+ }
+ if (_checkable && this.checked !== _oldChecked) {
+ for (const _type of ['input', 'change']) {
+ const _e = new Event(_type, {bubbles: true});
+ if (_trusted) globalThis.__obscura_markTrusted(_e);
+ try { this.dispatchEvent(_e); } catch (e) {}
+ }
+ return;
+ }
+ // Label activation behaviour (HTML spec): activating a label runs a
+ // synthetic click on its labeled control. The re-entrancy guard stops a
+ // control nested inside its own label from bouncing the click back.
+ const _label = _tag === 'LABEL'
+ ? this
+ : (this.closest && !this.matches(_INTERACTIVE) ? this.closest('label') : null);
+ if (_label && !(this.closest && this.closest(_INTERACTIVE) &&
+ _label.contains(this.closest(_INTERACTIVE)))) {
+ const control = _labeledControl(_label);
+ if (control && control !== this && globalThis.__obscura_activateLabel(_label, control)) {
+ return;
+ }
+ }
if (!cancelled) {
const link = this.tagName === 'A' ? this : (this.closest ? this.closest('a[href]') : null);
if (link) {
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index f36f742e..9e7aa245 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -13086,6 +13086,259 @@ mod tests {
assert_eq!(result, serde_json::json!("yes"));
}
+ #[test]
+ fn test_label_click_activates_its_labeled_control() {
+ let mut rt = setup_runtime(
+ r#"<label id="explicit" for="a">a</label><input type="checkbox" id="a">
+ <label id="implicit">b <input type="checkbox" id="b"></label>"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ const ids = ['explicit', 'implicit'];
+ for (const id of ids) { document.getElementById(id).click(); }
+ return [document.getElementById('a').checked, document.getElementById('b').checked];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!([true, true]));
+ }
+
+ #[test]
+ fn test_label_click_honors_the_association_rules() {
+ // A present `for` associates by id alone: an empty value associates
+ // nothing and must not fall back to the nested control, and a dangling
+ // id activates nothing. A disabled control has no activation behavior.
+ let mut rt = setup_runtime(
+ r#"<label id="empty" for="">a <input type="checkbox" id="a"></label>
+ <label id="dangling" for="missing">b</label><input type="checkbox" id="b">
+ <label id="disabled" for="c">c</label><input type="checkbox" id="c" disabled>
+ <label id="both" for="d">d <input type="checkbox" id="e"></label>
+ <input type="checkbox" id="d">"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ for (const id of ['empty', 'dangling', 'disabled', 'both']) {
+ document.getElementById(id).click();
+ }
+ return ['a', 'b', 'c', 'd', 'e'].map(id => document.getElementById(id).checked);
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([false, false, false, true, false])
+ );
+ }
+
+ #[test]
+ fn test_label_activation_does_not_double_fire_or_recurse() {
+ // Clicking the control inside its own label toggles once, and a click
+ // handler that clicks that label back cannot re-enter the forwarding.
+ let mut rt = setup_runtime(
+ r#"<label id="wrapper"><input type="checkbox" id="nested"></label>
+ <label id="host" for="reentrant">r</label>
+ <input type="checkbox" id="reentrant">"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ const reentrant = document.getElementById('reentrant');
+ document.getElementById('nested').click();
+ let bounces = 0;
+ reentrant.addEventListener('click', () => {
+ if (bounces++ < 1) { document.getElementById('host').click(); }
+ });
+ document.getElementById('host').click();
+ return [document.getElementById('nested').checked, reentrant.checked, bounces];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!([true, true, 1]));
+ }
+
+ #[test]
+ fn test_click_respects_disabled_controls_and_interactive_content() {
+ // A disabled control has no activation behaviour, whether it is clicked
+ // directly, reached through its label, or disabled by an ancestor
+ // fieldset. Interactive content inside a label swallows the label's
+ // activation, but an <a> without href is not interactive content.
+ let mut rt = setup_runtime(
+ r#"<input type="checkbox" id="direct" disabled>
+ <fieldset disabled><label id="in-set" for="set-box">s</label>
+ <input type="checkbox" id="set-box"></fieldset>
+ <label id="link"><a href="/x"><span id="in-link">go</span></a>
+ <input type="checkbox" id="link-box"></label>
+ <label id="plain"><a><span id="in-plain">go</span></a>
+ <input type="checkbox" id="plain-box"></label>"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ const ids = ['direct', 'in-set', 'in-link', 'in-plain'];
+ for (const id of ids) { document.getElementById(id).click(); }
+ return ['direct', 'set-box', 'link-box', 'plain-box']
+ .map(id => document.getElementById(id).checked);
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!([false, false, false, true]));
+ }
+
+ #[test]
+ fn test_disabled_only_applies_to_disableable_elements() {
+ // A `disabled` attribute is meaningless on anything that cannot be
+ // disabled, and only listed form controls inherit it from a fieldset.
+ // Component libraries do put `disabled` on plain <div>s, so treating
+ // that as disabled would silently stop their clicks.
+ let mut rt = setup_runtime(
+ r#"<div id="plain" disabled>x</div>
+ <fieldset disabled><a id="link" href="x">l</a>
+ <input type="checkbox" id="control"></fieldset>"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ const seen = [];
+ for (const id of ['plain', 'link']) {
+ const el = document.getElementById(id);
+ el.addEventListener('click', e => { seen.push(id); e.preventDefault(); });
+ el.click();
+ }
+ document.getElementById('control').click();
+ return [seen.join(','), document.getElementById('control').checked];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!(["plain,link", false]));
+ }
+
+ #[test]
+ fn test_label_forwarding_uses_interactive_content_not_labelable() {
+ // meter, output and progress are labelable but not interactive, so a
+ // click on one still activates the label. An <a> counts only with href.
+ let mut rt = setup_runtime(
+ r#"<label id="l1" for="c1"><output id="o">v</output></label>
+ <input type="checkbox" id="c1">
+ <label id="l2" for="c2"><a id="bare">t</a></label>
+ <input type="checkbox" id="c2">
+ <label id="l3" for="c3"><a id="linked" href="x">t</a></label>
+ <input type="checkbox" id="c3">
+ <label id="l4" for="c4"><button id="btn" type="button">b</button></label>
+ <input type="checkbox" id="c4">"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ const ids = ['o', 'bare', 'linked', 'btn'];
+ for (const id of ids) { document.getElementById(id).click(); }
+ return ['c1', 'c2', 'c3', 'c4'].map(id => document.getElementById(id).checked);
+ "#,
+ )
+ .unwrap();
+ assert_eq!(result, serde_json::json!([true, true, false, false]));
+ }
+
+ #[test]
+ fn test_radio_activation_moves_the_checked_peer_and_reverts_on_cancel() {
+ let mut rt = setup_runtime(
+ r#"<form><label id="pick" for="b">b</label>
+ <input type="radio" name="g" id="a" checked>
+ <input type="radio" name="g" id="b"></form>
+ <form><label id="veto" for="d">d</label>
+ <input type="radio" name="h" id="c" checked>
+ <input type="radio" name="h" id="d"></form>"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ const seen = [];
+ document.getElementById('b').addEventListener('change', () => seen.push('change'));
+ document.getElementById('pick').click();
+ document.getElementById('d').addEventListener('click', e => e.preventDefault());
+ document.getElementById('veto').click();
+ return [
+ document.getElementById('a').checked, document.getElementById('b').checked,
+ document.getElementById('c').checked, document.getElementById('d').checked,
+ seen.join(','),
+ ];
+ "#,
+ )
+ .unwrap();
+ // Activating b unchecks its peer a; the cancelled activation of d
+ // restores c.
+ assert_eq!(
+ result,
+ serde_json::json!([false, true, true, false, "change"])
+ );
+ }
+
+ #[test]
+ fn test_disabled_fieldset_exemption_is_the_first_legend_child_only() {
+ // Every disabled fieldset ancestor counts, and only descendants of that
+ // fieldset's first <legend> child escape it. A legend wrapped in a div
+ // is not the fieldset's legend, a second legend does not exempt, and an
+ // inner fieldset's legend does not escape an outer disabled fieldset.
+ let mut rt = setup_runtime(
+ r#"<fieldset disabled><legend><input type="checkbox" id="a"></legend>
+ <input type="checkbox" id="b"></fieldset>
+ <fieldset disabled><legend>x</legend>
+ <legend><input type="checkbox" id="c"></legend></fieldset>
+ <fieldset disabled><div><legend>
+ <input type="checkbox" id="d"></legend></div></fieldset>
+ <fieldset disabled><div><fieldset disabled><legend>
+ <input type="checkbox" id="e"></legend></fieldset></div></fieldset>
+ <fieldset disabled><fieldset><legend>
+ <input type="checkbox" id="f"></legend></fieldset></fieldset>"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ const ids = ['a', 'b', 'c', 'd', 'e', 'f'];
+ for (const id of ids) { document.getElementById(id).click(); }
+ return ids.map(id => document.getElementById(id).checked);
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!([true, false, false, false, false, false])
+ );
+ }
+
+ #[test]
+ fn test_label_click_runs_checkbox_pre_click_activation() {
+ // The control flips before the click event dispatches, so listeners
+ // observe the new state, `input` and `change` follow, and a cancelled
+ // event restores the old state.
+ let mut rt = setup_runtime(
+ r#"<label id="live" for="live-box">a</label><input type="checkbox" id="live-box">
+ <label id="cancel" for="cancel-box">b</label>
+ <input type="checkbox" id="cancel-box">"#,
+ );
+ let result = rt
+ .evaluate(
+ r#"
+ const events = [];
+ const live = document.getElementById('live-box');
+ for (const type of ['click', 'input', 'change']) {
+ live.addEventListener(type, () => events.push(type + ':' + live.checked));
+ }
+ document.getElementById('live').click();
+ const cancelled = document.getElementById('cancel-box');
+ cancelled.addEventListener('click', event => event.preventDefault());
+ document.getElementById('cancel').click();
+ return [events.join(','), live.checked, cancelled.checked];
+ "#,
+ )
+ .unwrap();
+ assert_eq!(
+ result,
+ serde_json::json!(["click:true,input:true,change:true", true, false])
+ );
+ }
+
#[test]
fn test_dispatch_mouse_event_runs_listener() {
let mut rt = setup_runtime(r#"<button id="go">Go</button>"#);