xa11y-core 0.6.2

Core types, traits, and selector engine for xa11y cross-platform accessibility
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use std::sync::Arc;
use std::time::Duration;

use crate::element::{Element, ElementData};
use crate::error::{Error, Result};
use crate::event::ElementState;
use crate::provider::Provider;
use crate::selector::Selector;

/// A lazy element descriptor that re-resolves against a fresh accessibility
/// tree on every operation.
///
/// Inspired by Playwright's `Locator` pattern: a Locator never holds a live
/// reference to a UI element. Instead, it stores a selector and resolves it
/// on demand, making it immune to staleness.
///
/// # Example
/// ```ignore
/// # use xa11y::*;
/// # fn example() -> Result<()> {
/// let app = App::by_name("MyApp")?;
/// let save_btn = app.locator(r#"button[name="Save"]"#);
/// save_btn.press()?;
/// # Ok(())
/// # }
/// ```
/// Default auto-wait timeout for Locator action methods (5 seconds).
const DEFAULT_ACTION_TIMEOUT: Duration = Duration::from_secs(5);

#[derive(Clone)]
pub struct Locator {
    provider: Arc<dyn Provider>,
    /// Root element for scoped searches. `None` = system root (all apps).
    root: Option<ElementData>,
    selector: String,
    /// Which match to select (0-based). `None` means first match.
    nth: Option<usize>,
    /// Timeout for auto-wait before action methods.
    timeout: Duration,
}

impl Locator {
    /// Create a new Locator.
    ///
    /// Pass `root: None` to search the entire accessibility tree, or
    /// `Some(element)` to scope the search to that element's subtree.
    pub fn new(provider: Arc<dyn Provider>, root: Option<ElementData>, selector: &str) -> Self {
        Self {
            provider,
            root,
            selector: selector.to_string(),
            nth: None,
            timeout: DEFAULT_ACTION_TIMEOUT,
        }
    }

    /// Return a new Locator with a custom auto-wait timeout for action methods.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Return a new Locator that selects the nth match (1-based).
    ///
    /// # Panics
    /// Panics if `n` is 0. Use `.first()` or `.nth(1)` for the first match.
    pub fn nth(mut self, n: usize) -> Self {
        assert!(n > 0, "Locator::nth() is 1-based, got 0");
        self.nth = Some(n - 1); // store 0-based internally
        self
    }

    /// Return a new Locator that selects the first match.
    pub fn first(self) -> Self {
        self.nth(1)
    }

    /// Return a new Locator scoped to a direct child matching `child_selector`.
    ///
    /// Appends ` > {child_selector}` to the current selector.
    pub fn child(mut self, child_selector: &str) -> Self {
        self.selector = format!("{} > {}", self.selector, child_selector);
        self.nth = None;
        self
    }

    /// Return a new Locator scoped to a descendant matching `desc_selector`.
    ///
    /// Appends ` {desc_selector}` to the current selector.
    pub fn descendant(mut self, desc_selector: &str) -> Self {
        self.selector = format!("{} {}", self.selector, desc_selector);
        self.nth = None;
        self
    }

    /// Get the selector string.
    pub fn selector(&self) -> &str {
        &self.selector
    }

    /// Get the underlying provider.
    #[doc(hidden)]
    pub fn provider(&self) -> &Arc<dyn Provider> {
        &self.provider
    }

    /// Get the root element data, if scoped.
    #[doc(hidden)]
    pub fn root(&self) -> Option<&ElementData> {
        self.root.as_ref()
    }

    /// Get the nth index, if set.
    #[doc(hidden)]
    pub fn nth_index(&self) -> Option<usize> {
        self.nth
    }

    // ── Internal resolution ─────────────────────────────────────────

    /// Resolve the selector to a single ElementData.
    fn resolve_data(&self) -> Result<ElementData> {
        let selector = Selector::parse(&self.selector)?;
        let matches = self.provider.find_elements(
            self.root.as_ref(),
            &selector,
            // Fetch enough to satisfy nth
            Some(self.nth.unwrap_or(0) + 1),
            None,
        )?;
        let idx = self.nth.unwrap_or(0);
        matches
            .into_iter()
            .nth(idx)
            .ok_or_else(|| Error::SelectorNotMatched {
                selector: self.selector.clone(),
            })
    }

