suspend.rs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. use dioxus::core::ElementId;
  2. use dioxus::core::{Mutation::*, SuspenseBoundary};
  3. use dioxus::prelude::*;
  4. use dioxus_core::SuspenseContext;
  5. use std::{rc::Rc, time::Duration};
  6. #[tokio::test]
  7. async fn it_works() {
  8. let mut dom = VirtualDom::new(app);
  9. let mutations = dom.rebuild().santize();
  10. // We should at least get the top-level template in
  11. assert_eq!(
  12. mutations.template_mutations,
  13. [
  14. CreateElement { name: "div" },
  15. CreateStaticText { value: "Waiting for child..." },
  16. CreatePlaceholder { id: ElementId(0) },
  17. AppendChildren { m: 2 },
  18. SaveTemplate { name: "template", m: 1 }
  19. ]
  20. );
  21. // And we should load it in and assign the placeholder properly
  22. assert_eq!(
  23. mutations.edits,
  24. [
  25. LoadTemplate { name: "template", index: 0, id: ElementId(1) },
  26. // hmmmmmmmmm.... with suspense how do we guarantee that IDs increase linearly?
  27. // can we even?
  28. AssignId { path: &[1], id: ElementId(3) },
  29. AppendChildren { m: 1 },
  30. ]
  31. );
  32. // wait just a moment, not enough time for the boundary to resolve
  33. dom.wait_for_work().await;
  34. }
  35. fn app(cx: Scope) -> Element {
  36. cx.render(rsx!(
  37. div {
  38. "Waiting for child..."
  39. suspense_boundary {}
  40. }
  41. ))
  42. }
  43. fn suspense_boundary(cx: Scope) -> Element {
  44. cx.use_hook(|| cx.provide_context(Rc::new(SuspenseBoundary::new(cx.scope_id()))));
  45. // Ensure the right types are found
  46. cx.has_context::<SuspenseContext>().unwrap();
  47. cx.render(rsx!(async_child {}))
  48. }
  49. async fn async_child(cx: Scope<'_>) -> Element {
  50. use_future!(cx, || tokio::time::sleep(Duration::from_millis(10))).await;
  51. cx.render(rsx!(async_text {}))
  52. }
  53. async fn async_text(cx: Scope<'_>) -> Element {
  54. cx.render(rsx!("async_text"))
  55. }