fix external router examples
This commit is contained in:
1 parent
45a004bf74
commit
07446386e6
7 files changed
+157
-133
No files matched your search
+92
-80
@@ -4,97 +4,109 @@ use dioxus::prelude::*;
|
|||||||
use dioxus_router::prelude::*;
|
use dioxus_router::prelude::*;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
dioxus_desktop::launch(app);
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
dioxus_web::launch(App);
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
dioxus_desktop::launch(App);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn app(cx: Scope) -> Element {
|
// ANCHOR: router
|
||||||
use_router(cx, &RouterConfiguration::default, &|| {
|
#[derive(Routable, Clone)]
|
||||||
Segment::content(comp(Home))
|
#[rustfmt::skip]
|
||||||
.fixed(
|
enum Route {
|
||||||
"users",
|
#[layout(NavBar)]
|
||||||
Route::empty()
|
#[route("/")]
|
||||||
.nested(Segment::content(comp(UserList)).catch_all((comp(User), UserId {}))),
|
Home {},
|
||||||
)
|
#[nest("/blog")]
|
||||||
.fixed(
|
#[layout(Blog)]
|
||||||
"blog",
|
#[route("/")]
|
||||||
Route::empty().nested(
|
BlogList {},
|
||||||
Segment::content(comp(BlogList)).catch_all((comp(BlogPost), PostId {})),
|
#[route("/blog/:name")]
|
||||||
),
|
BlogPost { name: String },
|
||||||
)
|
#[end_layout]
|
||||||
.fallback(comp(E404))
|
#[end_nest]
|
||||||
});
|
#[end_layout]
|
||||||
|
#[nest("/myblog")]
|
||||||
cx.render(rsx! {
|
#[redirect("/", || Route::BlogList {})]
|
||||||
ul {
|
#[redirect("/:name", |name: String| Route::BlogPost { name })]
|
||||||
li { Link { target: "/", "Go home!" } }
|
#[end_nest]
|
||||||
li { Link { target: "/users", "List all users" } }
|
#[route("/:...route")]
|
||||||
li { Link { target: "/blog", "Blog posts" }}
|
PageNotFound {
|
||||||
}
|
route: Vec<String>,
|
||||||
|
},
|
||||||
Outlet { }
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
// ANCHOR_END: router
|
||||||
|
|
||||||
fn Home(cx: Scope) -> Element {
|
fn App(cx: Scope) -> Element {
|
||||||
render!(h1 { "Home" })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn BlogList(cx: Scope) -> Element {
|
|
||||||
render! {
|
render! {
|
||||||
h1 { "Blog Posts" }
|
Router {}
|
||||||
ul {
|
|
||||||
li { Link { target: "/blog/1", "First blog post" } }
|
|
||||||
li { Link { target: "/blog/2", "Second blog post" } }
|
|
||||||
li { Link { target: "/blog/3", "Third blog post" } }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct PostId;
|
#[inline_props]
|
||||||
fn BlogPost(cx: Scope) -> Element {
|
fn NavBar(cx: Scope) -> Element {
|
||||||
let post = use_route(cx)?.parameter::<PostId>().unwrap();
|
|
||||||
|
|
||||||
cx.render(rsx! {
|
|
||||||
div {
|
|
||||||
h1 { "Reading blog post: {post}" }
|
|
||||||
p { "example blog post" }
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn UserList(cx: Scope) -> Element {
|
|
||||||
render! {
|
render! {
|
||||||
h1 { "Users" }
|
nav {
|
||||||
ul {
|
ul {
|
||||||
li { Link { target: "/users/bill", "Bill" } }
|
li { Link { target: Route::Home {}, "Home" } }
|
||||||
li { Link { target: "/users/jeremy", "Jeremy" } }
|
li { Link { target: Route::BlogList {}, "Blog" } }
|
||||||
li { Link { target: "/users/adrian", "Adrian" } }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct UserId;
|
|
||||||
fn User(cx: Scope) -> Element {
|
|
||||||
let state = use_route(cx)?;
|
|
||||||
|
|
||||||
let user = state.parameter::<UserId>().unwrap();
|
|
||||||
|
|
||||||
let query = state.query.as_ref().cloned().unwrap_or_default();
|
|
||||||
let bold = query.contains("bold") && !query.contains("bold=false");
|
|
||||||
|
|
||||||
cx.render(rsx! {
|
|
||||||
div {
|
|
||||||
h1 { "Showing user: {user}" }
|
|
||||||
|
|
||||||
if bold {
|
|
||||||
rsx!{ b { "bold" } }
|
|
||||||
} else {
|
|
||||||
rsx!{ i { "italic" } }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
Outlet {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn E404(cx: Scope) -> Element {
|
#[inline_props]
|
||||||
render!(h1 { "Error 404 - Page not Found" })
|
fn Home(cx: Scope) -> Element {
|
||||||
|
render! {
|
||||||
|
h1 { "Welcome to the Dioxus Blog!" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline_props]
|
||||||
|
fn Blog(cx: Scope) -> Element {
|
||||||
|
render! {
|
||||||
|
h1 { "Blog" }
|
||||||
|
Outlet {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline_props]
|
||||||
|
fn BlogList(cx: Scope) -> Element {
|
||||||
|
render! {
|
||||||
|
h2 { "Choose a post" }
|
||||||
|
ul {
|
||||||
|
li {
|
||||||
|
Link {
|
||||||
|
target: Route::BlogPost { name: "Blog post 1".into() },
|
||||||
|
"Read the first blog post"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
li {
|
||||||
|
Link {
|
||||||
|
target: Route::BlogPost { name: "Blog post 2".into() },
|
||||||
|
"Read the second blog post"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline_props]
|
||||||
|
fn BlogPost(cx: Scope, name: String) -> Element {
|
||||||
|
render! {
|
||||||
|
h2 { "Blog Post: {name}"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline_props]
|
||||||
|
fn PageNotFound(cx: Scope, route: Vec<String>) -> Element {
|
||||||
|
render! {
|
||||||
|
h1 { "Page not found" }
|
||||||
|
p { "We are terribly sorry, but the page you requested doesn't exist." }
|
||||||
|
pre {
|
||||||
|
color: "red",
|
||||||
|
"log:\nattemped to navigate to: {route:?}"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
#![allow(non_snake_case)]
|
#![allow(non_snake_case)]
|
||||||
use dioxus::prelude::*;
|
use dioxus::prelude::*;
|
||||||
use dioxus_fullstack::prelude::*;
|
use dioxus_fullstack::prelude::*;
|
||||||
use dioxus_router::*;
|
use dioxus_router::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
@@ -34,6 +34,8 @@ fn main() {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
use axum::extract::State;
|
use axum::extract::State;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
PostServerData::register().unwrap();
|
PostServerData::register().unwrap();
|
||||||
GetServerData::register().unwrap();
|
GetServerData::register().unwrap();
|
||||||
tokio::runtime::Runtime::new()
|
tokio::runtime::Runtime::new()
|
||||||
@@ -57,7 +59,7 @@ fn main() {
|
|||||||
&ServeConfigBuilder::new(
|
&ServeConfigBuilder::new(
|
||||||
App,
|
App,
|
||||||
AppProps {
|
AppProps {
|
||||||
route: Some(format!("http://{addr}{uri}")),
|
route: Route::from_str(&uri.to_string()).ok(),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.build(),
|
.build(),
|
||||||
@@ -74,48 +76,64 @@ fn main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Props, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Routable, Serialize, Deserialize, Debug, PartialEq)]
|
||||||
struct AppProps {
|
enum Route {
|
||||||
route: Option<String>,
|
#[route("/")]
|
||||||
|
Home {},
|
||||||
|
#[route("/blog")]
|
||||||
|
Blog {},
|
||||||
}
|
}
|
||||||
|
|
||||||
fn App(cx: Scope<AppProps>) -> Element {
|
#[inline_props]
|
||||||
cx.render(rsx! {
|
fn Blog(cx: Scope) -> Element {
|
||||||
Router {
|
render! {
|
||||||
initial_url: cx.props.route.clone(),
|
Link {
|
||||||
|
target: Route::Home {},
|
||||||
Route { to: "/blog",
|
"Go to counter"
|
||||||
Link {
|
}
|
||||||
to: "/",
|
table {
|
||||||
"Go to counter"
|
tbody {
|
||||||
}
|
for _ in 0..100 {
|
||||||
table {
|
tr {
|
||||||
tbody {
|
|
||||||
for _ in 0..100 {
|
for _ in 0..100 {
|
||||||
tr {
|
td { "hello world!" }
|
||||||
for _ in 0..100 {
|
|
||||||
td { "hello world!" }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
// Fallback
|
}
|
||||||
Route { to: "",
|
}
|
||||||
Counter {}
|
}
|
||||||
},
|
|
||||||
|
#[derive(Clone, Debug, Props, PartialEq, Serialize, Deserialize)]
|
||||||
|
struct AppProps {
|
||||||
|
route: Option<Route>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn App(cx: Scope<AppProps>) -> Element {
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
let initial_route = cx.props.route.clone().unwrap_or(Route::Home {});
|
||||||
|
cx.render(rsx! {
|
||||||
|
Router {
|
||||||
|
config: move || RouterConfig::default().history({
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
let history = MemoryHistory::with_initial_path(initial_route);
|
||||||
|
#[cfg(feature = "web")]
|
||||||
|
let history = WebHistory::default();
|
||||||
|
history
|
||||||
|
})
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn Counter(cx: Scope) -> Element {
|
#[inline_props]
|
||||||
|
fn Home(cx: Scope) -> Element {
|
||||||
let mut count = use_state(cx, || 0);
|
let mut count = use_state(cx, || 0);
|
||||||
let text = use_state(cx, || "...".to_string());
|
let text = use_state(cx, || "...".to_string());
|
||||||
|
|
||||||
cx.render(rsx! {
|
cx.render(rsx! {
|
||||||
Link {
|
Link {
|
||||||
to: "/blog",
|
target: Route::Blog {}
|
||||||
"Go to blog"
|
"Go to blog"
|
||||||
}
|
}
|
||||||
div{
|
div{
|
||||||
|
|||||||
@@ -5,13 +5,13 @@ use std::{cell::RefCell, str::FromStr};
|
|||||||
use crate::{
|
use crate::{
|
||||||
prelude::{GenericOutlet, GenericRouterContext},
|
prelude::{GenericOutlet, GenericRouterContext},
|
||||||
routable::Routable,
|
routable::Routable,
|
||||||
router_cfg::RouterConfiguration,
|
router_cfg::RouterConfig,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// The config for [`GenericRouter`].
|
/// The config for [`GenericRouter`].
|
||||||
pub struct RouterConfigFactory<R: Routable> {
|
pub struct RouterConfigFactory<R: Routable> {
|
||||||
#[allow(clippy::type_complexity)]
|
#[allow(clippy::type_complexity)]
|
||||||
config: RefCell<Option<Box<dyn FnOnce() -> RouterConfiguration<R>>>>,
|
config: RefCell<Option<Box<dyn FnOnce() -> RouterConfig<R>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Routable> Default for RouterConfigFactory<R>
|
impl<R: Routable> Default for RouterConfigFactory<R>
|
||||||
@@ -19,13 +19,11 @@ where
|
|||||||
<R as FromStr>::Err: std::fmt::Display,
|
<R as FromStr>::Err: std::fmt::Display,
|
||||||
{
|
{
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self::from(RouterConfiguration::default)
|
Self::from(RouterConfig::default)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Routable, F: FnOnce() -> RouterConfiguration<R> + 'static> From<F>
|
impl<R: Routable, F: FnOnce() -> RouterConfig<R> + 'static> From<F> for RouterConfigFactory<R> {
|
||||||
for RouterConfigFactory<R>
|
|
||||||
{
|
|
||||||
fn from(value: F) -> Self {
|
fn from(value: F) -> Self {
|
||||||
Self {
|
Self {
|
||||||
config: RefCell::new(Some(Box::new(value))),
|
config: RefCell::new(Some(Box::new(value))),
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use dioxus::prelude::*;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
history::HistoryProvider, navigation::NavigationTarget, routable::Routable,
|
history::HistoryProvider, navigation::NavigationTarget, routable::Routable,
|
||||||
router_cfg::RouterConfiguration,
|
router_cfg::RouterConfig,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// An error that can occur when navigating.
|
/// An error that can occur when navigating.
|
||||||
@@ -15,7 +15,8 @@ use crate::{
|
|||||||
pub struct ExternalNavigationFailure(String);
|
pub struct ExternalNavigationFailure(String);
|
||||||
|
|
||||||
/// A function the router will call after every routing update.
|
/// A function the router will call after every routing update.
|
||||||
pub(crate) type RoutingCallback<R> = Arc<dyn Fn(GenericRouterContext<R>) -> Option<NavigationTarget<R>>>;
|
pub(crate) type RoutingCallback<R> =
|
||||||
|
Arc<dyn Fn(GenericRouterContext<R>) -> Option<NavigationTarget<R>>>;
|
||||||
|
|
||||||
struct MutableRouterState<R>
|
struct MutableRouterState<R>
|
||||||
where
|
where
|
||||||
@@ -70,10 +71,7 @@ impl<R> GenericRouterContext<R>
|
|||||||
where
|
where
|
||||||
R: Routable,
|
R: Routable,
|
||||||
{
|
{
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(cfg: RouterConfig<R>, mark_dirty: Arc<dyn Fn(ScopeId) + Sync + Send>) -> Self
|
||||||
cfg: RouterConfiguration<R>,
|
|
||||||
mark_dirty: Arc<dyn Fn(ScopeId) + Sync + Send>,
|
|
||||||
) -> Self
|
|
||||||
where
|
where
|
||||||
R: Clone,
|
R: Clone,
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -33,17 +33,15 @@ where
|
|||||||
/// OtherPage {},
|
/// OtherPage {},
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// let mut history = MemoryHistory::<Route>::with_initial_path("/").unwrap();
|
/// let mut history = MemoryHistory::<Route>::with_initial_path(Route::Index {}).unwrap();
|
||||||
/// assert_eq!(history.current_route(), Route::Index {});
|
/// assert_eq!(history.current_route(), Route::Index {});
|
||||||
/// assert_eq!(history.can_go_back(), false);
|
/// assert_eq!(history.can_go_back(), false);
|
||||||
/// ```
|
/// ```
|
||||||
pub fn with_initial_path(path: impl AsRef<str>) -> Result<Self, <R as FromStr>::Err> {
|
pub fn with_initial_path(path: R) -> Self {
|
||||||
let path = path.as_ref();
|
Self {
|
||||||
|
current: path,
|
||||||
Ok(Self {
|
|
||||||
current: R::from_str(path)?,
|
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ pub mod prelude {
|
|||||||
pub use crate::hooks::*;
|
pub use crate::hooks::*;
|
||||||
pub use crate::navigation::*;
|
pub use crate::navigation::*;
|
||||||
pub use crate::routable::*;
|
pub use crate::routable::*;
|
||||||
pub use crate::router_cfg::RouterConfiguration;
|
pub use crate::router_cfg::RouterConfig;
|
||||||
pub use dioxus_router_macro::Routable;
|
pub use dioxus_router_macro::Routable;
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
|
|||||||
@@ -23,15 +23,15 @@ use crate::prelude::*;
|
|||||||
/// #[route("/")]
|
/// #[route("/")]
|
||||||
/// Index {},
|
/// Index {},
|
||||||
/// }
|
/// }
|
||||||
/// let cfg = RouterConfiguration::default().history(WebHistory<Route>::default());
|
/// let cfg = RouterConfig::default().history(WebHistory<Route>::default());
|
||||||
/// ```
|
/// ```
|
||||||
pub struct RouterConfiguration<R: Routable> {
|
pub struct RouterConfig<R: Routable> {
|
||||||
pub(crate) failure_external_navigation: fn(Scope) -> Element,
|
pub(crate) failure_external_navigation: fn(Scope) -> Element,
|
||||||
pub(crate) history: Box<dyn HistoryProvider<R>>,
|
pub(crate) history: Box<dyn HistoryProvider<R>>,
|
||||||
pub(crate) on_update: Option<RoutingCallback<R>>,
|
pub(crate) on_update: Option<RoutingCallback<R>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Routable + Clone> Default for RouterConfiguration<R>
|
impl<R: Routable + Clone> Default for RouterConfig<R>
|
||||||
where
|
where
|
||||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
<R as std::str::FromStr>::Err: std::fmt::Display,
|
||||||
{
|
{
|
||||||
@@ -50,7 +50,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Routable> RouterConfiguration<R> {
|
impl<R: Routable> RouterConfig<R> {
|
||||||
/// A function to be called whenever the routing is updated.
|
/// A function to be called whenever the routing is updated.
|
||||||
///
|
///
|
||||||
/// The callback is invoked after the routing is updated, but before components and hooks are
|
/// The callback is invoked after the routing is updated, but before components and hooks are
|
||||||
|
|||||||
Reference in new issue
Block a user