viewpoint_core/page/locator/mod.rs
1//! Locator system for element selection.
2//!
3//! Locators are lazy handles that store selection criteria but don't query the DOM
4//! until an action is performed. This enables auto-waiting and chainable refinement.
5//!
6//! # Example
7//!
8//! ```
9//! # #[cfg(feature = "integration")]
10//! # tokio_test::block_on(async {
11//! # use viewpoint_core::Browser;
12//! use viewpoint_core::AriaRole;
13//! # let browser = Browser::launch().headless(true).launch().await.unwrap();
14//! # let context = browser.new_context().await.unwrap();
15//! # let page = context.new_page().await.unwrap();
16//! # page.goto("about:blank").goto().await.unwrap();
17//!
18//! // CSS selector
19//! let button = page.locator("button.submit");
20//!
21//! // Text locator
22//! let heading = page.get_by_text("Welcome");
23//!
24//! // Role locator
25//! let submit = page.get_by_role(AriaRole::Button).with_name("Submit");
26//!
27//! // Chained locators
28//! let item = page.locator(".list").locator(".item").first();
29//! # });
30//! ```
31
32mod actions;
33mod aria_role;
34mod builders;
35mod debug;
36mod element;
37mod evaluation;
38mod files;
39mod filter;
40mod helpers;
41mod queries;
42mod select;
43pub mod aria;
44mod aria_js;
45pub(crate) mod selector;
46
47use std::time::Duration;
48
49pub use builders::{ClickBuilder, HoverBuilder, TapBuilder, TypeBuilder};
50pub use element::{BoundingBox, BoxModel, ElementHandle};
51pub use filter::{FilterBuilder, RoleLocatorBuilder};
52pub use aria::{AriaCheckedState, AriaSnapshot};
53pub use selector::{AriaRole, Selector, TextOptions};
54
55use crate::Page;
56
57/// Default timeout for locator operations.
58const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
59
60/// A locator for finding elements on a page.
61///
62/// Locators are lightweight handles that store selection criteria. They don't
63/// query the DOM until an action is performed, enabling auto-waiting.
64#[derive(Debug, Clone)]
65pub struct Locator<'a> {
66 /// Reference to the page.
67 page: &'a Page,
68 /// The selector for finding elements.
69 selector: Selector,
70 /// Locator options.
71 options: LocatorOptions,
72}
73
74/// Options for locator behavior.
75#[derive(Debug, Clone)]
76pub struct LocatorOptions {
77 /// Timeout for operations.
78 pub timeout: Duration,
79}
80
81impl Default for LocatorOptions {
82 fn default() -> Self {
83 Self {
84 timeout: DEFAULT_TIMEOUT,
85 }
86 }
87}
88
89impl<'a> Locator<'a> {
90 /// Create a new locator.
91 pub(crate) fn new(page: &'a Page, selector: Selector) -> Self {
92 Self {
93 page,
94 selector,
95 options: LocatorOptions::default(),
96 }
97 }
98
99 /// Create a new locator with custom options.
100 pub(crate) fn with_options(page: &'a Page, selector: Selector, options: LocatorOptions) -> Self {
101 Self {
102 page,
103 selector,
104 options,
105 }
106 }
107
108 /// Get the page this locator belongs to.
109 pub fn page(&self) -> &'a Page {
110 self.page
111 }
112
113 /// Get the selector.
114 pub fn selector(&self) -> &Selector {
115 &self.selector
116 }
117
118 /// Get the options.
119 pub fn options(&self) -> &LocatorOptions {
120 &self.options
121 }
122
123 /// Set a custom timeout for this locator.
124 #[must_use]
125 pub fn timeout(mut self, timeout: Duration) -> Self {
126 self.options.timeout = timeout;
127 self
128 }
129
130 /// Create a child locator that further filters elements.
131 ///
132 /// # Example
133 ///
134 /// ```ignore
135 /// let items = page.locator(".list").locator(".item");
136 /// ```
137 #[must_use]
138 pub fn locator(&self, selector: impl Into<String>) -> Locator<'a> {
139 Locator {
140 page: self.page,
141 selector: Selector::Chained(
142 Box::new(self.selector.clone()),
143 Box::new(Selector::Css(selector.into())),
144 ),
145 options: self.options.clone(),
146 }
147 }
148
149 /// Select the first matching element.
150 #[must_use]
151 pub fn first(&self) -> Locator<'a> {
152 Locator {
153 page: self.page,
154 selector: Selector::Nth {
155 base: Box::new(self.selector.clone()),
156 index: 0,
157 },
158 options: self.options.clone(),
159 }
160 }
161
162 /// Select the last matching element.
163 #[must_use]
164 pub fn last(&self) -> Locator<'a> {
165 Locator {
166 page: self.page,
167 selector: Selector::Nth {
168 base: Box::new(self.selector.clone()),
169 index: -1,
170 },
171 options: self.options.clone(),
172 }
173 }
174
175 /// Select the nth matching element (0-indexed).
176 #[must_use]
177 pub fn nth(&self, index: i32) -> Locator<'a> {
178 Locator {
179 page: self.page,
180 selector: Selector::Nth {
181 base: Box::new(self.selector.clone()),
182 index,
183 },
184 options: self.options.clone(),
185 }
186 }
187
188 /// Convert the selector to a JavaScript expression for CDP evaluation.
189 pub(crate) fn to_js_selector(&self) -> String {
190 self.selector.to_js_expression()
191 }
192
193 /// Create a locator that matches elements that match both this locator and `other`.
194 ///
195 /// # Example
196 ///
197 /// ```ignore
198 /// // Find visible buttons with specific text
199 /// let button = page.get_by_role(AriaRole::Button)
200 /// .and(page.get_by_text("Submit"));
201 /// ```
202 #[must_use]
203 pub fn and(&self, other: Locator<'a>) -> Locator<'a> {
204 Locator {
205 page: self.page,
206 selector: Selector::And(
207 Box::new(self.selector.clone()),
208 Box::new(other.selector),
209 ),
210 options: self.options.clone(),
211 }
212 }
213
214 /// Create a locator that matches elements that match either this locator or `other`.
215 ///
216 /// # Example
217 ///
218 /// ```ignore
219 /// // Find buttons or links
220 /// let clickable = page.get_by_role(AriaRole::Button)
221 /// .or(page.get_by_role(AriaRole::Link));
222 /// ```
223 #[must_use]
224 pub fn or(&self, other: Locator<'a>) -> Locator<'a> {
225 Locator {
226 page: self.page,
227 selector: Selector::Or(
228 Box::new(self.selector.clone()),
229 Box::new(other.selector),
230 ),
231 options: self.options.clone(),
232 }
233 }
234
235 /// Create a filter builder to narrow down the elements matched by this locator.
236 ///
237 /// # Example
238 ///
239 /// ```ignore
240 /// // Filter list items by text
241 /// let item = page.locator("li").filter().has_text("Product").build();
242 ///
243 /// // Filter by having a child element
244 /// let rows = page.locator("tr").filter().has(page.locator(".active")).build();
245 /// ```
246 pub fn filter(&self) -> FilterBuilder<'a> {
247 FilterBuilder::new(self.page, self.selector.clone(), self.options.clone())
248 }
249
250 /// Get an ARIA accessibility snapshot of this element.
251 ///
252 /// The snapshot captures the accessible tree structure as it would be
253 /// exposed to assistive technologies. This is useful for accessibility testing.
254 ///
255 /// # Example
256 ///
257 /// ```ignore
258 /// let snapshot = page.locator("form").aria_snapshot().await?;
259 /// println!("{}", snapshot); // YAML-like output
260 ///
261 /// // Compare with expected snapshot
262 /// let expected = AriaSnapshot::from_yaml(r#"
263 /// - form
264 /// - textbox "Username"
265 /// - textbox "Password"
266 /// - button "Login"
267 /// "#)?;
268 /// assert!(snapshot.matches(&expected));
269 /// ```
270 ///
271 /// # Errors
272 ///
273 /// Returns an error if the element is not found or snapshot capture fails.
274 pub async fn aria_snapshot(&self) -> Result<AriaSnapshot, crate::error::LocatorError> {
275 use crate::error::LocatorError;
276
277 if self.page.is_closed() {
278 return Err(LocatorError::PageClosed);
279 }
280
281 // Get the element and evaluate ARIA snapshot
282 let js_selector = self.selector.to_js_expression();
283 let js = format!(
284 r"
285 (function() {{
286 const element = {};
287 if (!element) {{
288 return {{ error: 'Element not found' }};
289 }}
290 const getSnapshot = {};
291 return getSnapshot(element);
292 }})()
293 ",
294 js_selector,
295 aria::aria_snapshot_js()
296 );
297
298 let result: viewpoint_cdp::protocol::runtime::EvaluateResult = self
299 .page
300 .connection()
301 .send_command(
302 "Runtime.evaluate",
303 Some(viewpoint_cdp::protocol::runtime::EvaluateParams {
304 expression: js,
305 object_group: None,
306 include_command_line_api: None,
307 silent: Some(true),
308 context_id: None,
309 return_by_value: Some(true),
310 await_promise: Some(false),
311 }),
312 Some(self.page.session_id()),
313 )
314 .await?;
315
316 if let Some(exception) = result.exception_details {
317 return Err(LocatorError::EvaluationError(exception.text));
318 }
319
320 let value = result.result.value.ok_or_else(|| {
321 LocatorError::EvaluationError("No result from aria snapshot".to_string())
322 })?;
323
324 // Check for error
325 if let Some(error) = value.get("error").and_then(|e| e.as_str()) {
326 return Err(LocatorError::NotFound(error.to_string()));
327 }
328
329 // Parse the snapshot
330 let snapshot: AriaSnapshot = serde_json::from_value(value).map_err(|e| {
331 LocatorError::EvaluationError(format!("Failed to parse aria snapshot: {e}"))
332 })?;
333
334 Ok(snapshot)
335 }
336}
337
338// FilterBuilder and RoleLocatorBuilder are in filter.rs