web_sys_ec/
wait.rs

1use crate::{until_impl, until_not_impl, Condition, WaitOptions};
2
3/// Wait for a condition to be met.
4///
5/// Returnsa a `Wait` struct that can be used to wait for a condition to be met.
6///
7/// You can pass a duration in seconds, a tuple of seconds and poll frequency in seconds,
8/// a `std::time::Duration`... etc. See the `from` implementations of [`WaitOptions`]
9/// struct for more details.
10#[allow(non_snake_case)]
11pub fn Wait<T>(options: T) -> Wait
12where
13    T: Into<WaitOptions>,
14{
15    Wait {
16        options: options.into(),
17    }
18}
19
20#[doc(hidden)]
21#[derive(Debug)]
22pub struct Wait {
23    pub(crate) options: WaitOptions,
24}
25
26impl Wait {
27    /// Wait until the given condition is met.
28    ///
29    /// Panics with a detailed error message if the condition is not met
30    /// in the given time.
31    #[allow(ungated_async_fn_track_caller)]
32    #[track_caller]
33    #[allow(private_bounds)]
34    pub async fn until(self, condition: impl Into<Condition>) {
35        until_impl(
36            condition.into(),
37            self,
38            #[cfg(feature = "nightly")]
39            std::panic::Location::caller(),
40        )
41        .await;
42    }
43
44    /// Wait until the given condition is not met.
45    ///
46    /// Panics with a detailed error message if the condition is still
47    /// meeting when the given time expires.
48    #[allow(ungated_async_fn_track_caller)]
49    #[track_caller]
50    #[allow(private_bounds)]
51    pub async fn until_not(self, condition: impl Into<Condition>) {
52        until_not_impl(
53            condition.into(),
54            self,
55            #[cfg(feature = "nightly")]
56            std::panic::Location::caller(),
57        )
58        .await;
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn waiter_from_seconds() {
68        let wait = Wait(10);
69
70        assert_eq!(wait.options.duration().as_millis(), 10000);
71        assert_eq!(wait.options.poll_frecuency().as_millis(), 200);
72
73        let wait = Wait(2);
74
75        assert_eq!(wait.options.duration().as_millis(), 2000);
76        assert_eq!(wait.options.poll_frecuency().as_millis(), 40);
77    }
78
79    #[test]
80    fn wait_from_tuple() {
81        let wait = Wait((10, 2));
82
83        assert_eq!(wait.options.duration().as_millis(), 10000);
84        assert_eq!(wait.options.poll_frecuency().as_millis(), 2000);
85
86        let wait = Wait((2, 1));
87
88        assert_eq!(wait.options.duration().as_millis(), 2000);
89        assert_eq!(wait.options.poll_frecuency().as_millis(), 1000);
90    }
91}