dioxus/examples/control_focus.rs

66 lines
1.8 KiB
Rust
Raw Normal View History

2024-02-14 20:33:07 +00:00
//! Managing focus
//!
//! This example shows how to manage focus in a Dioxus application. We implement a "roulette" that focuses on each input
//! in the grid every few milliseconds until the user interacts with the inputs.
2023-03-24 16:32:42 +00:00
use std::rc::Rc;
use async_std::task::sleep;
use dioxus::prelude::*;
const STYLE: &str = asset!("./examples/assets/roulette.css");
2023-03-24 16:32:42 +00:00
fn main() {
launch(app);
2023-03-24 16:32:42 +00:00
}
fn app() -> Element {
2024-02-14 20:33:07 +00:00
// Element data is stored as Rc<MountedData> so we can clone it and pass it around
let mut elements = use_signal(Vec::<Rc<MountedData>>::new);
let mut running = use_signal(|| true);
2023-03-24 16:32:42 +00:00
2024-01-15 21:06:05 +00:00
use_future(move || async move {
2023-03-24 16:32:42 +00:00
let mut focused = 0;
2024-02-02 22:33:02 +00:00
loop {
sleep(std::time::Duration::from_millis(50)).await;
2024-02-02 22:33:02 +00:00
if !running() {
continue;
2023-03-24 16:32:42 +00:00
}
2024-02-02 22:33:02 +00:00
if let Some(element) = elements.with(|f| f.get(focused).cloned()) {
_ = element.set_focus(true).await;
} else {
focused = 0;
}
focused += 1;
2023-03-24 16:32:42 +00:00
}
});
2024-01-16 19:18:46 +00:00
rsx! {
head::Link { rel: "stylesheet", href: STYLE }
2024-02-14 20:33:07 +00:00
h1 { "Input Roulette" }
button { onclick: move |_| running.toggle(), "Toggle roulette" }
div { id: "roulette-grid",
// Restart the roulette if the user presses escape
onkeydown: move |event| {
if event.code().to_string() == "Escape" {
running.set(true);
}
},
// Draw the grid of inputs
2023-03-24 16:32:42 +00:00
for i in 0..100 {
input {
2024-02-14 20:33:07 +00:00
r#type: "number",
2023-03-24 16:32:42 +00:00
value: "{i}",
2024-02-14 20:33:07 +00:00
onmounted: move |cx| elements.write().push(cx.data()),
oninput: move |_| running.set(false),
2023-03-24 16:32:42 +00:00
}
}
}
2024-01-14 05:12:21 +00:00
}
2023-03-24 16:32:42 +00:00
}