    // ── Queries (each re-queries the provider) ─────────────────────

    /// Check if a matching element exists.
    pub fn exists(&self) -> Result<bool> {
        match self.resolve_data() {
            Ok(_) => Ok(true),
            Err(Error::SelectorNotMatched { .. }) => Ok(false),
            Err(e) => Err(e),
        }
    }

    /// Count matching elements.
    pub fn count(&self) -> Result<usize> {
        let selector = Selector::parse(&self.selector)?;
        let matches = self
            .provider
            .find_elements(self.root.as_ref(), &selector, None, None)?;
        Ok(matches.len())
    }

    /// Get a single [`Element`] handle.
    pub fn element(&self) -> Result<Element> {
        let data = self.resolve_data()?;
        Ok(Element::new(data, Arc::clone(&self.provider)))
    }

    /// Get all matching elements.
    pub fn elements(&self) -> Result<Vec<Element>> {
        let selector = Selector::parse(&self.selector)?;
        let matches = self
            .provider
            .find_elements(self.root.as_ref(), &selector, None, None)?;
        Ok(matches
            .into_iter()
            .map(|d| Element::new(d, Arc::clone(&self.provider)))
            .collect())
    }

    // ── Auto-wait ──────────────────────────────────────────────────

    /// Poll until the element is attached, visible, and enabled, returning its data.
    fn auto_wait(&self) -> Result<ElementData> {
        let start = std::time::Instant::now();
        let poll_interval = Duration::from_millis(100);

        loop {
            let elapsed = start.elapsed();
            if elapsed >= self.timeout {
                return Err(Error::Timeout { elapsed });
            }

            match self.resolve_data() {
                Ok(data) if data.states.visible && data.states.enabled => return Ok(data),
                Ok(_) | Err(Error::SelectorNotMatched { .. }) => {
                    // Not yet actionable — poll again
                }
                Err(e) => return Err(e),
            }

            std::thread::sleep(poll_interval);
        }
    }

    // ── Common actions (auto-wait, then delegate to provider) ──────

    /// Click / invoke the matched element.
    pub fn press(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.press(&el)
    }

    /// Set keyboard focus on the matched element.
    pub fn focus(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.focus(&el)
    }

    /// Remove keyboard focus from the matched element.
    pub fn blur(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.blur(&el)
    }

    /// Toggle the matched element (checkbox, switch).
    pub fn toggle(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.toggle(&el)
    }

    /// Select the matched element (list item, etc.).
    pub fn select(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.select(&el)
    }

    /// Expand the matched element.
    pub fn expand(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.expand(&el)
    }

    /// Collapse the matched element.
    pub fn collapse(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.collapse(&el)
    }

    /// Show the context menu for the matched element.
    pub fn show_menu(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.show_menu(&el)
    }

    /// Increment the matched element (slider, spinner).
    pub fn increment(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.increment(&el)
    }

    /// Decrement the matched element (slider, spinner).
    pub fn decrement(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.decrement(&el)
    }

