userouter.rs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. use std::{cell::RefCell, rc::Rc};
  2. use crate::{Routable, RouterCfg, RouterService};
  3. use dioxus_core::ScopeState;
  4. /// Initialize the app's router service and provide access to `Link` components
  5. pub fn use_router<'a, R: Routable>(cx: &'a ScopeState, cfg: impl FnOnce(&mut RouterCfg)) -> &'a R {
  6. cx.use_hook(
  7. |_| {
  8. let svc: RouterService<R> = RouterService {
  9. regen_route: cx.schedule_update(),
  10. pending_routes: RefCell::new(Vec::new()),
  11. };
  12. let first_path = R::default();
  13. cx.provide_context(svc);
  14. UseRouterInner {
  15. svc: cx.consume_context::<RouterService<R>>().unwrap(),
  16. history: vec![first_path],
  17. }
  18. },
  19. |f| {
  20. let mut pending_routes = f.svc.pending_routes.borrow_mut();
  21. for route in pending_routes.drain(..) {
  22. f.history.push(route);
  23. }
  24. f.history.last().unwrap()
  25. },
  26. )
  27. }
  28. struct UseRouterInner<R: Routable> {
  29. svc: Rc<RouterService<R>>,
  30. history: Vec<R>,
  31. }