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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
use tokio::time::{delay_for, Duration, Instant};

use futures::Future;
use serde::{Deserialize, Serialize};
use std::mem;
use std::pin::Pin;
use std::sync::Arc;
use stringmatch::Needle;
use thirtyfour::error::{WebDriverError, WebDriverErrorInfo};
use thirtyfour::prelude::{WebDriver, WebDriverResult};
use thirtyfour::{By, WebDriverCommands, WebDriverSession, WebElement};

/// Get String containing comma-separated list of selectors used.
fn get_selector_summary(selectors: &[ElementSelector]) -> String {
    let criteria: Vec<String> = selectors.iter().map(|s| s.by.to_string()).collect();
    format!("[{}]", criteria.join(","))
}

/// Helper function to return the NoSuchElement error struct.
fn no_such_element(selectors: &[ElementSelector]) -> WebDriverError {
    WebDriverError::NoSuchElement(WebDriverErrorInfo::new(&format!(
        "Element(s) not found using selectors: {}",
        &get_selector_summary(selectors)
    )))
}

/// Parameters used to determine the polling / timeout behaviour.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub enum ElementPoller {
    /// No polling, single attempt.
    NoWait,
    /// Poll up to the specified timeout, with the specified interval being the
    /// minimum time elapsed between the start of each poll attempt.
    /// If the previous poll attempt took longer than the interval, the next will
    /// start immediately. Once the timeout is reached, a Timeout error will be
    /// returned regardless of the actual number of polling attempts completed.
    TimeoutWithInterval(Duration, Duration),
    /// Poll once every interval, up to the maximum number of polling attempts.
    /// If the previous poll attempt took longer than the interval, the next will
    /// start immediately. However, in the case that the desired element is not
    /// found, you will be guaranteed the specified number of polling attempts,
    /// regardless of how long it takes.
    NumTriesWithInterval(u32, Duration),
    /// Poll once every interval, up to the specified timeout, or the specified
    /// minimum number of polling attempts, whichever comes last.
    /// If the previous poll attempt took longer than the interval, the next will
    /// start immediately. If the timeout was reached before the minimum number
    /// of polling attempts has been executed, then the query will continue
    /// polling until the number of polling attempts equals the specified minimum.
    /// If the minimum number of polling attempts is reached prior to the
    /// specified timeout, then the polling attempts will continue until the
    /// timeout is reached instead.
    TimeoutWithIntervalAndMinTries(Duration, Duration, u32),
}

/// Function signature for element filters.
pub(crate) type ElementPredicate = Box<
    dyn for<'a> Fn(
            &'a WebElement<'a>,
        ) -> Pin<Box<dyn Future<Output = WebDriverResult<bool>> + Send + 'a>>
        + Send
        + Sync
        + 'static,
>;

/// An ElementSelector contains a selector method (By) as well as zero or more filters.
/// The filters will be applied to any elements matched by the selector.
/// Selectors and filters all run in full on every poll iteration.
pub struct ElementSelector<'a> {
    /// If false (default), find_elements() will be used. If true, find_element() will be used
    /// instead. See notes below for `with_single_selector()` for potential pitfalls.
    pub single: bool,
    pub by: By<'a>,
    pub filters: Vec<ElementPredicate>,
}

impl<'a> ElementSelector<'a> {
    //
    // Constructor
    //

    pub fn new(by: By<'a>) -> Self {
        Self {
            single: false,
            by: by.clone(),
            filters: Vec::new(),
        }
    }

    //
    // Configurator
    //

    /// Call `set_single()` to tell this selector to use find_element() rather than
    /// find_elements(). This can be slightly faster but only really makes sense if
    /// (1) you're not using any filters and (2) you're only interested in the first
    /// element matched anyway.
    pub fn set_single(&mut self) {
        self.single = true;
    }

    /// Add the specified filter to the list of filters for this selector.
    pub fn add_filter(&mut self, f: ElementPredicate) {
        self.filters.push(f);
    }

    //
    // Runner
    //

    /// Run all filters for this selector on the specified WebElement vec.
    pub async fn run_filters<'b>(
        &self,
        mut elements: Vec<WebElement<'b>>,
    ) -> WebDriverResult<Vec<WebElement<'b>>> {
        for func in &self.filters {
            let tmp_elements = mem::replace(&mut elements, Vec::new());
            for element in tmp_elements {
                if func(&element).await? {
                    elements.push(element);
                }
            }

            if elements.is_empty() {
                break;
            }
        }

        Ok(elements)
    }
}

