Merge pull request #107 from autarch/autarch/half-assed-router

A partial implementation of the router and associated bits
This commit is contained in:
Jonathan Kelley 2022-01-18 00:01:34 -05:00 committed by GitHub
commit 8d3ac3ff14
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 204 additions and 60 deletions

View file

@ -2,6 +2,7 @@
use dioxus::prelude::*;
use dioxus::router::{Link, Route, Router};
use serde::Deserialize;
fn main() {
dioxus::desktop::launch(app);
@ -30,7 +31,7 @@ fn app(cx: Scope) -> Element {
}
fn BlogPost(cx: Scope) -> Element {
let post = dioxus::router::use_route(&cx).last_segment()?;
let post = dioxus::router::use_route(&cx).last_segment();
cx.render(rsx! {
div {
@ -40,9 +41,14 @@ fn BlogPost(cx: Scope) -> Element {
})
}
#[derive(Deserialize)]
struct Query {
bold: bool,
}
fn User(cx: Scope) -> Element {
let post = dioxus::router::use_route(&cx).last_segment()?;
let bold = dioxus::router::use_route(&cx).param::<bool>("bold");
let post = dioxus::router::use_route(&cx).last_segment();
let query = dioxus::router::use_route(&cx).query::<Query>();
cx.render(rsx! {
div {

View file

@ -198,12 +198,9 @@ impl ScopeArena {
// run the hooks (which hold an &mut Reference)
// recursively call ensure_drop_safety on all children
items.borrowed_props.drain(..).for_each(|comp| {
let scope_id = comp
.scope
.get()
.expect("VComponents should be associated with a valid Scope");
self.ensure_drop_safety(scope_id);
if let Some(scope_id) = comp.scope.get() {
self.ensure_drop_safety(scope_id);
}
drop(comp.props.take());
});

View file

@ -31,6 +31,9 @@ pub struct LinkProps<'a> {
#[props(default, strip_option)]
id: Option<&'a str>,
#[props(default, strip_option)]
title: Option<&'a str>,
children: Element<'a>,
#[props(default)]
@ -38,17 +41,25 @@ pub struct LinkProps<'a> {
}
pub fn Link<'a>(cx: Scope<'a, LinkProps<'a>>) -> Element {
let service = cx.consume_context::<RouterService>()?;
cx.render(rsx! {
a {
href: "{cx.props.to}",
class: format_args!("{}", cx.props.class.unwrap_or("")),
id: format_args!("{}", cx.props.id.unwrap_or("")),
log::debug!("render Link to {}", cx.props.to);
if let Some(service) = cx.consume_context::<RouterService>() {
return cx.render(rsx! {
a {
href: "{cx.props.to}",
class: format_args!("{}", cx.props.class.unwrap_or("")),
id: format_args!("{}", cx.props.id.unwrap_or("")),
title: format_args!("{}", cx.props.title.unwrap_or("")),
prevent_default: "onclick",
onclick: move |_| service.push_route(cx.props.to),
prevent_default: "onclick",
onclick: move |_| service.push_route(cx.props.to),
&cx.props.children
}
})
&cx.props.children
}
});
}
log::warn!(
"Attempted to create a Link to {} outside of a Router context",
cx.props.to,
);
None
}

View file

@ -30,6 +30,7 @@ pub fn Route<'a>(cx: Scope<'a, RouteProps<'a>>) -> Element {
Some(ctx) => ctx.total_route.to_string(),
None => cx.props.to.to_string(),
};
log::trace!("total route for {} is {}", cx.props.to, total_route);
// provide our route context
let route_context = cx.provide_context(RouteContext {

View file

@ -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)]

View file

@ -1,30 +1,83 @@
use dioxus_core::ScopeState;
use gloo::history::{HistoryResult, Location};
use serde::de::DeserializeOwned;
use std::{rc::Rc, str::FromStr};
pub struct UseRoute<'a> {
cur_route: String,
cx: &'a ScopeState,
use crate::RouterService;
/// This struct provides is a wrapper around the internal router
/// implementation, with methods for getting information about the current
/// route.
pub struct UseRoute {
router: Rc<RouterService>,
}
impl<'a> UseRoute<'a> {
/// Parse the query part of the URL
pub fn param<T>(&self, param: &str) -> Option<&T> {
todo!()
impl UseRoute {
/// This method simply calls the [`Location::query`] method.
pub fn query<T>(&self) -> HistoryResult<T>
where
T: DeserializeOwned,
{
self.current_location().query::<T>()
}
pub fn nth_segment(&self, n: usize) -> Option<&str> {
todo!()
/// Returns the nth segment in the path. Paths that end with a slash have
/// the slash removed before determining the segments. If the path has
/// fewer segments than `n` then this method returns `None`.
pub fn nth_segment(&self, n: usize) -> Option<String> {
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!()
/// Returns the last segment in the path. Paths that end with a slash have
/// the slash removed before determining the segments. The root path, `/`,
/// will return an empty string.
pub fn last_segment(&self) -> String {
let mut segments = self.path_segments();
segments.remove(segments.len() - 1)
}
/// Parse the segments of the URL, using named parameters (defined in your router)
pub fn segment<T>(&self, name: &str) -> Option<&T> {
todo!()
/// Get the named parameter from the path, as defined in your router. The
/// value will be parsed into the type specified by `T` by calling
/// `value.parse::<T>()`. This method returns `None` if the named
/// parameter does not exist in the current path.
pub fn segment<T>(&self, name: &str) -> Option<Result<T, T::Err>>
where
T: FromStr,
{
self.router
.current_path_params()
.get(name)
.and_then(|v| Some(v.parse::<T>()))
}
/// Returns the [Location] for the current route.
pub fn current_location(&self) -> Location {
self.router.current_location()
}
fn path_segments(&self) -> Vec<String> {
let location = self.router.current_location();
let path = location.path();
if path == "/" {
return vec![String::new()];
}
let stripped = &location.path()[1..];
stripped.split('/').map(str::to_string).collect::<Vec<_>>()
}
}
pub fn use_route<'a>(cx: &'a ScopeState) -> UseRoute<'a> {
todo!()
/// This hook provides access to information about the current location in the
/// context of a [`Router`]. If this function is called outside of a `Router`
/// component it will panic.
pub fn use_route(cx: &ScopeState) -> UseRoute {
let router = cx
.consume_context::<RouterService>()
.expect("Cannot call use_route outside the scope of a Router component")
.clone();
UseRoute { router }
}

View file

@ -1,5 +1,3 @@
use url::Url;
pub trait RouterProvider {
fn get_current_route(&self) -> String;
fn subscribe_to_route_changes(&self, callback: Box<dyn Fn(String)>);

View file

@ -1,6 +1,6 @@
use gloo::history::{BrowserHistory, History, HistoryListener};
use gloo::history::{BrowserHistory, History, HistoryListener, Location};
use std::{
cell::{Cell, RefCell},
cell::{Cell, Ref, RefCell},
collections::HashMap,
rc::Rc,
};
@ -10,10 +10,9 @@ use dioxus_core::ScopeId;
pub struct RouterService {
pub(crate) regen_route: Rc<dyn Fn(ScopeId)>,
history: Rc<RefCell<BrowserHistory>>,
registerd_routes: RefCell<RouteSlot>,
slots: Rc<RefCell<Vec<(ScopeId, String)>>>,
root_found: Rc<Cell<bool>>,
cur_root: RefCell<String>,
root_found: Rc<Cell<Option<ScopeId>>>,
cur_path_params: Rc<RefCell<HashMap<String, String>>>,
listener: HistoryListener,
}
@ -40,48 +39,54 @@ impl RouterService {
let _slots = slots.clone();
let root_found = Rc::new(Cell::new(false));
let root_found = Rc::new(Cell::new(None));
let regen = regen_route.clone();
let _root_found = root_found.clone();
let listener = history.listen(move || {
_root_found.set(false);
_root_found.set(None);
// checking if the route is valid is cheap, so we do it
for (slot, _) in _slots.borrow_mut().iter().rev() {
log::trace!("regenerating slot {:?}", slot);
for (slot, root) in _slots.borrow_mut().iter().rev() {
log::trace!("regenerating slot {:?} for root '{}'", slot, root);
regen(*slot);
}
});
Self {
registerd_routes: RefCell::new(RouteSlot::Routes {
partial: String::from("/"),
total: String::from("/"),
rest: Vec::new(),
}),
root_found,
history: Rc::new(RefCell::new(history)),
regen_route,
slots,
cur_root: RefCell::new(path.to_string()),
cur_path_params: Rc::new(RefCell::new(HashMap::new())),
listener,
}
}
pub fn push_route(&self, route: &str) {
log::trace!("Pushing route: {}", route);
self.history.borrow_mut().push(route);
}
pub fn register_total_route(&self, route: String, scope: ScopeId, fallback: bool) {
self.slots.borrow_mut().push((scope, route));
let clean = clean_route(route);
log::trace!("Registered route '{}' with scope id {:?}", clean, scope);
self.slots.borrow_mut().push((scope, clean));
}
pub fn should_render(&self, scope: ScopeId) -> bool {
if self.root_found.get() {
log::trace!("Should render scope id {:?}?", scope);
if let Some(root_id) = self.root_found.get() {
log::trace!(" we already found a root with scope id {:?}", root_id);
if root_id == scope {
log::trace!(" yes - it's a match");
return true;
}
log::trace!(" no - it's not a match");
return false;
}
let location = self.history.borrow().location();
let path = location.path();
log::trace!(" current path is '{}'", path);
let roots = self.slots.borrow();
@ -89,15 +94,24 @@ impl RouterService {
// fallback logic
match root {
Some((_id, route)) => {
if route == path {
self.root_found.set(true);
Some((id, route)) => {
log::trace!(
" matched given scope id {:?} with route root '{}'",
scope,
route,
);
if let Some(params) = route_matches_path(route, path) {
log::trace!(" and it matches the current path '{}'", path);
self.root_found.set(Some(*id));
*self.cur_path_params.borrow_mut() = params;
true
} else {
if route == "" {
self.root_found.set(true);
log::trace!(" and the route is the root, so we will use that without a better match");
self.root_found.set(Some(*id));
true
} else {
log::trace!(" and the route '{}' is not the root nor does it match the current path", route);
false
}
}
@ -105,6 +119,70 @@ impl RouterService {
None => false,
}
}
pub fn current_location(&self) -> Location {
self.history.borrow().location().clone()
}
pub fn current_path_params(&self) -> Ref<HashMap<String, String>> {
self.cur_path_params.borrow()
}
}
fn clean_route(route: String) -> String {
if route.as_str() == "/" {
return route;
}
route.trim_end_matches('/').to_string()
}
fn clean_path(path: &str) -> &str {
if path == "/" {
return path;
}
path.trim_end_matches('/')
}
fn route_matches_path(route: &str, path: &str) -> Option<HashMap<String, String>> {
let route_pieces = route.split('/').collect::<Vec<_>>();
let path_pieces = clean_path(path).split('/').collect::<Vec<_>>();
log::trace!(
" checking route pieces {:?} vs path pieces {:?}",
route_pieces,
path_pieces,
);
if route_pieces.len() != path_pieces.len() {
log::trace!(" the routes are different lengths");
return None;
}
let mut matches = HashMap::new();
for (i, r) in route_pieces.iter().enumerate() {
log::trace!(" checking route piece '{}' vs path", r);
// If this is a parameter then it matches as long as there's
// _any_thing in that spot in the path.
if r.starts_with(':') {
log::trace!(
" route piece '{}' starts with a colon so it matches anything",
r,
);
let param = &r[1..];
matches.insert(param.to_string(), path_pieces[i].to_string());
continue;
}
log::trace!(
" route piece '{}' must be an exact match for path piece '{}'",
r,
path_pieces[i],
);
if path_pieces[i] != *r {
return None;
}
}
Some(matches)
}
pub struct RouterCfg {