feat: Allow using NavigationTarget outside router (#3633)

* feat: Allow using `NavigationTarget` outside of router

* chore: Update import

* chore: Update imports

* fmt
This commit is contained in:
Marc Espin authored and GitHub committed 2025-01-28 10:52:48 -08:00
1 parent 4e955d0e3b
commit c5f43dd13e
2 files changed
+21 -9

No files matched your search

+6
View File
@@ -12,3 +12,9 @@ pub fn use_router() -> RouterContext {
pub fn router() -> RouterContext { pub fn router() -> RouterContext {
dioxus_lib::prelude::consume_context() dioxus_lib::prelude::consume_context()
} }
/// Try to acquire the router without subscribing to updates.
#[doc(alias = "url")]
pub fn try_router() -> Option<RouterContext> {
dioxus_lib::prelude::try_consume_context()
}
+15 -9
View File
@@ -7,7 +7,9 @@ use std::{
use url::{ParseError, Url}; use url::{ParseError, Url};
use crate::{components::child_router::consume_child_route_mapping, routable::Routable, router}; use crate::{
components::child_router::consume_child_route_mapping, hooks::try_router, routable::Routable,
};
impl<R: Routable> From<R> for NavigationTarget { impl<R: Routable> From<R> for NavigationTarget {
fn from(value: R) -> Self { fn from(value: R) -> Self {
@@ -94,20 +96,24 @@ impl<R: Routable> From<R> for NavigationTarget<R> {
impl From<&str> for NavigationTarget { impl From<&str> for NavigationTarget {
fn from(value: &str) -> Self { fn from(value: &str) -> Self {
let router = router(); match try_router() {
match router.internal_route(value) { Some(router) => match router.internal_route(value) {
true => NavigationTarget::Internal(value.to_string()), true => NavigationTarget::Internal(value.to_string()),
false => NavigationTarget::External(value.to_string()), false => NavigationTarget::External(value.to_string()),
},
None => NavigationTarget::External(value.to_string()),
} }
} }
} }
impl From<String> for NavigationTarget { impl From<String> for NavigationTarget {
fn from(value: String) -> Self { fn from(value: String) -> Self {
let router = router(); match try_router() {
match router.internal_route(&value) { Some(router) => match router.internal_route(&value) {
true => NavigationTarget::Internal(value), true => NavigationTarget::Internal(value),
false => NavigationTarget::External(value), false => NavigationTarget::External(value),
},
None => NavigationTarget::External(value.to_string()),
} }
} }
} }