/// Elements can be queried from either a WebDriver or from a WebElement.
/// The command issued to the webdriver will differ depending on the source,
/// i.e. FindElement vs FindElementFromElement etc. but the ElementQuery
/// interface is the same for both.
pub enum ElementQuerySource<'a> {
    Driver(&'a WebDriverSession),
    Element(&'a WebElement<'a>),
}

/// High-level interface for performing powerful element queries using a
/// builder pattern.
///
/// # Example:
/// ```rust
/// # use thirtyfour::prelude::*;
/// # use thirtyfour::support::block_on;
/// # use thirtyfour_query::{ElementPoller, ElementQueryable};
/// # use std::time::Duration;
/// #
/// # fn main() -> WebDriverResult<()> {
/// #     block_on(async {
/// #         let caps = DesiredCapabilities::chrome();
/// #         let mut driver = WebDriver::new("http://localhost:4444/wd/hub", &caps).await?;
/// // Disable implicit timeout in order to use new query interface.
/// driver.set_implicit_wait_timeout(Duration::new(0, 0)).await?;
///
/// let poller = ElementPoller::TimeoutWithInterval(Duration::new(10, 0), Duration::from_millis(500));
/// driver.config_mut().set("ElementPoller", poller)?;
///
/// driver.get("http://webappdemo").await?;
///
/// let elem = driver.query(By::Id("button1")).first().await?;
/// #         assert_eq!(elem.tag_name().await?, "button");
/// #         Ok(())
/// #     })
/// # }
/// ```
pub struct ElementQuery<'a> {
    source: Arc<ElementQuerySource<'a>>,
    poller: ElementPoller,
    selectors: Vec<ElementSelector<'a>>,
}

impl<'a> ElementQuery<'a> {
    //
    // Constructor
    //

    fn new(source: ElementQuerySource<'a>, poller: ElementPoller, by: By<'a>) -> Self {
        let selector = ElementSelector::new(by.clone());
        Self {
            source: Arc::new(source),
            poller,
            selectors: vec![selector],
        }
    }

    //
    // Poller / Waiter
    //

    /// Use the specified ElementPoller for this ElementQuery.
    /// This will not affect the default ElementPoller used for other queries.
    pub fn with_poller(mut self, poller: ElementPoller) -> Self {
        self.poller = poller;
        self
    }

    /// Force this ElementQuery to wait for the specified timeout, polling once
    /// after each interval. This will override the poller for this
    /// ElementQuery only.
    pub fn wait(self, timeout: Duration, interval: Duration) -> Self {
        self.with_poller(ElementPoller::TimeoutWithInterval(timeout, interval))
    }

    /// Force this ElementQuery to not wait for the specified condition(s).
    /// This will override the poller for this ElementQuery only.
    pub fn nowait(self) -> Self {
        self.with_poller(ElementPoller::NoWait)
    }

    //
    // Selectors
    //

    /// Add the specified selector to this ElementQuery. Callers should use
    /// the `or()` method instead.
    fn add_selector(mut self, selector: ElementSelector<'a>) -> Self {
        self.selectors.push(selector);
        self
    }

    /// Add a new selector to this ElementQuery. All conditions specified after
    /// this selector (up until the next `or()` method) will apply to this
    /// selector.
    pub fn or(self, by: By<'a>) -> Self {
        self.add_selector(ElementSelector::new(by))
    }

    //
    // Retrievers
    //

    /// Return true if an element matches any selector, otherwise false.
    pub async fn exists(&self) -> WebDriverResult<bool> {
        let elements = self.run_poller(false).await?;
        Ok(!elements.is_empty())
    }

    /// Return true if no element matches any selector, otherwise false.
    pub async fn not_exists(&self) -> WebDriverResult<bool> {
        let elements = self.run_poller(true).await?;
        Ok(elements.is_empty())
    }

    /// Return only the first WebElement that matches any selector (including all of
    /// the filters for that selector).
    pub async fn first(&self) -> WebDriverResult<WebElement<'a>> {
        let mut elements = self.run_poller(false).await?;

