Skip to content

The headless browser for AI agents and web scraping

perf(render): preserve fast form state access

SGavrldeef294cabd7
diff --git a/crates/obscura-dom/src/selector.rs b/crates/obscura-dom/src/selector.rs
index 1ee7d992..09ecb31e 100644
--- a/crates/obscura-dom/src/selector.rs
+++ b/crates/obscura-dom/src/selector.rs
@@ -500,8 +500,8 @@ impl<'a> Element for DomElement<'a> {
PseudoClass::Enabled => self.is_form_control() && !self.has_boolean_attr("disabled"),
PseudoClass::Disabled => self.is_form_control() && self.has_boolean_attr("disabled"),
PseudoClass::Checked => {
- self.tree.form_control_state(self.node_id)
- .and_then(|control| control.checked)
+ self.tree
+ .form_control_checked(self.node_id)
.unwrap_or_else(|| self.has_boolean_attr("checked") || self.has_boolean_attr("selected"))
}
// Dynamic user-interaction pseudo-classes have no meaning against
diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rs
index f894fb99..6ce4f4ab 100644
--- a/crates/obscura-dom/src/tree.rs
+++ b/crates/obscura-dom/src/tree.rs
@@ -310,6 +310,31 @@ impl DomTree {
self.inner.borrow().form_controls.get(&node).cloned()
}
+ pub fn form_control_value_matches(&self, node: NodeId, value: &str) -> bool {
+ self.inner
+ .borrow()
+ .form_controls
+ .get(&node)
+ .and_then(|control| control.value.as_deref())
+ == Some(value)
+ }
+
+ pub fn form_control_checked(&self, node: NodeId) -> Option<bool> {
+ self.inner
+ .borrow()
+ .form_controls
+ .get(&node)
+ .and_then(|control| control.checked)
+ }
+
+ pub fn form_control_indeterminate(&self, node: NodeId) -> bool {
+ self.inner
+ .borrow()
+ .form_controls
+ .get(&node)
+ .is_some_and(|control| control.indeterminate)
+ }
+
pub fn update_form_control_state(&self, node: NodeId, update: impl FnOnce(&mut FormControlState)) {
let mut inner = self.inner.borrow_mut();
if inner.nodes.get(node.index()).is_some_and(|entry| entry.as_ref().is_some_and(Node::is_element)) {
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index ced44779..877853b9 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -697,8 +697,25 @@ function _getFp() {
}
function _fp(key) { return _getFp()[key]; }
globalThis._eventRegistry = globalThis._eventRegistry || {};
+globalThis._formValues = globalThis._formValues || {};
+globalThis._formChecked = globalThis._formChecked || {};
+globalThis._formIndeterminate = globalThis._formIndeterminate || {};
const _eventRegistry = globalThis._eventRegistry;
+const _formValues = globalThis._formValues;
+const _formChecked = globalThis._formChecked;
+const _formIndeterminate = globalThis._formIndeterminate;
const _domParse = (cmd, a1, a2) => { try { return JSON.parse(_dom(cmd, a1, a2)); } catch { return null; } };
+const _formStateLoaded = new Set();
+function _loadFormState(nid) {
+ if (_formStateLoaded.has(nid)) return;
+ const state = _domParse("get_form_state", nid);
+ if (state) {
+ if (state.value !== null) _formValues[nid] = state.value;
+ if (state.checked !== null) _formChecked[nid] = state.checked;
+ if (state.indeterminate) _formIndeterminate[nid] = true;
+ }
+ _formStateLoaded.add(nid);
+}
// HTML "ASCII whitespace": U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE.
// Class token splitting (classList, getElementsByClassName) uses exactly this set.
@@ -3966,8 +3983,8 @@ class Element extends Node {
if (opts.length) return opts[0].getAttribute('value') !== null ? opts[0].getAttribute('value') : opts[0].textContent;
return '';
}
- const currentValue = _domParse("get_form_value", this._nid);
- if (currentValue !== null) return currentValue;
+ if (_formValues[this._nid] === undefined) _loadFormState(this._nid);
+ if (_formValues[this._nid] !== undefined) return _formValues[this._nid];
if (tag === 'textarea') return this.textContent;
if (tag === 'option') {
const attr = this.getAttribute('value');
@@ -4018,9 +4035,11 @@ class Element extends Node {
}
return;
}
- _dom("set_form_value", this._nid, String(v));
+ const value = String(v);
+ _formValues[this._nid] = value;
+ _dom("set_form_value", this._nid, value);
if (tag === 'textarea') {
- this.textContent = String(v);
+ this.textContent = value;
}
}
get min() { return this.getAttribute('min') || ''; }
@@ -4096,17 +4115,28 @@ class Element extends Node {
this.value = _inputFormatNumber(t, value);
}
get checked() {
- const currentChecked = _domParse("get_form_checked", this._nid);
- if (currentChecked !== null) return currentChecked;
+ if (_formChecked[this._nid] === undefined) _loadFormState(this._nid);
+ if (_formChecked[this._nid] !== undefined) return _formChecked[this._nid];
return this.hasAttribute("checked");
}
- set checked(v) { _dom("set_form_checked", this._nid, String(!!v)); }
+ set checked(v) {
+ const checked = !!v;
+ _formChecked[this._nid] = checked;
+ _dom("set_form_checked", this._nid, String(checked));
+ }
// `indeterminate` is IDL-only: it has no content attribute to reflect, so
// the property itself must exist on the prototype for `'indeterminate' in
// el` to be true on a freshly created element. Native node-keyed state
// keeps IDL access and rendering consistent without changing attributes.
- get indeterminate() { return _domParse("get_form_indeterminate", this._nid) === true; }
- set indeterminate(v) { _dom("set_form_indeterminate", this._nid, String(!!v)); }
+ get indeterminate() {
+ if (_formIndeterminate[this._nid] === undefined) _loadFormState(this._nid);
+ return _formIndeterminate[this._nid] === true;
+ }
+ set indeterminate(v) {
+ const indeterminate = !!v;
+ _formIndeterminate[this._nid] = indeterminate;
+ _dom("set_form_indeterminate", this._nid, String(indeterminate));
+ }
get selected() {
if (this._selected !== undefined) return this._selected;
return this.hasAttribute("selected");
@@ -11628,7 +11658,22 @@ globalThis.HTMLFormElement = class HTMLFormElement extends Element {
get length() { return this.elements.length; }
// Inherit submit() from Element.prototype: it dispatches the cancelable
// 'submit' event and (if not prevented) builds form data and navigates.
- reset() { for (const f of this.elements) { if ('value' in f) f.value = ''; } }
+ reset() {
+ if (!this.dispatchEvent(new Event('reset', { bubbles: true, cancelable: true }))) return;
+ for (const f of this.elements) {
+ if (f.localName === 'input') {
+ const type = (f.getAttribute('type') || 'text').toLowerCase();
+ if (type === 'checkbox' || type === 'radio') {
+ f.checked = f.hasAttribute('checked');
+ f.indeterminate = false;
+ } else {
+ f.value = f.getAttribute('value') || '';
+ }
+ } else if ('value' in f) {
+ f.value = '';
+ }
+ }
+ }
};
globalThis.HTMLSelectElement = Element;
globalThis.HTMLTextAreaElement = class HTMLTextAreaElement extends Element {
diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rs
index 1d679af0..11454a3b 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -753,11 +753,12 @@ fn render_mutation_impact(
let Some(target) = node(arg1) else {
return RenderMutationImpact::default();
};
- let control = dom.form_control_state(target).unwrap_or_default();
let actual_change = match cmd {
- "set_form_value" => control.value.as_deref() != Some(arg2),
- "set_form_checked" => control.checked != Some(arg2 == "true"),
- _ => control.indeterminate != (arg2 == "true"),
+ "set_form_value" => !dom.form_control_value_matches(target, arg2),
+ "set_form_checked" => {
+ dom.form_control_checked(target) != Some(arg2 == "true")
+ }
+ _ => dom.form_control_indeterminate(target) != (arg2 == "true"),
};
RenderMutationImpact { connected: node_is_connected(dom, target), actual_change }
}
@@ -1529,14 +1530,18 @@ fn op_dom_inner(shared: SharedState, cmd: String, arg1: String, arg2: String) ->
};
match cmd.as_str() {
- "get_form_value" | "get_form_checked" | "get_form_indeterminate" => {
+ "get_form_state" => {
let nid = NodeId::new(arg1.parse().unwrap_or(u32::MAX));
- let control = dom.form_control_state(nid).unwrap_or_default();
- match cmd.as_str() {
- "get_form_value" => serde_json::to_string(&control.value).unwrap_or("null".into()),
- "get_form_checked" => serde_json::to_string(&control.checked).unwrap_or("null".into()),
- _ => control.indeterminate.to_string(),
- }
+ dom.form_control_state(nid)
+ .map(|control| {
+ serde_json::json!({
+ "value": control.value,
+ "checked": control.checked,
+ "indeterminate": control.indeterminate,
+ })
+ .to_string()
+ })
+ .unwrap_or_else(|| "null".to_string())
}
"set_form_value" | "set_form_checked" | "set_form_indeterminate" => {
let nid = NodeId::new(arg1.parse().unwrap_or(u32::MAX));
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 4a5b2853..e2821525 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -4401,14 +4401,19 @@ mod tests {
#[cfg(feature = "render")]
#[test]
- fn resetting_an_empty_default_input_clears_live_paint_state() {
- let mut rt = setup_runtime("<html><body><form id=form><input id=field></form></body></html>");
+ fn form_reset_restores_default_input_state_and_pixels() {
+ let mut rt = setup_runtime(
+ "<html><body><form id=form><input id=field value=default><input id=box type=checkbox checked></form></body></html>",
+ );
rt.set_viewport(320.0, 120.0);
let before = rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap();
- rt.evaluate("document.getElementById('field').value = 'typed'").unwrap();
+ rt.evaluate("const field=document.getElementById('field'),box=document.getElementById('box');field.value='typed';box.checked=false;box.indeterminate=true").unwrap();
assert_ne!(before, rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap());
rt.evaluate("document.getElementById('form').reset()").unwrap();
- assert_eq!(rt.evaluate("document.getElementById('field').value").unwrap(), serde_json::json!(""));
+ assert_eq!(
+ rt.evaluate("[field.value,field.getAttribute('value'),box.checked,box.indeterminate,box.hasAttribute('checked')]").unwrap(),
+ serde_json::json!(["default", "default", true, false, true])
+ );
assert_eq!(before, rt.screenshot_prepared((320.0, 120.0), Some("http://example.com/test")).unwrap());
}
diff --git a/crates/obscura-render/src/paint.rs b/crates/obscura-render/src/paint.rs
index 2d4354a5..bca2c62f 100644
--- a/crates/obscura-render/src/paint.rs
+++ b/crates/obscura-render/src/paint.rs
@@ -4715,17 +4715,22 @@ fn paint_laid_dom_scrolled(
}
}
- let input_type = node.get_attribute("type").unwrap_or("text").to_ascii_lowercase();
- let checkable = name.local.as_ref() == "input" && matches!(input_type.as_str(), "checkbox" | "radio");
+ let input_type = (name.local.as_ref() == "input")
+ .then(|| node.get_attribute("type").unwrap_or("text"));
+ let checkable = input_type.is_some_and(|kind| {
+ kind.eq_ignore_ascii_case("checkbox") || kind.eq_ignore_ascii_case("radio")
+ });
if checkable && rect.width > 0.0 && rect.height > 0.0 {
- let control = tree.form_control_state(nid).unwrap_or_default();
- let checked = control.checked.unwrap_or_else(|| node.get_attribute("checked").is_some());
- let indeterminate = input_type == "checkbox" && control.indeterminate;
+ let checked = tree
+ .form_control_checked(nid)
+ .unwrap_or_else(|| node.get_attribute("checked").is_some());
+ let is_radio = input_type.is_some_and(|kind| kind.eq_ignore_ascii_case("radio"));
+ let indeterminate = !is_radio && tree.form_control_indeterminate(nid);
let disabled = node.get_attribute("disabled").is_some();
let size = rect.width.min(rect.height);
let x = rect.x + (rect.width - size) / 2.0;
let y = rect.y + (rect.height - size) / 2.0;
- let shape = if input_type == "radio" {
+ let shape = if is_radio {
PathBuilder::from_circle(x + size / 2.0, y + size / 2.0, (size - 1.0).max(0.0) / 2.0)
} else {
tiny_skia::Rect::from_xywh(x + 0.5, y + 0.5, (size - 1.0).max(0.0), (size - 1.0).max(0.0))
@@ -4738,13 +4743,13 @@ fn paint_laid_dom_scrolled(
control_paint.set_color(Color::from_rgba8(color[0], color[1], color[2], color[3]));
control_paint.anti_alias = true;
let stroke = tiny_skia::Stroke { width: 1.0, ..Default::default() };
- if input_type == "checkbox" && selected {
+ if !is_radio && selected {
pixmap.fill_path(&shape, &control_paint, FillRule::Winding, raster_transform(raster_scale), element_clip_mask);
} else {
pixmap.stroke_path(&shape, &control_paint, &stroke, raster_transform(raster_scale), element_clip_mask);
}
if selected {
- if input_type == "radio" {
+ if is_radio {
if let Some(dot) = PathBuilder::from_circle(x + size / 2.0, y + size / 2.0, size * 0.25) {
pixmap.fill_path(&dot, &control_paint, FillRule::Winding, raster_transform(raster_scale), element_clip_mask);
}
@@ -4792,10 +4797,8 @@ fn paint_laid_dom_scrolled(
let text_y = rect.y + style.padding.top + style.border.top;
let color = style.color.unwrap_or([0, 0, 0, 255]);
let masked;
- let shown = if node
- .get_attribute("type")
- .is_some_and(|kind| kind.eq_ignore_ascii_case("password"))
- {
+ let shown = if input_type
+ .is_some_and(|kind| kind.eq_ignore_ascii_case("password")) {
masked = "\u{2022}".repeat(value.chars().count());
masked.as_str()
} else {