1
0

control_focus.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //! Managing focus
  2. //!
  3. //! This example shows how to manage focus in a Dioxus application. We implement a "roulette" that focuses on each input
  4. //! in the grid every few milliseconds until the user interacts with the inputs.
  5. use std::rc::Rc;
  6. use dioxus::prelude::*;
  7. fn main() {
  8. launch_desktop(app);
  9. }
  10. fn app() -> Element {
  11. // Element data is stored as Rc<MountedData> so we can clone it and pass it around
  12. let mut elements = use_signal(Vec::<Rc<MountedData>>::new);
  13. let mut running = use_signal(|| true);
  14. use_future(move || async move {
  15. let mut focused = 0;
  16. loop {
  17. tokio::time::sleep(std::time::Duration::from_millis(50)).await;
  18. if !running() {
  19. continue;
  20. }
  21. if let Some(element) = elements.with(|f| f.get(focused).cloned()) {
  22. _ = element.set_focus(true).await;
  23. } else {
  24. focused = 0;
  25. }
  26. focused += 1;
  27. }
  28. });
  29. rsx! {
  30. style { {include_str!("./assets/roulette.css")} }
  31. h1 { "Input Roulette" }
  32. button { onclick: move |_| running.toggle(), "Toggle roulette" }
  33. div { id: "roulette-grid",
  34. // Restart the roulette if the user presses escape
  35. onkeydown: move |event| {
  36. if event.code().to_string() == "Escape" {
  37. running.set(true);
  38. }
  39. },
  40. // Draw the grid of inputs
  41. for i in 0..100 {
  42. input {
  43. r#type: "number",
  44. value: "{i}",
  45. onmounted: move |cx| elements.write().push(cx.data()),
  46. oninput: move |_| running.set(false),
  47. }
  48. }
  49. }
  50. }
  51. }