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

+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))