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.
|
|
|
|
|
2024-07-23 17:29:37 +00:00
|
|
|
use dioxus::prelude::*;
|
2023-03-24 16:32:42 +00:00
|
|
|
use std::rc::Rc;
|
|
|
|
|
2024-07-23 17:29:37 +00:00
|
|
|
const STYLE: &str = asset!(file("./examples/assets/roulette.css"));
|
2023-03-24 16:32:42 +00:00
|
|
|
|
|
|
|
fn main() {
|
2024-01-16 17:45:02 +00:00
|
|
|
launch_desktop(app);
|
2023-03-24 16:32:42 +00:00
|
|
|
}
|
|
|
|
|
2024-01-14 04:51:37 +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
|
2024-01-16 07:24:59 +00:00
|
|
|
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 {
|
2024-02-14 20:33:07 +00:00
|
|
|
tokio::time::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! {
|
2024-07-23 17:29:37 +00:00
|
|
|
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
|
|
|
}
|