Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
Persist hover state for Stylo selectors
ldm08dffc69a898a
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.py b/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.pyindex b7004c715..7863ed575 100644--- a/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.py+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/dom_input.py@@ -282,13 +282,16 @@ async def run_locator_input_workflows(state: SmokeState) -> None:<style>#drag { position: absolute; left: 20px; top: 220px; width: 80px; height: 40px; background: #ddd; }#drop { position: absolute; left: 160px; top: 220px; width: 120px; height: 60px; background: #eee; }- #hover { position: absolute; left: 20px; top: 160px; width: 90px; height: 36px; }+ #hover-menu { position: absolute; left: 20px; top: 160px; width: 90px; }+ #hover { width: 90px; height: 36px; }+ #hover-child { display: none; width: 90px; height: 24px; }+ #hover-menu:hover #hover-child { display: block; }#editable { min-width: 120px; min-height: 24px; }</style><input id="text" value=""><textarea id="area"></textarea><div id="editable" contenteditable="true"></div>- <button id="hover">hover</button>+ <div id="hover-menu"><button id="hover">hover</button><button id="hover-child">child</button></div><input id="check" type="checkbox"><input id="radio-a" name="choice" type="radio" value="a"><input id="radio-b" name="choice" type="radio" value="b">@@ -299,10 +302,12 @@ async def run_locator_input_workflows(state: SmokeState) -> None:window.__keys = [];const textInput = document.getElementById('text');const hoverTarget = document.getElementById('hover');+ const hoverChild = document.getElementById('hover-child');const dragSource = document.getElementById('drag');const dropTarget = document.getElementById('drop');textInput.addEventListener('keydown', event => window.__keys.push(`${event.key}:${event.shiftKey}:${event.ctrlKey || event.metaKey}`));hoverTarget.addEventListener('mouseenter', () => window.__hovered = true);+ hoverChild.addEventListener('click', () => window.__hoverChildClicked = true);dragSource.addEventListener('dragstart', event => event.dataTransfer.setData('text/plain', 'dragged-value'));dropTarget.addEventListener('dragover', event => event.preventDefault());dropTarget.addEventListener('drop', event => {@@ -341,6 +346,23 @@ async def run_locator_input_workflows(state: SmokeState) -> None:True,"locator hover is dispatched",)+ assert_equal(+ await page.evaluate(+ """() => ({+ target: document.querySelector('#hover').matches(':hover'),+ ancestor: document.querySelector('#hover-menu').matches(':hover'),+ childDisplay: getComputedStyle(document.querySelector('#hover-child')).display,+ })"""+ ),+ {"target": True, "ancestor": True, "childDisplay": "block"},+ "locator hover persists in Stylo and exposes the dropdown",+ )+ await page.locator("#hover-child").click(timeout=1_000)+ assert_equal(+ await page.evaluate("() => window.__hoverChildClicked === true"),+ True,+ "hover dropdown child is clickable without waiting for a screencast frame",+ )await page.locator("#check").evaluate("input => input.checked = true")await page.locator("#radio-b").evaluate("input => input.checked = true")diff --git a/moli-dom/src/native/host/document.rs b/moli-dom/src/native/host/document.rsindex 3104b4de1..3fdfd80bf 100644--- a/moli-dom/src/native/host/document.rs+++ b/moli-dom/src/native/host/document.rs@@ -69,6 +69,7 @@ impl DomHost {child_browsing_context_host_candidates: RefCell::new(Vec::new()),shadow_disabled_custom_element_definitions: RefCell::new(HashSet::new()),active_element: Cell::new(None),+ hovered_elements: RefCell::new(IndexSet::new()),mutation_observer_records_enabled: Cell::new(false),devtools_mutation_records_enabled: Cell::new(false),};@@ -517,6 +518,54 @@ impl DomHost {false}+ pub fn hovered_element_handles(&self) -> Vec<DomHandle> {+ self.hovered_elements+ .borrow()+ .iter()+ .copied()+ .filter(|handle| {+ self.node(*handle)+ .is_some_and(|node| node.is_element() && node.is_connected())+ })+ .collect()+ }++ pub fn set_hovered_element_handles(&self, handles: Vec<DomHandle>) -> bool {+ let next = handles+ .into_iter()+ .filter(|handle| {+ self.node(*handle)+ .is_some_and(|node| node.is_element() && node.is_connected())+ })+ .collect::<IndexSet<_>>();+ let mut hovered = self.hovered_elements.borrow_mut();+ if *hovered == next {+ return false;+ }+ *hovered = next;+ drop(hovered);+ self.record_mutation(MutationScope::QueryState);+ true+ }++ pub fn clear_hovered_element_handles(&self) {+ if self.hovered_elements.borrow().is_empty() {+ return;+ }+ self.hovered_elements.borrow_mut().clear();+ self.record_mutation(MutationScope::QueryState);+ }++ pub(super) fn prune_disconnected_hovered_elements(&self) {+ self.hovered_elements+ .borrow_mut()+ .retain(|handle| self.is_connected(*handle));+ }++ pub fn element_matches_hover(&self, handle: DomHandle) -> bool {+ self.is_connected(handle) && self.hovered_elements.borrow().contains(&handle)+ }+pub fn resolve_node(&self, node_id: NodeId) -> Option<DomHandle> {self.node(node_id).map(|_| node_id)}diff --git a/moli-dom/src/native/host/mutation/tree.rs b/moli-dom/src/native/host/mutation/tree.rsindex c6aa1543a..5f2effe6a 100644--- a/moli-dom/src/native/host/mutation/tree.rs+++ b/moli-dom/src/native/host/mutation/tree.rs@@ -72,6 +72,7 @@ impl DomHost {.remove_child_with_stylesheet_candidate_changes(parent, child);if let Some(candidate_changes) = candidate_changes {self.invalidate_shadow_slot_name_index_for_tree_parent(parent);+ self.prune_disconnected_hovered_elements();let mut effects = DomMutationEffects::changed();effects.extend_stylesheet_candidate_changes(candidate_changes);self.clear_popover_open_states(&removal_context.open_popovers, &mut effects);diff --git a/moli-dom/src/native/host/types.rs b/moli-dom/src/native/host/types.rsindex 813479dd4..380f7d6c2 100644--- a/moli-dom/src/native/host/types.rs+++ b/moli-dom/src/native/host/types.rs@@ -41,6 +41,7 @@ pub struct DomHost {pub(super) child_browsing_context_host_candidates: RefCell<Vec<DomHandle>>,pub(super) shadow_disabled_custom_element_definitions: RefCell<HashSet<String>>,pub(super) active_element: Cell<Option<DomHandle>>,+ pub(super) hovered_elements: RefCell<IndexSet<DomHandle>>,pub(super) mutation_observer_records_enabled: Cell<bool>,pub(super) devtools_mutation_records_enabled: Cell<bool>,}diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rsindex 4481a895b..c6ac3a094 100644--- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs@@ -1,4 +1,4 @@-use std::rc::Rc;+use std::{collections::HashSet, rc::Rc};use super::{JsContextHost,@@ -9,6 +9,7 @@ use crate::{dom::native::{DocumentReadyState, DomStylesheetOwnerChange, DomStylesheetOwnerChangeKind, Node,},+ native_bridge::element::label_control_handle,network::context::DocumentResourceLoader,style_engine::{AdoptedStyleSheetInstallation, CssCustomPropertyRegistration,@@ -34,6 +35,43 @@ fn push_unique_handle(handles: &mut Vec<DomHandle>, handle: DomHandle) {}}+fn hover_chain_for_input_hit(runtime: &JsContextHost, hit: Option<DomHandle>) -> Vec<DomHandle> {+ let mut hovered = Vec::new();+ let mut visited = HashSet::new();+ let mut current = hit;+ while let Some(handle) = current {+ if !visited.insert(handle) {+ break;+ }+ let Some(node) = runtime.dom_host().node(handle) else {+ break;+ };+ if node.is_element() {+ push_unique_handle(&mut hovered, handle);+ if let Some(control) = label_control_handle(runtime, handle) {+ push_unique_handle(&mut hovered, control);+ }+ }+ if let Some(slot) = runtime.dom_host().assigned_slot_for_node(handle) {+ current = Some(slot);+ continue;+ }+ if let Some(parent) = runtime.dom_host().parent_node(handle) {+ current = if runtime.dom_host().is_shadow_root(parent) {+ runtime.dom_host().shadow_root_host(parent)+ } else {+ Some(parent)+ };+ continue;+ }+ current = node+ .is_document()+ .then(|| runtime.child_browsing_context_host_for_document_handle(handle))+ .flatten();+ }+ hovered+}+impl JsContextHost {pub(crate) fn documents_with_adopted_style_sheets(&self) -> Vec<DomHandle> {self.style_engine.documents_with_adopted_style_sheets()@@ -1685,6 +1723,39 @@ impl JsContextHost {);}+ pub(crate) fn set_hovered_element_for_input(&mut self, hit: Option<DomHandle>) -> bool {+ let next = hover_chain_for_input_hit(self, hit);+ let previous = self.dom_host().hovered_element_handles();+ if previous == next {+ return false;+ }+ let changed = previous+ .iter()+ .chain(&next)+ .copied()+ .filter(|handle| previous.contains(handle) != next.contains(handle))+ .collect::<Vec<_>>();+ let old_states = changed+ .iter()+ .map(|handle| (*handle, self.retained_current_element_state(*handle)))+ .collect::<Vec<_>>();+ if !self.dom_host().set_hovered_element_handles(next) {+ return false;+ }+ for (handle, old_state) in old_states {+ self.note_element_state_style_activity_with_old_state(+ handle,+ StyloElementState::HOVER,+ old_state,+ );+ }+ // Hover selectors may change box generation or geometry. The next hit+ // test must observe that new tree instead of waiting for a paint pass+ // to replace the latest owned layout snapshot.+ self.invalidate_layout_after_interaction_state_change();+ true+ }+pub(crate) fn note_custom_state_style_activity(&mut self,element: DomHandle,diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout.rs b/moli-renderer-v8/src/native_bridge/context_host/layout.rsindex a3fffab1e..d3f3f8071 100644--- a/moli-renderer-v8/src/native_bridge/context_host/layout.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/layout.rs@@ -284,6 +284,13 @@ impl JsContextHost {*self.document_layout_state.borrow_mut() = Default::default();}+ pub(crate) fn invalidate_layout_after_interaction_state_change(&self) {+ self.clear_layout_rect_cache();+ self.document_layout_state+ .borrow_mut()+ .clear_latest_layout();+ }+pub(crate) fn mark_document_web_font_sources_dirty(&self) {self.document_layout_state.borrow_mut()diff --git a/moli-renderer-v8/src/script_vm/input_dispatch.rs b/moli-renderer-v8/src/script_vm/input_dispatch.rsindex 055138df5..e18d3882b 100644--- a/moli-renderer-v8/src/script_vm/input_dispatch.rs+++ b/moli-renderer-v8/src/script_vm/input_dispatch.rs@@ -454,6 +454,10 @@ impl ScriptVm {.active_pointer_capture_target(MOUSE_POINTER_ID)}).flatten();+ if tracks_mouse_hover_for_event(event_name) {+ let mut context_host = self._context_host.borrow_mut();+ context_host.set_hovered_element_for_input(hit_handle);+ }let Some(handle) = capture_handle.or(hit_handle) else {return Ok(input_dispatch_outcome(false));};diff --git a/moli-renderer-v8/src/script_vm/input_helpers.rs b/moli-renderer-v8/src/script_vm/input_helpers.rsindex bc4e72330..a7659e40c 100644--- a/moli-renderer-v8/src/script_vm/input_helpers.rs+++ b/moli-renderer-v8/src/script_vm/input_helpers.rs@@ -50,6 +50,10 @@ pub(super) fn clear_input_dispatch_state(vm: &mut ScriptVm) {vm.pressed_mouse_buttons = 0;vm.pending_mouse_press = None;vm.hovered_mouse_handle = None;+ vm._context_host+ .borrow()+ .dom_host()+ .clear_hovered_element_handles();vm.active_touch_pointer_handle = None;vm.active_touch_pointer_handles.clear();vm.active_touch_event_handle = None;diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rsindex 5c296cc58..0fe7d32d8 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/dom.rs@@ -5395,6 +5395,95 @@ fn mouse_hover_dispatches_pointer_boundary_before_mouse_boundary() {);}+#[test]+fn mouse_hover_persists_stylo_state_and_reflows_dropdown_before_next_hit_test() {+ let mut vm = new_parsed_test_vm(+ "https://hover-dropdown.test/",+ r#"+<!doctype html>+<style>+ html, body { margin: 0; padding: 0; }+ #menu, #trigger, #submenu, #outside { width: 120px; }+ #trigger, #submenu, #outside { display: block; box-sizing: border-box; height: 24px; }+ #submenu { display: none; }+ #menu:hover #submenu { display: block; }+</style>+<nav id="menu">+ <button id="trigger">menu</button>+ <button id="submenu">child</button>+</nav>+<button id="outside">outside</button>+"#,+ );+ vm.eval(+ r#"+(() => {+ const menu = document.getElementById('menu');+ const trigger = document.getElementById('trigger');+ const submenu = document.getElementById('submenu');+ const outside = document.getElementById('outside');+ window.__submenuClicks = 0;+ window.__duringHover = '';+ window.__afterLeave = '';+ trigger.addEventListener('mousemove', () => {+ window.__duringHover = [+ trigger.matches(':hover'),+ menu.matches(':hover'),+ document.body.matches(':hover'),+ document.documentElement.matches(':hover'),+ getComputedStyle(submenu).display+ ].join('|');+ });+ submenu.addEventListener('click', () => window.__submenuClicks++);+ outside.addEventListener('mousemove', () => {+ window.__afterLeave = [+ trigger.matches(':hover'),+ menu.matches(':hover'),+ submenu.matches(':hover'),+ outside.matches(':hover'),+ getComputedStyle(submenu).display+ ].join('|');+ });+})()+"#,+ )+ .expect("hover dropdown listeners should install");++ assert_eq!(+ vm.eval(+ "[document.getElementById('menu').matches(':hover'), getComputedStyle(document.getElementById('submenu')).display].join('|')"+ )+ .expect("initial hover state should evaluate"),+ "false|none"+ );++ vm.dispatch_mouse_event_at_point(10.0, 10.0, "mousemove", -1, Some(0), 0.0, 0.0)+ .expect("mousemove should establish hover state");+ assert_eq!(+ vm.eval("window.__duringHover")+ .expect("in-event hover state should evaluate"),+ "true|true|true|true|block"+ );++ vm.dispatch_mouse_event_at_point(10.0, 35.0, "mousedown", 0, Some(1), 0.0, 0.0)+ .expect("mousedown should hit the newly displayed submenu");+ vm.dispatch_mouse_event_at_point(10.0, 35.0, "mouseup", 0, Some(0), 0.0, 0.0)+ .expect("mouseup should activate the newly displayed submenu");+ assert_eq!(+ vm.eval("String(window.__submenuClicks)")+ .expect("submenu click count should evaluate"),+ "1"+ );++ vm.dispatch_mouse_event_at_point(10.0, 60.0, "mousemove", -1, Some(0), 0.0, 0.0)+ .expect("mousemove outside the menu should clear its hover chain");+ assert_eq!(+ vm.eval("window.__afterLeave")+ .expect("post-hover state should evaluate"),+ "false|false|false|true|none"+ );+}+#[test]fn detached_document_tag_collection_exposes_named_item() {let mut vm = new_storage_test_vm("https://detached-document-named-item.test/");diff --git a/moli-selector/src/lib.rs b/moli-selector/src/lib.rsindex 896745925..3766b5d73 100644--- a/moli-selector/src/lib.rs+++ b/moli-selector/src/lib.rs@@ -1046,6 +1046,44 @@ mod tests {assert!(!engine.matches_host(&host, target, ":target").unwrap());}+ #[test]+ fn dom_api_selectors_match_persistent_hover_state() {+ let url = url::Url::parse("https://example.test/").unwrap();+ let mut host = DomHost::from_dom(NativeDom::new_html(url));+ host.reset_html_document_shell();+ let body = host.document_body_handle().unwrap();+ let menu = host.create_element("nav");+ let item = host.create_element("button");+ let sibling = host.create_element("button");+ assert!(host.append_child(menu, item));+ assert!(host.append_child(body, menu));+ assert!(host.append_child(body, sibling));++ let engine = QueryEngine;+ assert!(!engine.matches_host(&host, item, ":hover").unwrap());+ assert!(!engine.matches_host(&host, menu, ":hover").unwrap());++ assert!(host.set_hovered_element_handles(vec![item, menu, body]));+ assert!(engine.matches_host(&host, item, ":hover").unwrap());+ assert!(engine.matches_host(&host, menu, ":hover").unwrap());+ assert!(+ engine+ .matches_host(&host, menu, ":hover:has(> button:hover)")+ .unwrap()+ );+ assert!(!engine.matches_host(&host, sibling, ":hover").unwrap());++ assert!(host.set_hovered_element_handles(vec![sibling, body]));+ assert!(!engine.matches_host(&host, item, ":hover").unwrap());+ assert!(!engine.matches_host(&host, menu, ":hover").unwrap());+ assert!(engine.matches_host(&host, sibling, ":hover").unwrap());++ assert!(host.remove_child(body, sibling));+ assert!(!engine.matches_host(&host, sibling, ":hover").unwrap());+ assert!(host.append_child(body, sibling));+ assert!(!engine.matches_host(&host, sibling, ":hover").unwrap());+ }+#[test]fn dom_api_selectors_clear_target_state_for_empty_fragment_and_top() {let url = url::Url::parse("https://example.test/page.html#target").unwrap();diff --git a/moli-selector/src/stylo/query/element.rs b/moli-selector/src/stylo/query/element.rsindex 86597e361..5a00bf7f9 100644--- a/moli-selector/src/stylo/query/element.rs+++ b/moli-selector/src/stylo/query/element.rs@@ -588,8 +588,8 @@ impl SelectorsElement for QueryElement<'_> {match pc {NonTSPseudoClass::Link | NonTSPseudoClass::AnyLink => self.is_link(),NonTSPseudoClass::Visited => false,+ NonTSPseudoClass::Hover => self.host.element_matches_hover(self.handle),NonTSPseudoClass::Active- | NonTSPseudoClass::Hover| NonTSPseudoClass::Fullscreen| NonTSPseudoClass::Open| NonTSPseudoClass::ServoNonZeroBorderdiff --git a/moli-selector/src/stylo/query/pseudo.rs b/moli-selector/src/stylo/query/pseudo.rsindex 2ae09f527..a36f8b41a 100644--- a/moli-selector/src/stylo/query/pseudo.rs+++ b/moli-selector/src/stylo/query/pseudo.rs@@ -73,6 +73,9 @@ impl<'a> QueryElement<'a> {if self.host.element_matches_focus_within(self.handle) {state |= ElementState::FOCUS_WITHIN;}+ if self.host.element_matches_hover(self.handle) {+ state |= ElementState::HOVER;+ }if self.matches_target_pseudo() {state |= ElementState::URLTARGET;}