feat: apply local router changes

This commit is contained in:
Jonathan Kelley committed 2022-03-04 13:16:37 -05:00
1 parent 3928856a9b
commit f2979cb12a
28 files changed
+672 -516

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
#[derive(Default)]
pub struct RouterCfg {
pub base_url: Option<String>,
}
+82 -63
View File
@@ -1,97 +1,116 @@
use crate::RouterService;
use dioxus::Attribute;
use std::sync::Arc;
use crate::RouterCore;
use dioxus_core as dioxus;
use dioxus_core::prelude::*;
use dioxus_core_macro::{format_args_f, rsx, Props};
use dioxus_html as dioxus_elements;
/// Props for the [`Link`](struct.Link.html) component.
#[derive(Props)]
pub struct LinkProps<'a> {
to: &'a str,
/// The url that gets pushed to the history stack
/// The route to link to. This can be a relative path, or a full URL.
///
/// You can either put in your own inline method or just autoderive the route using `derive(Routable)`
///
/// ```rust, ignore
///
/// Link { to: Route::Home, href: |_| "home".to_string() }
///
/// // or
///
/// Link { to: Route::Home, href: Route::as_url }
/// ```rust
/// // Absolute path
/// Link { to: "/home", "Go Home" }
///
/// // Relative path
/// Link { to: "../", "Go Up" }
/// ```
#[props(default, strip_option)]
href: Option<&'a str>,
pub to: &'a str,
/// Set the class of the inner link ['a'](https://www.w3schools.com/tags/tag_a.asp) element.
///
/// This can be useful when styling the inner link element.
#[props(default, strip_option)]
class: Option<&'a str>,
pub class: Option<&'a str>,
/// Set the ID of the inner link ['a'](https://www.w3schools.com/tags/tag_a.asp) element.
///
/// This can be useful when styling the inner link element.
#[props(default, strip_option)]
id: Option<&'a str>,
pub id: Option<&'a str>,
/// Set the title of the window after the link is clicked..
#[props(default, strip_option)]
title: Option<&'a str>,
pub title: Option<&'a str>,
/// Autodetect if a link is external or not.
///
/// This is automatically set to `true` and will use http/https detection
#[props(default = true)]
autodetect: bool,
pub autodetect: bool,
/// Is this link an external link?
#[props(default = false)]
external: bool,
pub external: bool,
/// New tab?
#[props(default = false)]
new_tab: bool,
pub new_tab: bool,
children: Element<'a>,
#[props(default)]
attributes: Option<&'a [Attribute<'a>]>,
/// Pass children into the `<a>` element
pub children: Element<'a>,
}
/// A component that renders a link to a route.
///
/// `Link` components are just [`<a>`](https://www.w3schools.com/tags/tag_a.asp) elements
/// that link to different pages *within* your single-page app.
///
/// If you need to link to a resource outside of your app, then just use a regular
/// `<a>` element directly.
///
/// # Examples
///
/// ```rust
/// fn Header(cx: Scope) -> Element {
/// cx.render(rsx!{
/// Link { to: "/home", "Go Home" }
/// })
/// }
/// ```
pub fn Link<'a>(cx: Scope<'a, LinkProps<'a>>) -> Element {
if let Some(service) = cx.consume_context::<RouterService>() {
let LinkProps {
to,
href,
class,
id,
title,
autodetect,
external,
new_tab,
children,
..
} = cx.props;
let svc = cx.use_hook(|_| cx.consume_context::<Arc<RouterCore>>());
let is_http = to.starts_with("http") || to.starts_with("https");
let outerlink = (*autodetect && is_http) || *external;
let LinkProps {
to,
class,
id,
title,
autodetect,
external,
new_tab,
children,
..
} = cx.props;
let prevent_default = if outerlink { "" } else { "onclick" };
let is_http = to.starts_with("http") || to.starts_with("https");
let outerlink = (*autodetect && is_http) || *external;
let prevent_default = if outerlink { "" } else { "onclick" };
return cx.render(rsx! {
a {
href: "{to}",
class: format_args!("{}", class.unwrap_or("")),
id: format_args!("{}", id.unwrap_or("")),
title: format_args!("{}", title.unwrap_or("")),
prevent_default: "{prevent_default}",
target: format_args!("{}", if *new_tab { "_blank" } else { "" }),
onclick: move |_| {
if !outerlink {
cx.render(rsx! {
a {
href: "{to}",
class: format_args!("{}", class.unwrap_or("")),
id: format_args!("{}", id.unwrap_or("")),
title: format_args!("{}", title.unwrap_or("")),
prevent_default: "{prevent_default}",
target: format_args!("{}", if *new_tab { "_blank" } else { "" }),
onclick: move |_| {
if !outerlink {
if let Some(service) = svc {
service.push_route(to);
} else {
log::error!(
"Attempted to create a Link to {} outside of a Router context",
cx.props.to,
);
}
},
&cx.props.children
}
});
}
log::warn!(
"Attempted to create a Link to {} outside of a Router context",
cx.props.to,
);
None
}
},
children
}
})
}
@@ -0,0 +1,8 @@
use dioxus_core::prelude::*;
// The entire point of this component is to immediately redirect to the given path.
pub fn Redirect(cx: Scope) -> Element {
//
None
}
+26 -28
View File
@@ -1,4 +1,4 @@
use dioxus_core::Element;
use std::sync::Arc;
use dioxus_core as dioxus;
use dioxus_core::prelude::*;
@@ -6,31 +6,42 @@ use dioxus_core_macro::Props;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
use crate::{RouteContext, RouterService};
use crate::{RouteContext, RouterCore};
/// Props for the [`Route`](struct.Route.html) component.
#[derive(Props)]
pub struct RouteProps<'a> {
to: &'a str,
/// The path to match.
pub to: &'a str,
children: Element<'a>,
#[props(default)]
fallback: bool,
/// The component to render when the path matches.
pub children: Element<'a>,
}
/// A component that conditionally renders children based on the current location.
///
/// # Example
///
///```rust
/// rsx!(
/// Router {
/// Route { to: "/home", Home {} }
/// Route { to: "/about", About {} }
/// Route { to: "/Blog", Blog {} }
/// }
/// )
/// ```
pub fn Route<'a>(cx: Scope<'a, RouteProps<'a>>) -> Element {
// now we want to submit
let router_root = cx
.use_hook(|_| cx.consume_context::<RouterService>())
.use_hook(|_| cx.consume_context::<Arc<RouterCore>>())
.as_ref()?;
cx.use_hook(|_| {
// create a bigger, better, longer route if one above us exists
let total_route = match cx.consume_context::<RouteContext>() {
Some(ctx) => ctx.total_route.to_string(),
Some(ctx) => ctx.total_route,
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 {
@@ -39,28 +50,15 @@ pub fn Route<'a>(cx: Scope<'a, RouteProps<'a>>) -> Element {
});
// submit our rout
router_root.register_total_route(
route_context.total_route.clone(),
cx.scope_id(),
cx.props.fallback,
);
Some(RouteInner {})
router_root.register_total_route(route_context.total_route, cx.scope_id());
});
// log::trace!("Checking route {}", cx.props.to);
log::debug!("Checking Route: {:?}", cx.props.to);
if router_root.should_render(cx.scope_id()) {
log::debug!("Route should render: {:?}", cx.scope_id());
cx.render(rsx!(&cx.props.children))
} else {
log::debug!("Route should *not* render: {:?}", cx.scope_id());
None
}
}
struct RouteInner {}
impl Drop for RouteInner {
fn drop(&mut self) {
// todo!()
}
}
+70 -15
View File
@@ -1,35 +1,90 @@
use dioxus_core::Element;
use crate::location::ParsedRoute;
use std::cell::Cell;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use crate::cfg::RouterCfg;
use crate::RouteEvent;
use crate::RouterCore;
use dioxus_core as dioxus;
use dioxus_core::prelude::*;
use dioxus_core::Element;
use dioxus_core_macro::*;
use dioxus_html as dioxus_elements;
use futures_util::stream::StreamExt;
use crate::RouterService;
/// The props for the [`Router`](fn.Router.html) component.
#[derive(Props)]
pub struct RouterProps<'a> {
children: Element<'a>,
/// The routes and elements that should be rendered when the path matches.
///
/// If elements are not contained within Routes, the will be rendered
/// regardless of the path.
pub children: Element<'a>,
/// The URL to point at
///
/// This will be used to trim any latent segments from the URL when your app is
/// not deployed to the root of the domain.
#[props(optional)]
pub base_url: Option<&'a str>,
/// Hook into the router when the route is changed.
///
/// This lets you easily implement redirects
#[props(default)]
onchange: EventHandler<'a, String>,
pub onchange: EventHandler<'a, Arc<RouterCore>>,
}
/// A component that conditionally renders children based on the current location of the app.
///
/// Uses BrowserRouter in the browser and HashRouter everywhere else.
///
/// Will fallback to HashRouter is BrowserRouter is not available, or through configuration.
#[allow(non_snake_case)]
pub fn Router<'a>(cx: Scope<'a, RouterProps<'a>>) -> Element {
log::debug!("running router {:?}", cx.scope_id());
let call_onchange = cx.use_hook(|_| Rc::new(Cell::new(false)));
let svc = cx.use_hook(|_| {
let update = cx.schedule_update_any();
cx.provide_context(RouterService::new(update, cx.scope_id()))
let (tx, mut rx) = futures_channel::mpsc::unbounded::<RouteEvent>();
let base_url = cx.props.base_url.map(|s| s.to_string());
let svc = RouterCore::new(tx, RouterCfg { base_url });
cx.spawn({
let svc = svc.clone();
let regen_route = cx.schedule_update_any();
let call_onchange = call_onchange.clone();
let router_id = cx.scope_id();
async move {
while let Some(msg) = rx.next().await {
if let Some(_new) = svc.handle_route_event(msg) {
call_onchange.set(true);
regen_route(router_id);
for listener in svc.onchange_listeners.borrow().iter() {
regen_route(*listener);
}
for route in svc.slots.borrow().keys() {
regen_route(*route);
}
}
}
}
});
cx.provide_context(svc)
});
let any_pending = svc.pending_events.borrow().len() > 0;
svc.pending_events.borrow_mut().clear();
if any_pending {
let location = svc.current_location();
let path = location.path();
cx.props.onchange.call(path.to_string());
if call_onchange.get() {
cx.props.onchange.call(svc.clone());
call_onchange.set(false);
}
cx.render(rsx!(&cx.props.children))
File renamed without changes.
+5
View File
@@ -0,0 +1,5 @@
use dioxus_core::prelude::*;
pub fn use_param<T>(cx: &ScopeState) -> Option<T> {
todo!()
}
+14 -87
View File
@@ -1,94 +1,27 @@
use dioxus_core::{ScopeId, ScopeState};
use gloo::history::{HistoryResult, Location};
use serde::de::DeserializeOwned;
use std::{rc::Rc, str::FromStr};
use std::{rc::Rc, str::FromStr, sync::Arc};
use crate::RouterService;
/// This struct provides is a wrapper around the internal router
/// implementation, with methods for getting information about the current
/// route.
#[derive(Clone)]
pub struct UseRoute {
router: Rc<RouterService>,
}
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>()
}
/// 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))
}
/// 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)
}
/// 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<_>>()
}
}
use crate::{location::ParsedRoute, RouterCore, RouterService};
/// 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 {
&cx.use_hook(|_| {
pub fn use_route(cx: &ScopeState) -> &ParsedRoute {
let handle = cx.use_hook(|_| {
let router = cx
.consume_context::<RouterService>()
.consume_context::<Arc<RouterCore>>()
.expect("Cannot call use_route outside the scope of a Router component");
router.subscribe_onchange(cx.scope_id());
UseRouteListener {
router: UseRoute { router },
route: router.current_location(),
router,
scope: cx.scope_id(),
}
})
.router
});
&handle.route
}
// The entire purpose of this struct is to unubscribe this component when it is unmounted.
@@ -96,19 +29,13 @@ pub fn use_route(cx: &ScopeState) -> &UseRoute {
// Instead, we hide the drop implementation on this private type exclusive to the hook,
// and reveal our cached version of UseRoute to the component.
struct UseRouteListener {
router: UseRoute,
route: Arc<ParsedRoute>,
router: Arc<RouterCore>,
scope: ScopeId,
}
impl Drop for UseRouteListener {
fn drop(&mut self) {
self.router.router.unsubscribe_onchange(self.scope)
self.router.unsubscribe_onchange(self.scope)
}
}
/// This hook provides access to the `RouterService` for the app.
pub fn use_router(cx: &ScopeState) -> &Rc<RouterService> {
cx.use_hook(|_| {
cx.consume_context::<RouterService>()
.expect("Cannot call use_route outside the scope of a Router component")
})
}
+10
View File
@@ -0,0 +1,10 @@
use crate::RouterService;
use dioxus_core::ScopeState;
/// This hook provides access to the `RouterService` for the app.
pub fn use_router(cx: &ScopeState) -> &RouterService {
cx.use_hook(|_| {
cx.consume_context::<RouterService>()
.expect("Cannot call use_route outside the scope of a Router component")
})
}
+17 -20
View File
@@ -1,38 +1,35 @@
#![allow(warnings)]
//! Dioxus-Router
//!
//! A simple match-based router and router service for most routing needs.
//!
//! Dioxus-Router is not a *declarative* router. Instead it uses a simple parse-match
//! pattern which can be derived via a macro.
//!
//! ```rust
//! fn app(cx: Scope) -> Element {
//!
//! }
//! ```
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]
mod hooks {
mod use_param;
mod use_query;
mod use_route;
mod use_router;
pub use use_param::*;
pub use use_query::*;
pub use use_route::*;
pub use use_router::*;
}
pub use hooks::*;
mod components {
#![allow(non_snake_case)]
mod router;
pub use router::*;
mod route;
pub use route::*;
mod link;
mod redirect;
mod route;
mod router;
pub use link::*;
pub use redirect::*;
pub use route::*;
pub use router::*;
}
pub use components::*;
mod platform;
mod cfg;
mod location;
mod routecontext;
mod service;
mod utils;
+66
View File
@@ -0,0 +1,66 @@
use std::str::FromStr;
use url::Url;
pub struct ParsedRoute {
pub(crate) url: url::Url,
}
impl ParsedRoute {
pub(crate) fn new(url: Url) -> Self {
Self { url }
}
// get the underlying url
pub fn url(&self) -> &Url {
&self.url
}
pub fn query(&self) -> Option<&String> {
None
}
/// 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<&str> {
self.url.path_segments()?.nth(n)
}
/// 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) -> Option<&str> {
self.url.path_segments()?.last()
}
/// 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<&str>
where
T: FromStr,
{
self.url.path_segments()?.find(|&f| f.eq(name))
}
/// 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 parse_segment<T>(&self, name: &str) -> Option<Result<T, T::Err>>
where
T: FromStr,
{
self.url
.path_segments()?
.find(|&f| f.eq(name))
.map(|f| f.parse::<T>())
}
}
#[test]
fn parses_location() {
let route = ParsedRoute::new(Url::parse("app:///foo/bar?baz=qux&quux=corge").unwrap());
}
-4
View File
@@ -1,4 +0,0 @@
pub trait RouterProvider {
fn get_current_route(&self) -> String;
fn listen(&self, callback: Box<dyn Fn()>);
}
-125
View File
@@ -1,125 +0,0 @@
use web_sys::{window, Event};
pub struct RouterService<R: Routable> {
historic_routes: Vec<R>,
history_service: RefCell<web_sys::History>,
base_ur: RefCell<Option<String>>,
}
impl<R: Routable> RouterService<R> {
fn push_route(&self, r: R) {
todo!()
// self.historic_routes.borrow_mut().push(r);
}
fn get_current_route(&self) -> &str {
todo!()
}
fn update_route_impl(&self, url: String, push: bool) {
let history = web_sys::window().unwrap().history().expect("no history");
let base = self.base_ur.borrow();
let path = match base.as_ref() {
Some(base) => {
let path = format!("{}{}", base, url);
if path.is_empty() {
"/".to_string()
} else {
path
}
}
None => url,
};
if push {
history
.push_state_with_url(&JsValue::NULL, "", Some(&path))
.expect("push history");
} else {
history
.replace_state_with_url(&JsValue::NULL, "", Some(&path))
.expect("replace history");
}
let event = Event::new("popstate").unwrap();
web_sys::window()
.unwrap()
.dispatch_event(&event)
.expect("dispatch");
}
}
pub fn use_router_service<R: Routable>(cx: &ScopeState) -> Option<&Rc<RouterService<R>>> {
cx.use_hook(|_| cx.consume_state::<RouterService<R>>())
.as_ref()
}
/// This hould only be used once per app
///
/// You can manually parse the route if you want, but the derived `parse` method on `Routable` will also work just fine
pub fn use_router<R: Routable>(cx: &ScopeState, mut parse: impl FnMut(&str) -> R + 'static) -> &R {
// for the web, attach to the history api
let state = cx.use_hook(
#[cfg(not(feature = "web"))]
|_| {},
#[cfg(feature = "web")]
|f| {
//
use gloo::events::EventListener;
let base = window()
.unwrap()
.document()
.unwrap()
.query_selector("base[href]")
.ok()
.flatten()
.and_then(|base| {
let base = JsCast::unchecked_into::<web_sys::HtmlBaseElement>(base).href();
let url = web_sys::Url::new(&base).unwrap();
if url.pathname() != "/" {
Some(strip_slash_suffix(&base).to_string())
} else {
None
}
});
let location = window().unwrap().location();
let pathname = location.pathname().unwrap();
let initial_route = parse(&pathname);
let service: RouterService<R> = RouterService {
historic_routes: vec![initial_route],
history_service: RefCell::new(
web_sys::window().unwrap().history().expect("no history"),
),
base_ur: RefCell::new(base),
};
// let base = base_url();
// let url = route.to_path();
// pending_routes: RefCell::new(vec![]),
// service.history_service.push_state(data, title);
// cx.provide_state(service);
let regenerate = cx.schedule_update();
// // when "back" is called by the user, we want to to re-render the component
let listener = EventListener::new(&web_sys::window().unwrap(), "popstate", move |_| {
//
regenerate();
});
service
},
);
let base = state.base_ur.borrow();
if let Some(base) = base.as_ref() {
let path = format!("{}{}", base, state.get_current_route());
}
let history = state.history_service.borrow();
state.historic_routes.last().unwrap()
}
+19 -2
View File
@@ -1,7 +1,24 @@
/// A `RouteContext` is a context that is provided by [`Route`](fn.Route.html) components.
///
/// This signals to all child [`Route`] and [`Link`] components that they are
/// currently nested under this route.
#[derive(Debug, Clone)]
pub struct RouteContext {
// "/name/:id"
/// The `declared_route` is the sub-piece of the route that matches this pattern.
///
///
/// It follows this pattern:
/// ```
/// "name/:id"
/// ```
pub declared_route: String,
// "app/name/:id"
/// The `total_route` is the full route that matches this pattern.
///
///
/// It follows this pattern:
/// ```
/// "/level0/level1/:id"
/// ```
pub total_route: String,
}
+253 -114
View File
@@ -1,150 +1,202 @@
use gloo::history::{BrowserHistory, History, HistoryListener, Location};
// todo: how does router work in multi-window contexts?
// does each window have its own router? probably, lol
use crate::{cfg::RouterCfg, location::ParsedRoute};
use dioxus_core::ScopeId;
use futures_channel::mpsc::UnboundedSender;
use std::any::Any;
use std::{
cell::{Cell, Ref, RefCell},
cell::{Cell, RefCell},
collections::{HashMap, HashSet},
rc::Rc,
sync::Arc,
};
use url::Url;
use dioxus_core::ScopeId;
/// An abstraction over the platform's history API.
///
/// The history is denoted using web-like semantics, with forward slashes delmitiing
/// routes and question marks denoting optional parameters.
///
/// This RouterService is exposed so you can modify the history directly. It
/// does not provide a high-level ergonomic API for your components. Instead,
/// you should consider using the components and hooks instead.
/// - [`Route`](struct.Route.html)
/// - [`Link`](struct.Link.html)
/// - [`UseRoute`](struct.UseRoute.html)
/// - [`Router`](struct.Router.html)
///
///
/// # Example
///
/// ```rust
/// let router = Router::new();
/// router.push_route("/home/custom");
/// cx.provide_context(router);
/// ```
///
/// # Platform Specific
///
/// - On the web, this is a [`BrowserHistory`](https://docs.rs/gloo/0.3.0/gloo/history/struct.BrowserHistory.html).
/// - On desktop, mobile, and SSR, this is just a Vec of Strings. Currently on
/// desktop, there is no way to tap into forward/back for the app unless explicitly set.
pub struct RouterCore {
pub root_found: Cell<Option<ScopeId>>,
use crate::platform::RouterProvider;
pub stack: RefCell<Vec<Arc<ParsedRoute>>>,
pub struct RouterService {
pub(crate) regen_route: Arc<dyn Fn(ScopeId)>,
pub(crate) pending_events: Rc<RefCell<Vec<RouteEvent>>>,
slots: Rc<RefCell<Vec<(ScopeId, String)>>>,
onchange_listeners: Rc<RefCell<HashSet<ScopeId>>>,
root_found: Rc<Cell<Option<ScopeId>>>,
cur_path_params: Rc<RefCell<HashMap<String, String>>>,
pub router_needs_update: Cell<bool>,
// history: Rc<dyn RouterProvider>,
history: Rc<RefCell<BrowserHistory>>,
listener: HistoryListener,
pub tx: UnboundedSender<RouteEvent>,
pub slots: Rc<RefCell<HashMap<ScopeId, String>>>,
pub onchange_listeners: Rc<RefCell<HashSet<ScopeId>>>,
pub query_listeners: Rc<RefCell<HashMap<ScopeId, String>>>,
pub semgment_listeners: Rc<RefCell<HashMap<ScopeId, String>>>,
pub history: Box<dyn RouterProvider>,
pub cfg: RouterCfg,
}
pub type RouterService = Arc<RouterCore>;
#[derive(Debug)]
pub enum RouteEvent {
Change,
Push(String),
Pop,
Push,
}
enum RouteSlot {
Routes {
// the partial route
partial: String,
impl RouterCore {
pub fn new(tx: UnboundedSender<RouteEvent>, cfg: RouterCfg) -> Arc<Self> {
#[cfg(feature = "web")]
let history = Box::new(web::new(tx.clone()));
// the total route
total: String,
#[cfg(not(feature = "web"))]
let history = Box::new(hash::create_router());
// Connections to other routs
rest: Vec<RouteSlot>,
},
}
let route = Arc::new(ParsedRoute::new(history.init_location()));
impl RouterService {
pub fn new(regen_route: Arc<dyn Fn(ScopeId)>, root_scope: ScopeId) -> Self {
let history = BrowserHistory::default();
let location = history.location();
let path = location.path();
Arc::new(Self {
cfg,
tx,
root_found: Cell::new(None),
stack: RefCell::new(vec![route]),
slots: Default::default(),
semgment_listeners: Default::default(),
query_listeners: Default::default(),
onchange_listeners: Default::default(),
history,
router_needs_update: Default::default(),
})
}
let onchange_listeners = Rc::new(RefCell::new(HashSet::new()));
let slots: Rc<RefCell<Vec<(ScopeId, String)>>> = Default::default();
let pending_events: Rc<RefCell<Vec<RouteEvent>>> = Default::default();
let root_found = Rc::new(Cell::new(None));
pub fn handle_route_event(&self, msg: RouteEvent) -> Option<Arc<ParsedRoute>> {
log::debug!("handling route event {:?}", msg);
self.root_found.set(None);
let listener = history.listen({
let pending_events = pending_events.clone();
let regen_route = regen_route.clone();
let root_found = root_found.clone();
let slots = slots.clone();
let onchange_listeners = onchange_listeners.clone();
move || {
root_found.set(None);
// checking if the route is valid is cheap, so we do it
for (slot, root) in slots.borrow_mut().iter().rev() {
regen_route(*slot);
}
match msg {
RouteEvent::Push(route) => {
let cur = self.current_location();
for listener in onchange_listeners.borrow_mut().iter() {
regen_route(*listener);
}
let new_url = cur.url.join(&route).ok().unwrap();
// also regenerate the root
regen_route(root_scope);
self.history.push(new_url.as_str());
pending_events.borrow_mut().push(RouteEvent::Change)
let route = Arc::new(ParsedRoute::new(new_url));
self.stack.borrow_mut().push(route.clone());
Some(route)
}
});
RouteEvent::Pop => {
let mut stack = self.stack.borrow_mut();
if stack.len() == 1 {
return None;
}
Self {
listener,
root_found,
history: Rc::new(RefCell::new(history)),
regen_route,
slots,
pending_events,
onchange_listeners,
cur_path_params: Rc::new(RefCell::new(HashMap::new())),
self.history.pop();
stack.pop()
}
}
}
/// Push a new route to the history.
///
/// This will trigger a route change event.
///
/// This does not modify the current route
pub fn push_route(&self, route: &str) {
self.history.borrow_mut().push(route);
// convert the users route to our internal format
self.tx
.unbounded_send(RouteEvent::Push(route.to_string()))
.unwrap();
}
pub fn register_total_route(&self, route: String, scope: ScopeId, fallback: bool) {
/// Pop the current route from the history.
///
///
pub fn pop_route(&self) {
self.tx.unbounded_send(RouteEvent::Pop).unwrap();
}
pub(crate) fn register_total_route(&self, route: String, scope: ScopeId) {
let clean = clean_route(route);
self.slots.borrow_mut().push((scope, clean));
self.slots.borrow_mut().insert(scope, clean);
}
pub fn should_render(&self, scope: ScopeId) -> bool {
if let Some(root_id) = self.root_found.get() {
if root_id == scope {
return true;
}
return false;
}
pub(crate) fn should_render(&self, scope: ScopeId) -> bool {
log::debug!("Checking render: {:?}", scope);
let location = self.history.borrow().location();
let path = location.path();
if let Some(root_id) = self.root_found.get() {
return root_id == scope;
}
let roots = self.slots.borrow();
let root = roots.iter().find(|(id, route)| id == &scope);
if let Some(route) = roots.get(&scope) {
log::debug!("Registration found for scope {:?} {:?}", scope, route);
// fallback logic
match root {
Some((id, route)) => {
if let Some(params) = route_matches_path(route, path) {
self.root_found.set(Some(*id));
*self.cur_path_params.borrow_mut() = params;
true
} else {
if route == "" {
self.root_found.set(Some(*id));
true
} else {
false
}
}
if route_matches_path(&self.current_location(), route) || route.is_empty() {
self.root_found.set(Some(scope));
true
} else {
false
}
None => false,
} else {
log::debug!("no route found for scope: {:?}", scope);
false
}
}
pub fn current_location(&self) -> Location {
self.history.borrow().location().clone()
/// Get the current location of the Router
pub fn current_location(&self) -> Arc<ParsedRoute> {
self.stack.borrow().last().unwrap().clone()
}
pub fn current_path_params(&self) -> Ref<HashMap<String, String>> {
self.cur_path_params.borrow()
pub fn query_current_location(&self) -> HashMap<String, String> {
todo!()
// self.history.borrow().query()
}
/// Get the current location of the Router
pub fn native_location<T: 'static>(&self) -> Option<Box<T>> {
self.history.native_location().downcast::<T>().ok()
}
/// Registers a scope to regenerate on route change.
///
/// This is useful if you've built some abstraction on top of the router service.
pub fn subscribe_onchange(&self, id: ScopeId) {
self.onchange_listeners.borrow_mut().insert(id);
}
/// Unregisters a scope to regenerate on route change.
///
/// This is useful if you've built some abstraction on top of the router service.
pub fn unsubscribe_onchange(&self, id: ScopeId) {
self.onchange_listeners.borrow_mut().remove(&id);
}
@@ -161,41 +213,128 @@ fn clean_path(path: &str) -> &str {
if path == "/" {
return path;
}
path.trim_end_matches('/')
let sub = path.trim_end_matches('/');
if sub.starts_with('/') {
&path[1..]
} else {
sub
}
}
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<_>>();
fn route_matches_path(cur: &ParsedRoute, attempt: &str) -> bool {
let cur_pieces = cur.url.path_segments().unwrap().collect::<Vec<_>>();
let attempt_pieces = clean_path(attempt).split('/').collect::<Vec<_>>();
if route_pieces.len() != path_pieces.len() {
return None;
if attempt == "/" && cur_pieces.len() == 1 && cur_pieces[0].is_empty() {
return true;
}
let mut matches = HashMap::new();
for (i, r) in route_pieces.iter().enumerate() {
log::debug!(
"Comparing cur {:?} to attempt {:?}",
cur_pieces,
attempt_pieces
);
if attempt_pieces.len() != cur_pieces.len() {
return false;
}
for (i, r) in attempt_pieces.iter().enumerate() {
log::debug!("checking route: {:?}", 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(':') {
let param = &r[1..];
matches.insert(param.to_string(), path_pieces[i].to_string());
continue;
}
if path_pieces[i] != *r {
return None;
if cur_pieces[i] != *r {
return false;
}
}
Some(matches)
true
}
pub struct RouterCfg {
initial_route: String,
pub trait RouterProvider {
fn push(&self, path: &str);
fn pop(&self);
fn native_location(&self) -> Box<dyn Any>;
fn init_location(&self) -> Url;
}
impl RouterCfg {
pub fn new(initial_route: String) -> Self {
Self { initial_route }
mod hash {
use super::*;
/// a simple cross-platform hash-based router
pub struct HashRouter {}
impl RouterProvider for HashRouter {
fn push(&self, _path: &str) {}
fn native_location(&self) -> Box<dyn Any> {
Box::new(())
}
fn pop(&self) {}
fn init_location(&self) -> Url {
Url::parse("app:///").unwrap()
}
}
}
#[cfg(feature = "web")]
mod web {
use super::RouterProvider;
use crate::RouteEvent;
use futures_channel::mpsc::UnboundedSender;
use gloo::{
events::EventListener,
history::{BrowserHistory, History},
};
use std::any::Any;
use url::Url;
pub struct WebRouter {
// keep it around so it drops when the router is dropped
_listener: gloo::events::EventListener,
history: BrowserHistory,
}
impl RouterProvider for WebRouter {
fn push(&self, path: &str) {
self.history.push(path);
// use gloo::history;
// web_sys::window()
// .unwrap()
// .location()
// .set_href(path)
// .unwrap();
}
fn native_location(&self) -> Box<dyn Any> {
todo!()
}
fn pop(&self) {
// set the title, maybe?
}
fn init_location(&self) -> Url {
url::Url::parse(&web_sys::window().unwrap().location().href().unwrap()).unwrap()
}
}
pub fn new(tx: UnboundedSender<RouteEvent>) -> WebRouter {
WebRouter {
history: BrowserHistory::new(),
_listener: EventListener::new(&web_sys::window().unwrap(), "popstate", move |_| {
let _ = tx.unbounded_send(RouteEvent::Pop);
}),
}
}
}