        if elements.is_empty() {
            Err(no_such_element(&self.selectors))
        } else {
            Ok(elements.remove(0))
        }
    }

    /// Return all WebElements that match any one selector (including all of the
    /// filters for that selector).
    ///
    /// Returns an empty Vec if no elements match.
    pub async fn all(&self) -> WebDriverResult<Vec<WebElement<'a>>> {
        self.run_poller(false).await
    }

    /// Return all WebElements that match any one selector (including all of the
    /// filters for that selector).
    ///
    /// Returns Err(WebDriverError::NoSuchElement) if no elements match.
    pub async fn all_required(&self) -> WebDriverResult<Vec<WebElement<'a>>> {
        let elements = self.run_poller(false).await?;

        if elements.is_empty() {
            Err(no_such_element(&self.selectors))
        } else {
            Ok(elements)
        }
    }

    //
    // Helper Retrievers
    //

    /// Run the poller for this ElementQuery and return the Vec of WebElements matched.
    async fn run_poller(&self, inverted: bool) -> WebDriverResult<Vec<WebElement<'a>>> {
        match self.poller {
            ElementPoller::NoWait => self.run_poller_with_options(None, None, 0, inverted).await,
            ElementPoller::TimeoutWithInterval(timeout, interval) => {
                self.run_poller_with_options(Some(timeout), Some(interval), 0, inverted).await
            }
            ElementPoller::NumTriesWithInterval(max_tries, interval) => {
                self.run_poller_with_options(None, Some(interval), max_tries, inverted).await
            }
            ElementPoller::TimeoutWithIntervalAndMinTries(timeout, interval, min_tries) => {
                self.run_poller_with_options(Some(timeout), Some(interval), min_tries, inverted)
                    .await
            }
        }
    }

    /// Run the specified poller with the corresponding timeout, interval
    /// and num_tries parameters.
    /// NOTE: This function doesn't return a no_such_element error and the user has to handle it
    async fn run_poller_with_options(
        &self,
        timeout: Option<Duration>,
        interval: Option<Duration>,
        min_tries: u32,
        inverted: bool,
    ) -> WebDriverResult<Vec<WebElement<'a>>> {
        let no_such_element_error = no_such_element(&self.selectors);
        if self.selectors.is_empty() {
            return Err(no_such_element_error);
        }
        let mut tries = 0;

        let check = |value: bool| {
            if inverted {
                !value
            } else {
                value
            }
        };

        let start = Instant::now();
        loop {
            tries += 1;

            for selector in &self.selectors {
                let mut elements = match self.fetch_elements_from_source(selector).await {
                    Ok(x) => x,
                    Err(WebDriverError::NoSuchElement(_)) => Vec::new(),
                    Err(e) => return Err(e),
                };

                if !elements.is_empty() {
                    elements = selector.run_filters(elements).await?;
                }

                if check(!elements.is_empty()) {
                    return Ok(elements);
                }

                if let Some(t) = timeout {
                    if start.elapsed() >= t && tries >= min_tries {
                        return Ok(Vec::new());
                    }
                }
            }

            if timeout.is_none() && tries >= min_tries {
                return Ok(Vec::new());
            }

            if let Some(i) = interval {
                // Next poll is due no earlier than this long after the first poll started.
                let minimum_elapsed = i * tries;

                // But this much time has elapsed since the first poll started.
                let actual_elapsed = start.elapsed();

                if actual_elapsed < minimum_elapsed {
                    // So we need to wait this much longer.
                    delay_for(minimum_elapsed - actual_elapsed).await;
                }
            }
        }
    }

    /// Execute the specified selector and return any matched WebElements.
    fn fetch_elements_from_source(
        &self,
        selector: &ElementSelector<'a>,
    ) -> impl Future<Output = WebDriverResult<Vec<WebElement<'a>>>> + Send {
        let by = selector.by.clone();
        let single = selector.single;
        let source = self.source.clone();
        async move {
            match single {
                true => match source.as_ref() {
                    ElementQuerySource::Driver(driver) => {
                        driver.find_element(by).await.map(|x| vec![x])
                    }
                    ElementQuerySource::Element(element) => {
                        element.find_element(by).await.map(|x| vec![x])
                    }
                },
                false => match source.as_ref() {
                    ElementQuerySource::Driver(driver) => driver.find_elements(by).await,
                    ElementQuerySource::Element(element) => element.find_elements(by).await,
                },
            }
        }
    }

    //
    // Filters
    //

    /// Add the specified ElementPredicate to the last selector.
    pub fn with_filter(mut self, f: ElementPredicate) -> Self {
        if let Some(selector) = self.selectors.last_mut() {
            selector.add_filter(f);
        }
        self
    }

    /// Set the previous selector to only return the first matched element.
    /// WARNING: Use with caution! This can result in faster lookups, but will probably break
    ///          any filters on this selector.
    ///
    /// If you are simply want to get the first element after filtering from a list,
    /// use the `first()` method instead.
    pub fn with_single_selector(mut self) -> Self {
        if let Some(selector) = self.selectors.last_mut() {
            selector.set_single();
        }
        self
    }

    //
    // Advance selectors
    //

    /// Only match elements that are enabled.
    pub fn and_enabled(self) -> Self {
        self.with_filter(Box::new(|elem| {
            Box::pin(async move { elem.is_enabled().await.or(Ok(false)) })
        }))
    }

    /// Only match elements that are NOT enabled.
    pub fn and_not_enabled(self) -> Self {
        self.with_filter(Box::new(|elem| {
            Box::pin(async move { elem.is_enabled().await.map(|x| !x).or(Ok(false)) })
        }))
    }

    /// Only match elements that are selected.
    pub fn and_selected(self) -> Self {
        self.with_filter(Box::new(|elem| {
            Box::pin(async move { elem.is_selected().await.or(Ok(false)) })
        }))
    }

    /// Only match elements that are NOT selected.
    pub fn and_not_selected(self) -> Self {
        self.with_filter(Box::new(|elem| {
            Box::pin(async move { elem.is_selected().await.map(|x| !x).or(Ok(false)) })
        }))
    }

    /// Only match elements that are displayed.
    pub fn and_displayed(self) -> Self {
        self.with_filter(Box::new(|elem| {
            Box::pin(async move { elem.is_displayed().await.or(Ok(false)) })
        }))
    }

    /// Only match elements that are NOT displayed.
    pub fn and_not_displayed(self) -> Self {
        self.with_filter(Box::new(|elem| {
            Box::pin(async move { elem.is_displayed().await.map(|x| !x).or(Ok(false)) })
        }))
    }

    /// Only match elements that are clickable.
    pub fn and_clickable(self) -> Self {
        self.with_filter(Box::new(|elem| {
            Box::pin(async move { elem.is_clickable().await.or(Ok(false)) })
        }))
    }

    /// Only match elements that are NOT clickable.
    pub fn and_not_clickable(self) -> Self {
        self.with_filter(Box::new(|elem| {
            Box::pin(async move { elem.is_clickable().await.map(|x| !x).or(Ok(false)) })
        }))
    }

    //
    // By alternative helper selectors
    //

    /// Only match elements that have the specified text.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_text<N>(self, text: N) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        self.with_filter(Box::new(move |elem| {
            let text = text.clone();
            Box::pin(async move { elem.text().await.map(|x| text.is_match(&x)).or(Ok(false)) })
        }))
    }

    /// Only match elements that have the specified id.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_id<N>(self, id: N) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        self.with_filter(Box::new(move |elem| {
            let id = id.clone();
            Box::pin(async move {
                match elem.id().await {
                    Ok(Some(x)) => Ok(id.is_match(&x)),
                    _ => Ok(false),
                }
            })
        }))
    }

    /// Only match elements that have the specified class name.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_class<N>(self, class_name: N) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        self.with_filter(Box::new(move |elem| {
            let class_name = class_name.clone();
            Box::pin(async move {
                match elem.class_name().await {
                    Ok(Some(x)) => Ok(class_name.is_match(&x)),
                    _ => Ok(false),
                }
            })
        }))
    }

    /// Only match elements that have the specified tag.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_tag<N>(self, tag_name: N) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        self.with_filter(Box::new(move |elem| {
            let tag_name = tag_name.clone();
            Box::pin(
                async move { elem.tag_name().await.map(|x| tag_name.is_match(&x)).or(Ok(false)) },
            )
        }))
    }

    /// Only match elements that have the specified value.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_value<N>(self, value: N) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        self.with_filter(Box::new(move |elem| {
            let value = value.clone();
            Box::pin(async move {
                match elem.value().await {
                    Ok(Some(x)) => Ok(value.is_match(&x)),
                    _ => Ok(false),
                }
            })
        }))
    }

    /// Only match elements that have the specified attribute with the specified value.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_attribute<N>(self, attribute_name: &str, value: N) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        let attribute_name = attribute_name.to_string();
        self.with_filter(Box::new(move |elem| {
            let attribute_name = attribute_name.clone();
            let value = value.clone();
            Box::pin(async move {
                match elem.get_attribute(&attribute_name).await {
                    Ok(Some(x)) => Ok(value.is_match(&x)),
                    _ => Ok(false),
                }
            })
        }))
    }

    /// Only match elements that have the specified attributes with the specified values.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_attributes<N>(self, desired_attributes: &'static [(String, N)]) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        self.with_filter(Box::new(move |elem| {
            Box::pin(async move {
                for (attribute_name, value) in desired_attributes {
                    match elem.get_attribute(&attribute_name).await {
                        Ok(Some(x)) => {
                            if !value.is_match(&x) {
                                return Ok(false);
                            }
                        }
                        _ => return Ok(false),
                    }
                }
                Ok(true)
            })
        }))
    }

    /// Only match elements that have the specified property with the specified value.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_property<N>(self, property_name: &str, value: N) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        let property_name = property_name.to_string();
        self.with_filter(Box::new(move |elem| {
            let property_name = property_name.clone();
            let value = value.clone();
            Box::pin(async move {
                match elem.get_property(&property_name).await {
                    Ok(Some(x)) => Ok(value.is_match(&x)),
                    _ => Ok(false),
                }
            })
        }))
    }

    /// Only match elements that have the specified properties with the specified value.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_properties<N>(self, desired_properties: &'static [(&str, N)]) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        self.with_filter(Box::new(move |elem| {
            Box::pin(async move {
                for (property_name, value) in desired_properties {
                    match elem.get_property(property_name).await {
                        Ok(Some(x)) => {
                            if !value.is_match(&x) {
                                return Ok(false);
                            }
                        }
                        _ => return Ok(false),
                    }
                }
                Ok(true)
            })
        }))
    }

    /// Only match elements that have the specified CSS property with the specified value.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_css_property<N>(self, css_property_name: &str, value: N) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        let css_property_name = css_property_name.to_string();
        self.with_filter(Box::new(move |elem| {
            let css_property_name = css_property_name.clone();
            let value = value.clone();
            Box::pin(async move {
                match elem.get_css_property(&css_property_name).await {
                    Ok(x) => Ok(value.is_match(&x)),
                    _ => Ok(false),
                }
            })
        }))
    }

    /// Only match elements that have the specified CSS properties with the
    /// specified values.
    /// See the `Needle` documentation for more details on text matching rules.
    pub fn with_css_properties<N>(self, desired_css_properties: &'static [(&str, N)]) -> Self
    where
        N: Needle + Clone + Send + Sync + 'static,
    {
        self.with_filter(Box::new(move |elem| {
            Box::pin(async move {
                for (css_property_name, value) in desired_css_properties {
                    match elem.get_css_property(css_property_name).await {
                        Ok(x) => {
                            if !value.is_match(&x) {
                                return Ok(false);
                            }
                        }
                        _ => return Ok(false),
                    }
                }
                Ok(true)
            })
        }))
    }
}

