1
0

router.rs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //! Fullstack router intigration
  2. #![allow(non_snake_case)]
  3. use dioxus::prelude::*;
  4. /// Used by the launch macro
  5. #[doc(hidden)]
  6. pub fn RouteWithCfg<R>(cx: Scope<FullstackRouterConfig<R>>) -> Element
  7. where
  8. R: dioxus_router::prelude::Routable,
  9. <R as std::str::FromStr>::Err: std::fmt::Display,
  10. {
  11. use dioxus_router::prelude::RouterConfig;
  12. #[cfg(feature = "ssr")]
  13. let context = crate::prelude::server_context();
  14. let cfg = *cx.props;
  15. render! {
  16. dioxus_router::prelude::Router::<R> {
  17. config: move || {
  18. RouterConfig::default()
  19. .failure_external_navigation(cfg.failure_external_navigation)
  20. .history({
  21. #[cfg(feature = "ssr")]
  22. let history = dioxus_router::prelude::MemoryHistory::with_initial_path(
  23. context
  24. .request_parts().unwrap()
  25. .uri
  26. .to_string()
  27. .parse()
  28. .unwrap_or_else(|err| {
  29. tracing::error!("Failed to parse uri: {}", err);
  30. "/"
  31. .parse()
  32. .unwrap_or_else(|err| {
  33. panic!("Failed to parse uri: {}", err);
  34. })
  35. }),
  36. );
  37. #[cfg(not(feature = "ssr"))]
  38. let history = dioxus_router::prelude::WebHistory::new(
  39. None,
  40. cfg.scroll_restoration,
  41. );
  42. history
  43. })
  44. },
  45. }
  46. }
  47. }
  48. fn default_external_navigation_handler() -> fn(Scope) -> Element {
  49. dioxus_router::prelude::FailureExternalNavigation
  50. }
  51. /// The configuration for the router
  52. #[derive(Props, serde::Serialize, serde::Deserialize)]
  53. pub struct FullstackRouterConfig<R>
  54. where
  55. R: dioxus_router::prelude::Routable,
  56. <R as std::str::FromStr>::Err: std::fmt::Display,
  57. {
  58. #[serde(skip)]
  59. #[serde(default = "default_external_navigation_handler")]
  60. failure_external_navigation: fn(Scope) -> Element,
  61. scroll_restoration: bool,
  62. #[serde(skip)]
  63. phantom: std::marker::PhantomData<R>,
  64. }
  65. impl<R> Clone for FullstackRouterConfig<R>
  66. where
  67. R: dioxus_router::prelude::Routable,
  68. <R as std::str::FromStr>::Err: std::fmt::Display,
  69. {
  70. fn clone(&self) -> Self {
  71. *self
  72. }
  73. }
  74. impl<R> Copy for FullstackRouterConfig<R>
  75. where
  76. R: dioxus_router::prelude::Routable,
  77. <R as std::str::FromStr>::Err: std::fmt::Display,
  78. {
  79. }
  80. impl<R> Default for FullstackRouterConfig<R>
  81. where
  82. R: dioxus_router::prelude::Routable,
  83. <R as std::str::FromStr>::Err: std::fmt::Display,
  84. {
  85. fn default() -> Self {
  86. Self {
  87. failure_external_navigation: dioxus_router::prelude::FailureExternalNavigation,
  88. scroll_restoration: true,
  89. phantom: std::marker::PhantomData,
  90. }
  91. }
  92. }