Renderers are now packages, not features. (#387)
* feat: use synchronous router design * feat: function to get router out of dom * chore: restructure workspace to use renderers as packages, not features
This commit is contained in:
1 parent
c97ca7dff6
commit
d9546d9504
181 files changed
+487
-1463
No files matched your search
@@ -11,7 +11,7 @@ keywords = ["dom", "ui", "gui", "react", "wasm"]
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
dioxus = { path = "../rsx-prelude", version = "^0.1.0", package = "rsx-prelude" }
|
||||
dioxus = { path = "../dioxus" }
|
||||
futures-channel = "0.3.21"
|
||||
url = { version = "2.2.2", default-features = false }
|
||||
|
||||
@@ -26,7 +26,7 @@ web-sys = { version = "0.3", features = [
|
||||
"Url",
|
||||
"UrlSearchParams",
|
||||
"Window",
|
||||
"Location"
|
||||
"Location",
|
||||
], optional = true }
|
||||
wasm-bindgen = { version = "0.2", optional = true }
|
||||
js-sys = { version = "0.3", optional = true }
|
||||
@@ -46,14 +46,11 @@ hot-reload = ["dioxus/hot-reload"]
|
||||
|
||||
[dev-dependencies]
|
||||
console_error_panic_hook = "0.1.7"
|
||||
dioxus-web = { path = "../web" }
|
||||
log = "0.4.14"
|
||||
wasm-logger = "0.2.0"
|
||||
wasm-bindgen-test = "0.3"
|
||||
gloo-utils = "0.1.2"
|
||||
dioxus-ssr = { path = "../ssr" }
|
||||
|
||||
dioxus-router = { path = ".", default-features = false }
|
||||
dioxus-web = { path = "../web" }
|
||||
|
||||
[target.wasm32-unknown-unknown.dev-dependencies]
|
||||
dioxus-router = { path = ".", features = ["web"] }
|
||||
|
||||
@@ -4,8 +4,6 @@ use dioxus::prelude::*;
|
||||
use dioxus_router::*;
|
||||
|
||||
fn main() {
|
||||
console_error_panic_hook::set_once();
|
||||
wasm_logger::init(wasm_logger::Config::new(log::Level::Debug));
|
||||
dioxus_web::launch(app);
|
||||
}
|
||||
|
||||
|
||||
@@ -120,15 +120,15 @@ pub fn Link<'a>(cx: Scope<'a, LinkProps<'a>>) -> Element {
|
||||
id: format_args!("{}", id.unwrap_or("")),
|
||||
title: format_args!("{}", title.unwrap_or("")),
|
||||
prevent_default: "{prevent_default}",
|
||||
target: format_args!("{}", if *new_tab { "_blank" } else { "" }),
|
||||
target: format_args!("{}", if * new_tab { "_blank" } else { "" }),
|
||||
onclick: move |_| {
|
||||
if !outerlink {
|
||||
if let Some(service) = svc {
|
||||
service.push_route(to, cx.props.title.map(|f| f.to_string()), None);
|
||||
} else {
|
||||
log::error!(
|
||||
"Attempted to create a Link to {} outside of a Router context",
|
||||
cx.props.to,
|
||||
"Attempted to create a Link to {} outside of a Router context", cx.props
|
||||
.to,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
use crate::ParsedRoute;
|
||||
use crate::{cfg::RouterCfg, RouteEvent, RouterCore};
|
||||
use crate::{cfg::RouterCfg, RouterCore};
|
||||
use dioxus::prelude::*;
|
||||
use futures_util::stream::StreamExt;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The props for the [`Router`](fn.Router.html) component.
|
||||
@@ -40,81 +38,13 @@ pub struct RouterProps<'a> {
|
||||
#[allow(non_snake_case)]
|
||||
pub fn Router<'a>(cx: Scope<'a, RouterProps<'a>>) -> Element {
|
||||
let svc = cx.use_hook(|_| {
|
||||
let (tx, mut rx) = futures_channel::mpsc::unbounded::<RouteEvent>();
|
||||
|
||||
let svc = RouterCore::new(
|
||||
tx,
|
||||
cx.provide_context(RouterCore::new(
|
||||
&cx,
|
||||
RouterCfg {
|
||||
base_url: cx.props.base_url.map(|s| s.to_string()),
|
||||
active_class: cx.props.active_class.map(|s| s.to_string()),
|
||||
},
|
||||
);
|
||||
|
||||
cx.spawn({
|
||||
let svc = svc.clone();
|
||||
let regen_route = cx.schedule_update_any();
|
||||
let router_id = cx.scope_id();
|
||||
|
||||
async move {
|
||||
while let Some(msg) = rx.next().await {
|
||||
match msg {
|
||||
RouteEvent::Push {
|
||||
route,
|
||||
serialized_state,
|
||||
title,
|
||||
} => {
|
||||
let new_route = Arc::new(ParsedRoute {
|
||||
url: svc.current_location().url.join(&route).ok().unwrap(),
|
||||
title,
|
||||
serialized_state,
|
||||
});
|
||||
|
||||
svc.history.push(&new_route);
|
||||
svc.stack.borrow_mut().push(new_route);
|
||||
}
|
||||
|
||||
RouteEvent::Replace {
|
||||
route,
|
||||
title,
|
||||
serialized_state,
|
||||
} => {
|
||||
let new_route = Arc::new(ParsedRoute {
|
||||
url: svc.current_location().url.join(&route).ok().unwrap(),
|
||||
title,
|
||||
serialized_state,
|
||||
});
|
||||
|
||||
svc.history.replace(&new_route);
|
||||
*svc.stack.borrow_mut().last_mut().unwrap() = new_route;
|
||||
}
|
||||
|
||||
RouteEvent::Pop => {
|
||||
let mut stack = svc.stack.borrow_mut();
|
||||
|
||||
if stack.len() == 1 {
|
||||
continue;
|
||||
}
|
||||
|
||||
stack.pop();
|
||||
}
|
||||
}
|
||||
|
||||
svc.route_found.set(None);
|
||||
|
||||
regen_route(router_id);
|
||||
|
||||
for listener in svc.onchange_listeners.borrow().iter() {
|
||||
regen_route(*listener);
|
||||
}
|
||||
|
||||
for route in svc.ordering.borrow().iter().rev() {
|
||||
regen_route(*route);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
cx.provide_context(svc)
|
||||
))
|
||||
});
|
||||
|
||||
// next time we run the rout_found will be filled
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// does each window have its own router? probably, lol
|
||||
|
||||
use crate::cfg::RouterCfg;
|
||||
use dioxus::core::ScopeId;
|
||||
use futures_channel::mpsc::UnboundedSender;
|
||||
use dioxus::core::{ScopeId, ScopeState, VirtualDom};
|
||||
use std::any::Any;
|
||||
use std::sync::Weak;
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
collections::{HashMap, HashSet},
|
||||
@@ -45,8 +45,6 @@ pub struct RouterCore {
|
||||
|
||||
pub(crate) stack: RefCell<Vec<Arc<ParsedRoute>>>,
|
||||
|
||||
pub(crate) tx: UnboundedSender<RouteEvent>,
|
||||
|
||||
pub(crate) slots: Rc<RefCell<HashMap<ScopeId, String>>>,
|
||||
|
||||
pub(crate) ordering: Rc<RefCell<Vec<ScopeId>>>,
|
||||
@@ -55,6 +53,10 @@ pub struct RouterCore {
|
||||
|
||||
pub(crate) history: Box<dyn RouterProvider>,
|
||||
|
||||
pub(crate) regen_any_route: Arc<dyn Fn(ScopeId)>,
|
||||
|
||||
pub(crate) router_id: ScopeId,
|
||||
|
||||
pub(crate) cfg: RouterCfg,
|
||||
}
|
||||
|
||||
@@ -74,41 +76,38 @@ pub struct ParsedRoute {
|
||||
pub serialized_state: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum RouteEvent {
|
||||
Push {
|
||||
route: String,
|
||||
title: Option<String>,
|
||||
serialized_state: Option<String>,
|
||||
},
|
||||
Replace {
|
||||
route: String,
|
||||
title: Option<String>,
|
||||
serialized_state: Option<String>,
|
||||
},
|
||||
Pop,
|
||||
}
|
||||
|
||||
impl RouterCore {
|
||||
pub(crate) fn new(tx: UnboundedSender<RouteEvent>, cfg: RouterCfg) -> Arc<Self> {
|
||||
pub(crate) fn new(cx: &ScopeState, cfg: RouterCfg) -> Arc<Self> {
|
||||
#[cfg(feature = "web")]
|
||||
let history = Box::new(web::new(tx.clone()));
|
||||
let history = Box::new(web::new());
|
||||
|
||||
#[cfg(not(feature = "web"))]
|
||||
let history = Box::new(hash::new());
|
||||
|
||||
let route = Arc::new(history.init_location());
|
||||
|
||||
Arc::new(Self {
|
||||
let svc = Arc::new(Self {
|
||||
cfg,
|
||||
tx,
|
||||
regen_any_route: cx.schedule_update_any(),
|
||||
router_id: cx.scope_id(),
|
||||
route_found: Cell::new(None),
|
||||
stack: RefCell::new(vec![route]),
|
||||
ordering: Default::default(),
|
||||
slots: Default::default(),
|
||||
onchange_listeners: Default::default(),
|
||||
history,
|
||||
})
|
||||
});
|
||||
|
||||
svc.history.attach_listeners(Arc::downgrade(&svc));
|
||||
|
||||
svc
|
||||
}
|
||||
|
||||
/// Push a new route with no custom title or serialized state.
|
||||
///
|
||||
/// This is a convenience method for easily navigating.
|
||||
pub fn navigate_to(&self, route: &str) {
|
||||
self.push_route(route, None, None);
|
||||
}
|
||||
|
||||
/// Push a new route to the history.
|
||||
@@ -117,16 +116,16 @@ impl RouterCore {
|
||||
///
|
||||
/// This does not modify the current route
|
||||
pub fn push_route(&self, route: &str, title: Option<String>, serialized_state: Option<String>) {
|
||||
let _ = self.tx.unbounded_send(RouteEvent::Push {
|
||||
route: route.to_string(),
|
||||
let new_route = Arc::new(ParsedRoute {
|
||||
url: self.current_location().url.join(route).ok().unwrap(),
|
||||
title,
|
||||
serialized_state,
|
||||
});
|
||||
}
|
||||
|
||||
/// Pop the current route from the history.
|
||||
pub fn pop_route(&self) {
|
||||
let _ = self.tx.unbounded_send(RouteEvent::Pop);
|
||||
self.history.push(&new_route);
|
||||
self.stack.borrow_mut().push(new_route);
|
||||
|
||||
self.regen_routes();
|
||||
}
|
||||
|
||||
/// Instead of pushing a new route, replaces the current route.
|
||||
@@ -136,11 +135,44 @@ impl RouterCore {
|
||||
title: Option<String>,
|
||||
serialized_state: Option<String>,
|
||||
) {
|
||||
let _ = self.tx.unbounded_send(RouteEvent::Replace {
|
||||
route: route.to_string(),
|
||||
let new_route = Arc::new(ParsedRoute {
|
||||
url: self.current_location().url.join(route).ok().unwrap(),
|
||||
title,
|
||||
serialized_state,
|
||||
});
|
||||
|
||||
self.history.replace(&new_route);
|
||||
*self.stack.borrow_mut().last_mut().unwrap() = new_route;
|
||||
|
||||
self.regen_routes();
|
||||
}
|
||||
|
||||
/// Pop the current route from the history.
|
||||
pub fn pop_route(&self) {
|
||||
let mut stack = self.stack.borrow_mut();
|
||||
|
||||
if stack.len() > 1 {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
self.regen_routes();
|
||||
}
|
||||
|
||||
/// Regenerate any routes that need to be regenerated, discarding the currently found route
|
||||
///
|
||||
/// You probably don't need this method
|
||||
pub fn regen_routes(&self) {
|
||||
self.route_found.set(None);
|
||||
|
||||
(self.regen_any_route)(self.router_id);
|
||||
|
||||
for listener in self.onchange_listeners.borrow().iter() {
|
||||
(self.regen_any_route)(*listener);
|
||||
}
|
||||
|
||||
for route in self.ordering.borrow().iter().rev() {
|
||||
(self.regen_any_route)(*route);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the current location of the Router
|
||||
@@ -196,6 +228,20 @@ impl RouterCore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the router service from an existing VirtualDom.
|
||||
///
|
||||
/// Takes an optional target_scope parameter to specify the scope to use if ScopeId is not the component
|
||||
/// that owns the router.
|
||||
///
|
||||
/// This might change in the future.
|
||||
pub fn get_router_from_vdom(
|
||||
dom: &VirtualDom,
|
||||
target_scope: Option<ScopeId>,
|
||||
) -> Option<Arc<RouterCore>> {
|
||||
dom.get_scope(target_scope.unwrap_or(ScopeId(0)))
|
||||
.and_then(|scope| scope.consume_context::<Arc<RouterCore>>())
|
||||
}
|
||||
|
||||
fn clean_route(route: String) -> String {
|
||||
if route.as_str() == "/" {
|
||||
return route;
|
||||
@@ -236,8 +282,6 @@ fn route_matches_path(cur: &Url, attempt: &str, base_url: Option<&String>) -> bo
|
||||
|
||||
let attempt_pieces = clean_path(attempt).split('/').collect::<Vec<_>>();
|
||||
|
||||
log::trace!("Comparing {:?} to {:?}", cur_pieces, attempt_pieces);
|
||||
|
||||
if attempt_pieces.len() != cur_pieces.len() {
|
||||
return false;
|
||||
}
|
||||
@@ -262,6 +306,7 @@ pub(crate) trait RouterProvider {
|
||||
fn replace(&self, route: &ParsedRoute);
|
||||
fn native_location(&self) -> Box<dyn Any>;
|
||||
fn init_location(&self) -> ParsedRoute;
|
||||
fn attach_listeners(&self, svc: Weak<RouterCore>);
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "web"))]
|
||||
@@ -291,22 +336,23 @@ mod hash {
|
||||
}
|
||||
|
||||
fn replace(&self, _route: &ParsedRoute) {}
|
||||
|
||||
fn attach_listeners(&self, _svc: Weak<RouterCore>) {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "web")]
|
||||
mod web {
|
||||
use super::RouterProvider;
|
||||
use crate::{ParsedRoute, RouteEvent};
|
||||
use crate::ParsedRoute;
|
||||
|
||||
use futures_channel::mpsc::UnboundedSender;
|
||||
use gloo_events::EventListener;
|
||||
use std::any::Any;
|
||||
use std::{any::Any, cell::Cell};
|
||||
use web_sys::History;
|
||||
|
||||
pub struct WebRouter {
|
||||
// keep it around so it drops when the router is dropped
|
||||
_listener: gloo_events::EventListener,
|
||||
_listener: Cell<Option<gloo_events::EventListener>>,
|
||||
|
||||
window: web_sys::Window,
|
||||
history: History,
|
||||
@@ -358,30 +404,25 @@ mod web {
|
||||
serialized_state: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn attach_listeners(&self, svc: std::sync::Weak<crate::RouterCore>) {
|
||||
self._listener.set(Some(EventListener::new(
|
||||
&web_sys::window().unwrap(),
|
||||
"popstate",
|
||||
move |_| {
|
||||
if let Some(svc) = svc.upgrade() {
|
||||
svc.pop_route();
|
||||
}
|
||||
},
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn new(tx: UnboundedSender<RouteEvent>) -> WebRouter {
|
||||
pub(crate) fn new() -> WebRouter {
|
||||
WebRouter {
|
||||
history: web_sys::window().unwrap().history().unwrap(),
|
||||
window: web_sys::window().unwrap(),
|
||||
_listener: EventListener::new(&web_sys::window().unwrap(), "popstate", move |_| {
|
||||
let _ = tx.unbounded_send(RouteEvent::Pop);
|
||||
}),
|
||||
_listener: Cell::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Route { to: "/blog/:id" }
|
||||
Route { to: "/blog/:id" }
|
||||
Route { to: "/blog/:id" }
|
||||
Route { to: "/blog/:id" }
|
||||
Route { to: "/blog/:id" }
|
||||
|
||||
*/
|
||||
@@ -1,28 +0,0 @@
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use dioxus::prelude::*;
|
||||
use dioxus_router::*;
|
||||
|
||||
#[test]
|
||||
fn generates_without_error() {
|
||||
let mut app = VirtualDom::new(app);
|
||||
app.rebuild();
|
||||
|
||||
let out = dioxus_ssr::render_vdom(&app);
|
||||
|
||||
assert_eq!(out, "<nav>navbar</nav>default<!--placeholder-->");
|
||||
}
|
||||
|
||||
fn app(cx: Scope) -> Element {
|
||||
cx.render(rsx! {
|
||||
Router {
|
||||
nav { "navbar" }
|
||||
Route { to: "/", "default" }
|
||||
Route { to: "/home", Home {} }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn Home(cx: Scope) -> Element {
|
||||
cx.render(rsx! { h1 { "Home" } })
|
||||
}
|
||||
@@ -73,10 +73,10 @@ If the active class is given on both, the `Router` and the `Link`, the one on th
|
||||
Router {
|
||||
active_class: "custom-active", // All active links in this router get this class.
|
||||
Link { to: "/", "Home" },
|
||||
Link {
|
||||
Link {
|
||||
to: "/blog",
|
||||
active_class: "is-active", // Only for this Link. Overwrites "custom-active" from Router.
|
||||
"Blog"
|
||||
"Blog"
|
||||
},
|
||||
}
|
||||
```
|
||||
@@ -207,7 +207,7 @@ let mut prerendered_pages = dom
|
||||
let _ = dom.rebuild();
|
||||
|
||||
// render the page and insert it into our map
|
||||
(route, dioxus::ssr::render_vdom(&dom))
|
||||
(route, dioxus_ssr::render_vdom(&dom))
|
||||
})
|
||||
.collect::<HashMap<_, _>>();
|
||||
```
|
||||
Reference in new issue
Block a user