Using the JS API

JavaScript provide API to manipulate HTML elements. Async UI provides the same API, translated to Rust via wasm-bindgen and the web-sys crate. Anything you can do in JavaScript, you should be able to do here.

Let's start simple: we'll set the placeholder text in a text <input /> field.

#![allow(unused)]
fn main() {
async fn input_with_placeholder() {
    let input = Input::new();
    input.set_placeholder("enter something"); // 👈 set the placeholder
    input.render().await;
}
}

The .set_placeholder(_) method used is from web_sys. It is implemented on web_sys::HtmlInputElement, which is web-sys' translation of the same JS API (x.set_placeholder(y); is equal to x.placeholder = y; in JS).

You can call the method on async_ui_web::html::Input because our Input derefs to web_sys::HtmlInputElement.

Other Async UI HTML components deref to their web-sys counterpart too. All the methods are listed in the documentation.

Example: Countdown

This example update the content of an HTML Text Node every second.

We'll use gloo-timers to conveniently access JavaScript setTimeout. Add this in your Cargo.toml dependencies

gloo-timers = { version = "0.2.6", features = ["futures"] }

Leveraging the Ecosystem

The gloo-timers crate isn't related to Async UI, but since it provides an async API, we can use it in our Async UI app very easily.

This is one of the strengths of Async UI: it integrates very well with any async Rust code.

Now, for our countdown code

#![allow(unused)]
fn main() {
use async_ui_web::{html::Text, join};
use gloo_timers::future::TimeoutFuture; // nice async interface to `setTimeout`

async fn countdown(mut seconds: i32) {
    let text = Text::new(); // create an HTML text node

    // join two Futures:
    // * one to render the text node
    // * the other to keep updating the content of the node
    join((
        text.render(), // render the text node
        async {
            while seconds > 0 {
                // 👇 Set the content of the text node. This is `text.data = "..."` in JS.
                text.set_data(&seconds.to_string());

                // wait 1 second
                TimeoutFuture::new(1000).await;

                // decrement the count
                seconds -= 1;
            }
            // count has reached zero!
            text.set_data("boom!");
        },
    ))
    .await;
}
}

Note: Our example here is just for demonstration. For a correct countdown implementation, use setInterval instead of setTimeout.