use_route.rs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. use crate::{ParsedRoute, RouteContext, RouterCore, RouterService};
  2. use dioxus::core::{ScopeId, ScopeState};
  3. use std::{borrow::Cow, str::FromStr, sync::Arc};
  4. use url::Url;
  5. /// This hook provides access to information about the current location in the
  6. /// context of a [`Router`]. If this function is called outside of a `Router`
  7. /// component it will panic.
  8. pub fn use_route(cx: &ScopeState) -> &UseRoute {
  9. let handle = cx.use_hook(|_| {
  10. let router = cx
  11. .consume_context::<RouterService>()
  12. .expect("Cannot call use_route outside the scope of a Router component");
  13. let route_context = cx.consume_context::<RouteContext>();
  14. router.subscribe_onchange(cx.scope_id());
  15. UseRouteListener {
  16. state: UseRoute {
  17. route_context,
  18. route: router.current_location(),
  19. },
  20. router,
  21. scope: cx.scope_id(),
  22. }
  23. });
  24. handle.state.route = handle.router.current_location();
  25. &handle.state
  26. }
  27. /// A handle to the current location of the router.
  28. pub struct UseRoute {
  29. pub(crate) route: Arc<ParsedRoute>,
  30. /// If `use_route` is used inside a `Route` component this has some context otherwise `None`.
  31. pub(crate) route_context: Option<RouteContext>,
  32. }
  33. impl UseRoute {
  34. /// Get the underlying [`Url`] of the current location.
  35. pub fn url(&self) -> &Url {
  36. &self.route.url
  37. }
  38. /// Get the first query parameter given the parameter name.
  39. ///
  40. /// If you need to get more than one parameter, use [`query_pairs`] on the [`Url`] instead.
  41. #[cfg(feature = "query")]
  42. pub fn query<T: serde::de::DeserializeOwned>(&self) -> Option<T> {
  43. let query = self.url().query()?;
  44. serde_urlencoded::from_str(query).ok()
  45. }
  46. /// Get the first query parameter given the parameter name.
  47. ///
  48. /// If you need to get more than one parameter, use [`query_pairs`] on the [`Url`] instead.
  49. pub fn query_param(&self, param: &str) -> Option<Cow<str>> {
  50. self.route
  51. .url
  52. .query_pairs()
  53. .find(|(k, _)| k == param)
  54. .map(|(_, v)| v)
  55. }
  56. /// Returns the nth segment in the path. Paths that end with a slash have
  57. /// the slash removed before determining the segments. If the path has
  58. /// fewer segments than `n` then this method returns `None`.
  59. pub fn nth_segment(&self, n: usize) -> Option<&str> {
  60. self.route.url.path_segments()?.nth(n)
  61. }
  62. /// Returns the last segment in the path. Paths that end with a slash have
  63. /// the slash removed before determining the segments. The root path, `/`,
  64. /// will return an empty string.
  65. pub fn last_segment(&self) -> Option<&str> {
  66. self.route.url.path_segments()?.last()
  67. }
  68. /// Get the named parameter from the path, as defined in your router. The
  69. /// value will be parsed into the type specified by `T` by calling
  70. /// `value.parse::<T>()`. This method returns `None` if the named
  71. /// parameter does not exist in the current path.
  72. pub fn segment(&self, name: &str) -> Option<&str> {
  73. let total_route = match self.route_context {
  74. None => self.route.url.path(),
  75. Some(ref ctx) => &ctx.total_route,
  76. };
  77. let index = total_route
  78. .trim_start_matches('/')
  79. .split('/')
  80. .position(|segment| segment.starts_with(':') && &segment[1..] == name)?;
  81. self.route.url.path_segments()?.nth(index)
  82. }
  83. /// Get the named parameter from the path, as defined in your router. The
  84. /// value will be parsed into the type specified by `T` by calling
  85. /// `value.parse::<T>()`. This method returns `None` if the named
  86. /// parameter does not exist in the current path.
  87. pub fn parse_segment<T>(&self, name: &str) -> Option<Result<T, T::Err>>
  88. where
  89. T: FromStr,
  90. {
  91. self.segment(name).map(|value| value.parse::<T>())
  92. }
  93. }
  94. // The entire purpose of this struct is to unubscribe this component when it is unmounted.
  95. // The UseRoute can be cloned into async contexts, so we can't rely on its drop to unubscribe.
  96. // Instead, we hide the drop implementation on this private type exclusive to the hook,
  97. // and reveal our cached version of UseRoute to the component.
  98. struct UseRouteListener {
  99. state: UseRoute,
  100. router: Arc<RouterCore>,
  101. scope: ScopeId,
  102. }
  103. impl Drop for UseRouteListener {
  104. fn drop(&mut self) {
  105. self.router.unsubscribe_onchange(self.scope)
  106. }
  107. }