dioxus_transition/utils/
dom.rs

1use gloo::utils::window;
2use wasm_bindgen::{JsCast, closure::Closure};
3
4#[macro_export]
5macro_rules! animate {
6    ($element:expr, $duration:expr) => {
7        $element.style().set_property("transition", $duration)?;
8
9        $element
10            .style()
11            .set_property("transition-timing-function", "ease-in-out")?;
12    };
13    ($element:expr => using $class:expr => for $duration:expr => forwards) => {
14        $element.class_list().add_1($class)?;
15        animate!($element, $duration);
16    };
17    ($element:expr => using $class:expr => for $duration:expr => backwards) => {
18        $element.class_list().remove_1($class)?;
19        animate!($element, $duration);
20    };
21}
22
23#[macro_export]
24macro_rules! element_by_id {
25    ($id:expr) => {{
26        use wasm_bindgen::JsCast;
27
28        gloo::utils::document()
29            .get_element_by_id($id)
30            .and_then(|element| element.dyn_into::<web_sys::HtmlElement>().ok())
31    }};
32}
33
34#[macro_export]
35macro_rules! wait_for {
36    ($ms:expr) => {
37        async_std::task::sleep(instant::Duration::from_millis($ms as u64))
38    };
39}
40
41pub(crate) async fn request_animation_frame() {
42    use futures_channel::oneshot;
43
44    let (tx, rx) = oneshot::channel::<()>();
45    let mut tx = Some(tx);
46
47    let callback = Closure::wrap(Box::new(move || {
48        if let Some(tx) = tx.take() {
49            let _ = tx.send(());
50        }
51    }) as Box<dyn FnMut()>);
52
53    let _ = window()
54        .request_animation_frame(callback.as_ref().unchecked_ref());
55
56    callback.forget();
57
58    rx.await.expect("Failed to receive the animation frame")
59}