firefox-webdriver 0.1.4

High-performance Firefox WebDriver in Rust
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
//! Element search and observation methods.

use std::sync::Arc;
use std::time::Duration;

use parking_lot::Mutex as ParkingMutex;
use tokio::sync::oneshot;
use tokio::time::timeout;
use tracing::debug;

use crate::browser::Element;
use crate::browser::selector::By;
use crate::error::{Error, Result};
use crate::identifiers::{ElementId, SubscriptionId};
use crate::protocol::event::ParsedEvent;
use crate::protocol::{Command, ElementCommand, Event};

use super::Tab;

// ============================================================================
// Constants
// ============================================================================

/// Default timeout for wait_for_element (30 seconds).
const DEFAULT_WAIT_TIMEOUT: Duration = Duration::from_secs(30);

// ============================================================================
// Tab - Element Search
// ============================================================================

impl Tab {
    /// Finds a single element using a locator strategy.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use firefox_webdriver::By;
    ///
    /// // CSS selector
    /// let btn = tab.find_element(By::Css("#submit")).await?;
    ///
    /// // By ID
    /// let form = tab.find_element(By::Id("login-form")).await?;
    ///
    /// // By text content
    /// let link = tab.find_element(By::Text("Click here")).await?;
    ///
    /// // By XPath
    /// let btn = tab.find_element(By::XPath("//button[@type='submit']")).await?;
    /// ```
    pub async fn find_element(&self, by: By) -> Result<Element> {
        let command = Command::Element(ElementCommand::Find {
            strategy: by.strategy().to_string(),
            value: by.value().to_string(),
            parent_id: None,
        });

        let response = self.send_command(command).await?;

        let element_id = response
            .result
            .as_ref()
            .and_then(|v| v.get("elementId"))
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                Error::element_not_found(
                    format!("{}:{}", by.strategy(), by.value()),
                    self.inner.tab_id,
                    self.inner.frame_id,
                )
            })?;

        Ok(Element::new(
            ElementId::new(element_id),
            self.inner.tab_id,
            self.inner.frame_id,
            self.inner.session_id,
            self.inner.window.clone(),
        ))
    }

    /// Finds all elements using a locator strategy.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use firefox_webdriver::By;
    ///
    /// let buttons = tab.find_elements(By::Tag("button")).await?;
    /// let links = tab.find_elements(By::PartialText("Read")).await?;
    /// ```
    pub async fn find_elements(&self, by: By) -> Result<Vec<Element>> {
        let command = Command::Element(ElementCommand::FindAll {
            strategy: by.strategy().to_string(),
            value: by.value().to_string(),
            parent_id: None,
        });

        let response = self.send_command(command).await?;

        let elements = response
            .result
            .as_ref()
            .and_then(|v| v.get("elementIds"))
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .map(|id| {
                        Element::new(
                            ElementId::new(id),
                            self.inner.tab_id,
                            self.inner.frame_id,
                            self.inner.session_id,
                            self.inner.window.clone(),
                        )
                    })
                    .collect()
            })
            .unwrap_or_default();

        Ok(elements)
    }
}

// ============================================================================
// Tab - Element Observation
// ============================================================================

impl Tab {
    /// Waits for an element using a locator strategy.
    ///
    /// Uses MutationObserver (no polling). Times out after 30 seconds.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use firefox_webdriver::By;
    ///
    /// let btn = tab.wait_for_element(By::Id("submit")).await?;
    /// let link = tab.wait_for_element(By::Css("a.login")).await?;
    /// let el = tab.wait_for_element(By::XPath("//button")).await?;
    /// ```
    pub async fn wait_for_element(&self, by: By) -> Result<Element> {
        self.wait_for_element_timeout(by, DEFAULT_WAIT_TIMEOUT)
            .await
    }

