diff --git a/packages/router/src/components/router.rs b/packages/router/src/components/router.rs index 85f0a62a3..3d9f0c83a 100644 --- a/packages/router/src/components/router.rs +++ b/packages/router/src/components/router.rs @@ -12,7 +12,7 @@ pub struct RouterProps<'a> { children: Element<'a>, #[props(default, strip_option)] - onchange: Option<&'a Fn(&'a str)>, + onchange: Option<&'a dyn Fn(&'a str)>, } #[allow(non_snake_case)] diff --git a/packages/router/src/hooks/use_route.rs b/packages/router/src/hooks/use_route.rs index 8307ed1f0..bf76d0975 100644 --- a/packages/router/src/hooks/use_route.rs +++ b/packages/router/src/hooks/use_route.rs @@ -1,7 +1,11 @@ use dioxus_core::ScopeState; +use gloo::history::Location; +use std::rc::Rc; + +use crate::RouterService; pub struct UseRoute<'a> { - cur_route: String, + router: Rc, cx: &'a ScopeState, } @@ -11,20 +15,44 @@ impl<'a> UseRoute<'a> { todo!() } - pub fn nth_segment(&self, n: usize) -> Option<&str> { - todo!() + pub fn nth_segment(&self, n: usize) -> Option { + let mut segments = self.path_segments(); + let len = segments.len(); + if len - 1 < n { + return None; + } + Some(segments.remove(n)) } - pub fn last_segment(&self) -> Option<&'a str> { - todo!() + pub fn last_segment(&self) -> Option { + let mut segments = self.path_segments(); + let len = segments.len(); + if len == 0 { + return None; + } + Some(segments.remove(len - 1)) } /// Parse the segments of the URL, using named parameters (defined in your router) pub fn segment(&self, name: &str) -> Option<&T> { todo!() } + + pub fn current_location(&self) -> Location { + self.router.current_location() + } + + fn path_segments(&self) -> Vec { + let location = self.router.current_location(); + let stripped = &location.path()[1..]; + stripped.split('/').map(str::to_string).collect::>() + } } pub fn use_route<'a>(cx: &'a ScopeState) -> UseRoute<'a> { - todo!() + let router = cx + .consume_context::() + .expect("Cannot call use_route outside the scope of a Router component") + .clone(); + UseRoute { router, cx } } diff --git a/packages/router/src/platform/mod.rs b/packages/router/src/platform/mod.rs index bbb0e7c18..7afc1316a 100644 --- a/packages/router/src/platform/mod.rs +++ b/packages/router/src/platform/mod.rs @@ -1,5 +1,3 @@ -use url::Url; - pub trait RouterProvider { fn get_current_route(&self) -> String; fn subscribe_to_route_changes(&self, callback: Box); diff --git a/packages/router/src/service.rs b/packages/router/src/service.rs index 7eddeb69d..c0b383e81 100644 --- a/packages/router/src/service.rs +++ b/packages/router/src/service.rs @@ -1,7 +1,6 @@ -use gloo::history::{BrowserHistory, History, HistoryListener}; +use gloo::history::{BrowserHistory, History, HistoryListener, Location}; use std::{ cell::{Cell, RefCell}, - collections::HashMap, rc::Rc, }; @@ -118,6 +117,10 @@ impl RouterService { None => false, } } + + pub fn current_location(&self) -> Location { + self.history.borrow().location().clone() + } } pub struct RouterCfg {