/// Trait for enabling the ElementQuery interface.
pub trait ElementQueryable {
    fn query<'a>(&'a self, by: By<'a>) -> ElementQuery<'a>;
}

impl ElementQueryable for WebElement<'_> {
    /// Return an ElementQuery instance for more executing powerful element queries.
    fn query<'a>(&'a self, by: By<'a>) -> ElementQuery<'a> {
        let poller: ElementPoller =
            self.session.config().get("ElementPoller").unwrap_or(ElementPoller::NoWait);
        ElementQuery::new(ElementQuerySource::Element(&self), poller, by)
    }
}

impl ElementQueryable for WebDriver {
    /// Return an ElementQuery instance for more executing powerful element queries.
    fn query<'a>(&'a self, by: By<'a>) -> ElementQuery<'a> {
        let poller: ElementPoller =
            self.config().get("ElementPoller").unwrap_or(ElementPoller::NoWait);
        ElementQuery::new(ElementQuerySource::Driver(&self.session), poller, by)
    }
}

#[cfg(test)]
/// This function checks if the public async methods implement Send. It is not intended to be executed.
async fn _test_is_send() -> WebDriverResult<()> {
    use thirtyfour::prelude::*;

    // Helper methods
    fn is_send<T: Send>() {}
    fn is_send_val<T: Send>(_val: &T) {}

    // ElementSelector
    let selector = ElementSelector::new(By::Css("div"));
    is_send_val(&selector.run_filters(Vec::new()));

    // Pre values
    let caps = DesiredCapabilities::chrome();
    let driver = WebDriver::new("http://localhost:4444", &caps).await?;

    // ElementQuery
    let query = driver.query(By::Css("div"));
    is_send_val(&query.exists());
    is_send_val(&query.not_exists());
    is_send_val(&query.first());
    is_send_val(&query.all());
    is_send_val(&query.all_required());

    Ok(())
}