    /// Waits for an element using a locator strategy with custom timeout.
    pub async fn wait_for_element_timeout(
        &self,
        by: By,
        timeout_duration: Duration,
    ) -> Result<Element> {
        debug!(
            tab_id = %self.inner.tab_id,
            strategy = by.strategy(),
            value = by.value(),
            timeout_ms = timeout_duration.as_millis(),
            "Waiting for element"
        );

        let window = self.get_window()?;

        let (tx, rx) = oneshot::channel::<Result<Element>>();
        let tx = Arc::new(ParkingMutex::new(Some(tx)));
        let strategy_str = by.strategy().to_string();
        let value_str = by.value().to_string();
        let tab_id = self.inner.tab_id;
        let frame_id = self.inner.frame_id;
        let session_id = self.inner.session_id;
        let window_clone = self.inner.window.clone();
        let tx_clone = Arc::clone(&tx);

        let handler_key = format!("wait_for_element_{}_{}", strategy_str, value_str);
        let handler_key_clone = handler_key.clone();
        let expected_strategy = strategy_str.clone();
        let expected_value = value_str.clone();

        window.inner.pool.add_event_handler(
            window.inner.session_id,
            handler_key.clone(),
            Box::new(move |event: Event| {
                if event.method.as_str() != "element.added" {
                    return None;
                }

                let parsed = event.parse();
                if let ParsedEvent::ElementAdded {
                    strategy,
                    value,
                    element_id,
                    ..
                } = parsed
                    && strategy == expected_strategy
                    && value == expected_value
                {
                    let element = Element::new(
                        ElementId::new(&*element_id),
                        tab_id,
                        frame_id,
                        session_id,
                        window_clone.clone(),
                    );

                    if let Some(tx) = tx_clone.lock().take() {
                        let _ = tx.send(Ok(element));
                    }
                }

                None
            }),
        );

        let command = Command::Element(ElementCommand::Subscribe {
            strategy: strategy_str,
            value: value_str,
            one_shot: true,
            timeout: Some(timeout_duration.as_millis() as u64),
        });
        let response = self.send_command(command).await?;

        // Check if element already exists
        if let Some(element_id) = response
            .result
            .as_ref()
            .and_then(|v| v.get("elementId"))
            .and_then(|v| v.as_str())
        {
            window
                .inner
                .pool
                .remove_event_handler(window.inner.session_id, &handler_key_clone);

            return Ok(Element::new(
                ElementId::new(element_id),
                self.inner.tab_id,
                self.inner.frame_id,
                self.inner.session_id,
                self.inner.window.clone(),
            ));
        }

        let result = timeout(timeout_duration, rx).await;

        window
            .inner
            .pool
            .remove_event_handler(window.inner.session_id, &handler_key_clone);

        match result {
            Ok(Ok(element)) => element,
            Ok(Err(_)) => Err(Error::protocol("Channel closed unexpectedly")),
            Err(_) => Err(Error::Timeout {
                operation: format!("wait_for({}:{})", by.strategy(), by.value()),
                timeout_ms: timeout_duration.as_millis() as u64,
            }),
        }
    }

    /// Registers a callback for when elements matching the selector appear.
    ///
    /// # Returns
    ///
    /// Subscription ID for later unsubscription.
    pub async fn on_element_added<F>(&self, by: By, callback: F) -> Result<SubscriptionId>
    where
        F: Fn(Element) + Send + Sync + 'static,
    {
        debug!(
            tab_id = %self.inner.tab_id,
            strategy = by.strategy(),
            value = by.value(),
            "Subscribing to element.added"
        );

        let window = self.get_window()?;

        let strategy_str = by.strategy().to_string();
        let value_str = by.value().to_string();
        let tab_id = self.inner.tab_id;
        let frame_id = self.inner.frame_id;
        let session_id = self.inner.session_id;
        let window_clone = self.inner.window.clone();
        let callback = Arc::new(callback);

        let handler_key = format!("on_element_added_{}_{}", strategy_str, value_str);
        let expected_strategy = strategy_str.clone();
        let expected_value = value_str.clone();

        window.inner.pool.add_event_handler(
            window.inner.session_id,
            handler_key,
            Box::new(move |event: Event| {
                if event.method.as_str() != "element.added" {
                    return None;
                }

                let parsed = event.parse();
                if let ParsedEvent::ElementAdded {
                    strategy,
                    value,
                    element_id,
                    ..
                } = parsed
                    && strategy == expected_strategy
                    && value == expected_value
                {
                    let element = Element::new(
                        ElementId::new(&*element_id),
                        tab_id,
                        frame_id,
                        session_id,
                        window_clone.clone(),
                    );
                    callback(element);
                }

                None
            }),
        );

        let command = Command::Element(ElementCommand::Subscribe {
            strategy: strategy_str,
            value: value_str,
            one_shot: false,
            timeout: None,
        });

        let response = self.send_command(command).await?;

        let subscription_id = response
            .result
            .as_ref()
            .and_then(|v| v.get("subscriptionId"))
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::protocol("No subscriptionId in response"))?;

        Ok(SubscriptionId::new(subscription_id))
    }

    /// Registers a callback for when a specific element is removed.
    pub async fn on_element_removed<F>(&self, element_id: &ElementId, callback: F) -> Result<()>
    where
        F: Fn() + Send + Sync + 'static,
    {
        debug!(tab_id = %self.inner.tab_id, %element_id, "Watching for element removal");

        let window = self.get_window()?;

        let element_id_clone = element_id.as_str().to_string();
        let callback = Arc::new(callback);

        let handler_key = format!("on_element_removed_{}", element_id_clone);

        window.inner.pool.add_event_handler(
            window.inner.session_id,
            handler_key,
            Box::new(move |event: Event| {
                if event.method.as_str() != "element.removed" {
                    return None;
                }

                let parsed = event.parse();
                if let ParsedEvent::ElementRemoved {
                    element_id: removed_id,
                    ..
                } = parsed
                    && removed_id == element_id_clone
                {
                    callback();
                }

                None
            }),
        );

        let command = Command::Element(ElementCommand::WatchRemoval {
            element_id: element_id.clone(),
        });

        self.send_command(command).await?;
        Ok(())
    }

    /// Unsubscribes from element observation.
    pub async fn unsubscribe(&self, subscription_id: &SubscriptionId) -> Result<()> {
        let command = Command::Element(ElementCommand::Unsubscribe {
            subscription_id: subscription_id.as_str().to_string(),
        });

        self.send_command(command).await?;

        if let Some(window) = &self.inner.window {
            // Remove handlers associated with this subscription
            let key = format!("on_element_added_{}", subscription_id.as_str());
            window
                .inner
                .pool
                .remove_event_handler(window.inner.session_id, &key);
        }

        Ok(())
    }
}