    /// Scroll the matched element into view.
    pub fn scroll_into_view(&self) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.scroll_into_view(&el)
    }

    // ── Typed operations (auto-wait, then delegate) ────────────────

    /// Set the text value of the matched element.
    pub fn set_value(&self, value: &str) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.set_value(&el, value)
    }

    /// Set the numeric value of the matched element (slider, spinner).
    pub fn set_numeric_value(&self, value: f64) -> Result<()> {
        if !value.is_finite() {
            return Err(Error::InvalidActionData {
                message: format!("set_numeric_value requires a finite value, got {}", value),
            });
        }
        let el = self.auto_wait()?;
        self.provider.set_numeric_value(&el, value)
    }

    /// Type text at the current cursor position on the matched element.
    pub fn type_text(&self, text: &str) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.type_text(&el, text)
    }

    /// Select a text range within the matched element.
    pub fn select_text(&self, start: u32, end: u32) -> Result<()> {
        if start > end {
            return Err(Error::InvalidActionData {
                message: format!("select_text start ({}) must be <= end ({})", start, end),
            });
        }
        let el = self.auto_wait()?;
        self.provider.set_text_selection(&el, start, end)
    }

    /// Scroll the matched element downward.
    pub fn scroll_down(&self, amount: f64) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.scroll_down(&el, amount)
    }

    /// Scroll the matched element upward.
    pub fn scroll_up(&self, amount: f64) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.scroll_up(&el, amount)
    }

    /// Scroll the matched element rightward.
    pub fn scroll_right(&self, amount: f64) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.scroll_right(&el, amount)
    }

    /// Scroll the matched element leftward.
    pub fn scroll_left(&self, amount: f64) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.scroll_left(&el, amount)
    }

    // ── Generic action escape hatch ────────────────────────────────

    /// Perform an action by name (with auto-wait).
    ///
    /// This is the escape hatch for platform-specific actions not covered
    /// by the named methods above. Also works for well-known action names.
    pub fn perform_action(&self, action: &str) -> Result<()> {
        let el = self.auto_wait()?;
        self.provider.perform_action(&el, action)
    }

    // ── Wait operations ─────────────────────────────────────────────

    /// Wait until the element is visible, polling the provider.
    pub fn wait_visible(&self, timeout: Duration) -> Result<Element> {
        self.wait_for_state(ElementState::Visible, timeout)
            .map(|opt| opt.expect("visible wait must return an element"))
    }

    /// Wait until the element exists.
    pub fn wait_attached(&self, timeout: Duration) -> Result<Element> {
        self.wait_for_state(ElementState::Attached, timeout)
            .map(|opt| opt.expect("attached wait must return an element"))
    }

    /// Wait until the element is removed.
    pub fn wait_detached(&self, timeout: Duration) -> Result<()> {
        self.wait_for_state(ElementState::Detached, timeout)
            .map(|_| ())
    }

    /// Wait until the element is enabled.
    pub fn wait_enabled(&self, timeout: Duration) -> Result<Element> {
        self.wait_for_state(ElementState::Enabled, timeout)
            .map(|opt| opt.expect("enabled wait must return an element"))
    }

    /// Wait until the element is disabled (exists but not enabled).
    pub fn wait_disabled(&self, timeout: Duration) -> Result<Element> {
        self.wait_for_state(ElementState::Disabled, timeout)
            .map(|opt| opt.expect("disabled wait must return an element"))
    }

    /// Wait until the element is hidden or removed.
    pub fn wait_hidden(&self, timeout: Duration) -> Result<()> {
        self.wait_for_state(ElementState::Hidden, timeout)
            .map(|_| ())
    }

    /// Wait until the element has keyboard focus.
    pub fn wait_focused(&self, timeout: Duration) -> Result<Element> {
        self.wait_for_state(ElementState::Focused, timeout)
            .map(|opt| opt.expect("focused wait must return an element"))
    }

    /// Wait until the element does not have keyboard focus.
    pub fn wait_unfocused(&self, timeout: Duration) -> Result<Element> {
        self.wait_for_state(ElementState::Unfocused, timeout)
            .map(|opt| opt.expect("unfocused wait must return an element"))
    }

    /// Wait for an [`ElementState`] condition to be met.
    pub fn wait_for_state(
        &self,
        state: ElementState,
        timeout: Duration,
    ) -> Result<Option<Element>> {
        self.poll_until(|element| state.is_met(element), timeout)
    }

    /// Wait until an arbitrary predicate is satisfied, polling at ~100 ms intervals.
    pub fn wait_until(
        &self,
        predicate: impl Fn(Option<&ElementData>) -> bool,
        timeout: Duration,
    ) -> Result<Option<Element>> {
        self.poll_until(&predicate, timeout)
    }

    /// Core polling loop shared by `wait_for_state` and `wait_until`.
    fn poll_until(
        &self,
        predicate: impl Fn(Option<&ElementData>) -> bool,
        timeout: Duration,
    ) -> Result<Option<Element>> {
        let start = std::time::Instant::now();
        let poll_interval = Duration::from_millis(100);

        loop {
            let elapsed = start.elapsed();
            if elapsed >= timeout {
                return Err(Error::Timeout { elapsed });
            }

            let matched = match self.resolve_data() {
                Ok(data) => Some(data),
                Err(Error::SelectorNotMatched { .. }) => None,
                Err(e) => return Err(e),
            };

            if predicate(matched.as_ref()) {
                return Ok(matched.map(|data| Element::new(data, Arc::clone(&self.provider))));
            }

            std::thread::sleep(poll_interval);
        }
    }
}