Skip to main content

thirtyfour/components/wrapper/
resolver.rs

1use std::fmt::{Debug, Formatter};
2use std::sync::Arc;
3
4use arc_swap::ArcSwap;
5use tokio::sync::OnceCell;
6
7use crate::components::Component;
8use crate::error::WebDriverResult;
9use crate::extensions::query::ElementQueryOptions;
10use crate::prelude::ElementQueryable;
11use crate::{By, DynElementQueryFn, ElementQueryFn, TypingData, WebElement};
12
13/// Type alias for `ElementResolver<WebElement>`, for convenience.
14pub type ElementResolverSingle = ElementResolver<WebElement>;
15/// Type alias for `ElementResolver<Vec<WebElement>>` for convenience.
16pub type ElementResolverMulti = ElementResolver<Vec<WebElement>>;
17
18/// `resolve!(x)` expands to `x.resolve().await?`
19#[macro_export]
20macro_rules! resolve {
21    ($a:expr) => {
22        $a.resolve().await?
23    };
24}
25
26/// `resolve_present!(x)` expands to `x.resolve_present().await?`
27#[macro_export]
28macro_rules! resolve_present {
29    ($a:expr) => {
30        $a.resolve_present().await?
31    };
32}
33
34/// Element resolver that can resolve a particular element or list of elements on demand.
35///
36/// Once resolved, the result will be cached for later retrieval until manually invalidated.
37#[derive(Clone)]
38pub struct ElementResolver<T> {
39    base_element: WebElement,
40    query_fn: Arc<DynElementQueryFn<T>>,
41    element: Arc<ArcSwap<OnceCell<T>>>,
42}
43
44impl<T: Debug> Debug for ElementResolver<T> {
45    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
46        let guard = self.element.load();
47        f.debug_struct("ElementResolver")
48            .field("base_element", &self.base_element)
49            .field("element", &guard.get())
50            .finish()
51    }
52}
53
54impl<T: Clone + 'static> ElementResolver<T> {
55    /// Create a new resolver using a custom resolver function.
56    pub fn new_custom(
57        base_element: WebElement,
58        query_fn: impl ElementQueryFn<T> + 'static,
59    ) -> Self {
60        Self {
61            base_element,
62            query_fn: DynElementQueryFn::arc(query_fn),
63            element: Arc::new(ArcSwap::from_pointee(OnceCell::new())),
64        }
65    }
66
67    fn peek(&self) -> Option<T> {
68        self.element.load().get().cloned()
69    }
70
71    /// Return the cached element(s) if any, otherwise run the query and return the result.
72    pub async fn resolve(&self) -> WebDriverResult<T> {
73        self.element
74            .load()
75            .get_or_try_init(|| self.query_fn.call(self.base_element.clone()))
76            .await
77            .cloned()
78    }
79
80    /// Invalidate any cached element(s).
81    pub fn invalidate(&self) {
82        if self.element.load().initialized() {
83            self.element.store(Arc::new(OnceCell::new()));
84        }
85    }
86
87    /// Run the query, ignoring any cached element(s).
88    pub async fn resolve_force(&self) -> WebDriverResult<T>
89    where
90        T: Clone,
91    {
92        self.invalidate();
93        self.resolve().await
94    }
95}
96
97mod sealed {
98    use std::future::Future;
99
100    use futures_util::{StreamExt, TryStreamExt};
101
102    use crate::WebElement;
103    use crate::components::Component;
104    use crate::error::WebDriverResult;
105
106    pub trait Resolve: Sized {
107        fn is_present(&self) -> impl Future<Output = WebDriverResult<bool>> + Send;
108    }
109
110    impl Resolve for WebElement {
111        async fn is_present(&self) -> WebDriverResult<bool> {
112            self.is_present().await
113        }
114    }
115
116    impl<T: Component + Sync> Resolve for T {
117        async fn is_present(&self) -> WebDriverResult<bool> {
118            self.base_element().is_present().await
119        }
120    }
121
122    impl<T: Resolve + Sync> Resolve for Vec<T> {
123        fn is_present(&self) -> impl Future<Output = WebDriverResult<bool>> + Send {
124            futures_util::stream::iter(self)
125                .map(Resolve::is_present)
126                // 16 is arbitrary, just don't send too many requests at the same time
127                .buffer_unordered(self.len().min(16))
128                .try_all(std::future::ready)
129        }
130    }
131}
132
133/// Either an element or component, or a Vec of [`Resolve`]
134pub trait Resolve: sealed::Resolve {}
135impl<T: sealed::Resolve> Resolve for T {}
136
137impl<T: Resolve + Clone + 'static> ElementResolver<T> {
138    /// Validate that the cached component is present, and if so, return it.
139    pub async fn validate(&self) -> WebDriverResult<Option<T>> {
140        match self.peek() {
141            Some(component) => Ok(component.is_present().await?.then_some(component)),
142            None => Ok(None),
143        }
144    }
145
146    /// Validate the element or component and repeat the query if it is not present, returning the result.
147    ///
148    /// If the component is already present, the cached component will be returned without
149    /// performing an additional query.
150    pub async fn resolve_present(&self) -> WebDriverResult<T> {
151        match self.validate().await? {
152            Some(component) => Ok(component),
153            None => self.resolve_force().await,
154        }
155    }
156}
157
158impl ElementResolver<WebElement> {
159    /// Resolve a present element and call [`WebElement::click()`] on it.
160    ///
161    /// This validates the cached element and re-runs the resolver first if it is stale.
162    pub async fn click(&self) -> WebDriverResult<()> {
163        self.resolve_present().await?.click().await
164    }
165
166    /// Resolve a present element and call [`WebElement::click_when_ready()`] on it.
167    ///
168    /// The click can still fail if, for example, the element becomes stale or another element
169    /// intercepts the click after the readiness check. This does not retry the click or wait for
170    /// an application outcome.
171    pub async fn click_when_ready(&self) -> WebDriverResult<()> {
172        self.resolve_present().await?.click_when_ready().await
173    }
174
175    /// Resolve a present element and call [`WebElement::clear()`] on it.
176    pub async fn clear(&self) -> WebDriverResult<()> {
177        self.resolve_present().await?.clear().await
178    }
179
180    /// Resolve a present element and forward the specified [`TypingData`] to
181    /// [`WebElement::send_keys()`].
182    pub async fn send_keys(&self, key: impl Into<TypingData>) -> WebDriverResult<()> {
183        self.resolve_present().await?.send_keys(key).await
184    }
185
186    /// Resolve a present element and return [`WebElement::text()`].
187    pub async fn text(&self) -> WebDriverResult<String> {
188        self.resolve_present().await?.text().await
189    }
190
191    /// Resolve a present element and return its optional `value` property from
192    /// [`WebElement::value()`].
193    pub async fn value(&self) -> WebDriverResult<Option<String>> {
194        self.resolve_present().await?.value().await
195    }
196
197    /// Create a new element resolver that must return a single element.
198    pub fn new_single(base_element: WebElement, by: By) -> Self {
199        let resolver = move |elem: WebElement| {
200            let by = by.clone();
201            async move { elem.query(by).single().await }
202        };
203        Self::new_custom(base_element, resolver)
204    }
205
206    /// Create a new element resolver that must return a single element, with extra options.
207    pub fn new_single_opts(base_element: WebElement, by: By, options: ElementQueryOptions) -> Self {
208        let resolver = move |elem: WebElement| {
209            let by = by.clone();
210            let options = options.clone();
211            async move { elem.query(by).options(options).single().await }
212        };
213        Self::new_custom(base_element, resolver)
214    }
215
216    /// Create a new element resolver that returns the first element.
217    pub fn new_first(base_element: WebElement, by: By) -> Self {
218        let resolver = move |elem: WebElement| {
219            let by = by.clone();
220            async move { elem.query(by).first().await }
221        };
222        Self::new_custom(base_element, resolver)
223    }
224
225    /// Create a new element resolver that returns the first element, with extra options.
226    pub fn new_first_opts(base_element: WebElement, by: By, options: ElementQueryOptions) -> Self {
227        let resolver = move |elem: WebElement| {
228            let by = by.clone();
229            let options = options.clone();
230            async move { elem.query(by).options(options).first().await }
231        };
232        Self::new_custom(base_element, resolver)
233    }
234}
235
236impl ElementResolver<Vec<WebElement>> {
237    /// Create a new element resolver that returns all elements, if any.
238    ///
239    /// If no elements were found, this will resolve to an empty Vec.
240    pub fn new_allow_empty(base_element: WebElement, by: By) -> Self {
241        let resolver = move |elem: WebElement| {
242            let by = by.clone();
243            async move { elem.query(by).all_from_selector().await }
244        };
245        Self::new_custom(base_element, resolver)
246    }
247
248    /// Create a new element resolver that returns all elements (if any), with extra options.
249    pub fn new_allow_empty_opts(
250        base_element: WebElement,
251        by: By,
252        options: ElementQueryOptions,
253    ) -> Self {
254        let resolver = move |elem: WebElement| {
255            let by = by.clone();
256            let options = options.clone();
257            async move { elem.query(by).options(options).all_from_selector().await }
258        };
259        Self::new_custom(base_element, resolver)
260    }
261
262    /// Create a new element resolver that returns at least one element.
263    ///
264    /// If no elements were found, a NoSuchElement error will be returned by the resolver's
265    /// `resolve()` method.
266    pub fn new_not_empty(base_element: WebElement, by: By) -> Self {
267        let resolver = move |elem: WebElement| {
268            let by = by.clone();
269            async move { elem.query(by).all_from_selector_required().await }
270        };
271        Self::new_custom(base_element, resolver)
272    }
273
274    /// Create a new element resolver that returns at least one element, with extra options.
275    ///
276    /// If no elements were found, a NoSuchElement error will be returned by the resolver's
277    /// `resolve()` method.
278    pub fn new_not_empty_opts(
279        base_element: WebElement,
280        by: By,
281        options: ElementQueryOptions,
282    ) -> Self {
283        let resolver = move |elem: WebElement| {
284            let by = by.clone();
285            let options = options.clone();
286            async move { elem.query(by).options(options).all_from_selector_required().await }
287        };
288        Self::new_custom(base_element, resolver)
289    }
290}
291
292impl<T: Component + Clone + 'static> ElementResolver<T> {
293    /// Create a new element resolver that must return a single component.
294    pub fn new_single(base_element: WebElement, by: By) -> Self {
295        let resolver = move |elem: WebElement| {
296            let by = by.clone();
297            async move {
298                let elem = elem.query(by).single().await?;
299                Ok(elem.into())
300            }
301        };
302        Self::new_custom(base_element, resolver)
303    }
304
305    /// Create a new element resolver that must return a single component, with extra options.
306    pub fn new_single_opts(base_element: WebElement, by: By, options: ElementQueryOptions) -> Self {
307        let resolver = move |elem: WebElement| {
308            let by = by.clone();
309            let options = options.clone();
310            async move {
311                let elem = elem.query(by).options(options).single().await?;
312                Ok(elem.into())
313            }
314        };
315        Self::new_custom(base_element, resolver)
316    }
317
318    /// Create a new element resolver that returns the first component.
319    pub fn new_first(base_element: WebElement, by: By) -> Self {
320        let resolver = move |elem: WebElement| {
321            let by = by.clone();
322            async move {
323                let elem = elem.query(by).first().await?;
324                Ok(elem.into())
325            }
326        };
327        Self::new_custom(base_element, resolver)
328    }
329
330    /// Create a new element resolver that returns the first component, with extra options.
331    pub fn new_first_opts(base_element: WebElement, by: By, options: ElementQueryOptions) -> Self {
332        let resolver = move |elem: WebElement| {
333            let by = by.clone();
334            let options = options.clone();
335            async move {
336                let elem = elem.query(by).options(options).first().await?;
337                Ok(elem.into())
338            }
339        };
340        Self::new_custom(base_element, resolver)
341    }
342}
343
344impl<T: Component + Clone + 'static> ElementResolver<Vec<T>> {
345    /// Create a new element resolver that returns all components, if any.
346    ///
347    /// If no components were found, this will resolve to an empty Vec.
348    pub fn new_allow_empty(base_element: WebElement, by: By) -> Self {
349        let resolver = move |elem: WebElement| {
350            let by = by.clone();
351            async move {
352                let elems = elem.query(by).all_from_selector().await?;
353                Ok(elems.into_iter().map(T::from).collect())
354            }
355        };
356        Self::new_custom(base_element, resolver)
357    }
358
359    /// Create a new element resolver that returns all components (if any), with extra options.
360    pub fn new_allow_empty_opts(
361        base_element: WebElement,
362        by: By,
363        options: ElementQueryOptions,
364    ) -> Self {
365        let resolver = move |elem: WebElement| {
366            let by = by.clone();
367            let options = options.clone();
368            async move {
369                let elems = elem.query(by).options(options).all_from_selector().await?;
370                Ok(elems.into_iter().map(T::from).collect())
371            }
372        };
373        Self::new_custom(base_element, resolver)
374    }
375
376    /// Create a new element resolver that returns at least one component.
377    ///
378    /// If no components were found, a NoSuchElement error will be returned by the resolver's
379    /// `resolve()` method.
380    pub fn new_not_empty(base_element: WebElement, by: By) -> Self {
381        let resolver = move |elem: WebElement| {
382            let by = by.clone();
383            async move {
384                let elems = elem.query(by).all_from_selector_required().await?;
385                Ok(elems.into_iter().map(T::from).collect())
386            }
387        };
388        Self::new_custom(base_element, resolver)
389    }
390
391    /// Create a new element resolver that returns at least one component, with extra options.
392    ///
393    /// If no components were found, a NoSuchElement error will be returned by the resolver's
394    /// `resolve()` method.
395    pub fn new_not_empty_opts(
396        base_element: WebElement,
397        by: By,
398        options: ElementQueryOptions,
399    ) -> Self {
400        let resolver = move |elem: WebElement| {
401            let by = by.clone();
402            let options = options.clone();
403            async move {
404                let elems = elem.query(by).options(options).all_from_selector_required().await?;
405                Ok(elems.into_iter().map(T::from).collect())
406            }
407        };
408        Self::new_custom(base_element, resolver)
409    }
410}