Implement hash fragments in the router (#2320)
* implement hash fragments in the router * clean up query and search example --------- Co-authored-by: Jonathan Kelley <jkelleyrtp@gmail.com>
This commit is contained in:
1 parent
dd8e69635b
commit
08da9a1253
17 files changed
+550
-190
No files matched your search
@@ -392,9 +392,7 @@ where
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
fn deserialize_leaky<'a, 'de, T: serde::Deserialize<'de>, D>(
|
||||
deserializer: D,
|
||||
) -> Result<&'a [T], D::Error>
|
||||
fn deserialize_leaky<'a, 'de, T, D>(deserializer: D) -> Result<&'a [T], D::Error>
|
||||
where
|
||||
T: serde::Deserialize<'de>,
|
||||
D: serde::Deserializer<'de>,
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
use quote::quote;
|
||||
use syn::{Ident, Type};
|
||||
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct HashFragment {
|
||||
pub ident: Ident,
|
||||
pub ty: Type,
|
||||
}
|
||||
|
||||
impl HashFragment {
|
||||
pub fn contains_ident(&self, ident: &Ident) -> bool {
|
||||
self.ident == *ident
|
||||
}
|
||||
|
||||
pub fn parse(&self) -> TokenStream2 {
|
||||
let ident = &self.ident;
|
||||
let ty = &self.ty;
|
||||
quote! {
|
||||
let #ident = <#ty as dioxus_router::routable::FromHashFragment>::from_hash_fragment(&*hash);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write(&self) -> TokenStream2 {
|
||||
let ident = &self.ident;
|
||||
quote! {
|
||||
write!(f, "#{}", #ident)?;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_from_str<'a>(
|
||||
route_span: proc_macro2::Span,
|
||||
mut fields: impl Iterator<Item = (&'a Ident, &'a Type)>,
|
||||
hash: &str,
|
||||
) -> syn::Result<Self> {
|
||||
// check if the route has a hash string
|
||||
let Some(hash) = hash.strip_prefix(':') else {
|
||||
return Err(syn::Error::new(
|
||||
route_span,
|
||||
"Failed to parse `:`. Hash fragments must be in the format '#:<field>'",
|
||||
));
|
||||
};
|
||||
|
||||
let hash_ident = Ident::new(hash, proc_macro2::Span::call_site());
|
||||
let field = fields.find(|(name, _)| *name == &hash_ident);
|
||||
|
||||
let ty = if let Some((_, ty)) = field {
|
||||
ty.clone()
|
||||
} else {
|
||||
return Err(syn::Error::new(
|
||||
route_span,
|
||||
format!("Could not find a field with the name '{}'", hash_ident),
|
||||
));
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
ident: hash_ident,
|
||||
ty,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use proc_macro2::TokenStream as TokenStream2;
|
||||
|
||||
use crate::{layout::LayoutId, route_tree::RouteTree};
|
||||
|
||||
mod hash;
|
||||
mod layout;
|
||||
mod nest;
|
||||
mod query;
|
||||
@@ -523,6 +524,11 @@ impl RouteEnum {
|
||||
from_route = true
|
||||
}
|
||||
}
|
||||
if let Some(hash) = &route.hash {
|
||||
if hash.contains_ident(field) {
|
||||
from_route = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -576,9 +582,10 @@ impl RouteEnum {
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let route = s;
|
||||
let (route, _hash) = route.split_once('#').unwrap_or((route, ""));
|
||||
let (route, hash) = route.split_once('#').unwrap_or((route, ""));
|
||||
let (route, query) = route.split_once('?').unwrap_or((route, ""));
|
||||
let query = dioxus_router::exports::urlencoding::decode(query).unwrap_or(query.into());
|
||||
let hash = dioxus_router::exports::urlencoding::decode(hash).unwrap_or(hash.into());
|
||||
let mut segments = route.split('/').map(|s| dioxus_router::exports::urlencoding::decode(s).unwrap_or(s.into()));
|
||||
// skip the first empty segment
|
||||
if s.starts_with('/') {
|
||||
|
||||
@@ -51,6 +51,66 @@ impl QuerySegment {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_from_str<'a>(
|
||||
route_span: proc_macro2::Span,
|
||||
mut fields: impl Iterator<Item = (&'a Ident, &'a Type)>,
|
||||
query: &str,
|
||||
) -> syn::Result<Self> {
|
||||
// check if the route has a query string
|
||||
if let Some(query) = query.strip_prefix(":..") {
|
||||
let query_ident = Ident::new(query, proc_macro2::Span::call_site());
|
||||
let field = fields.find(|(name, _)| *name == &query_ident);
|
||||
|
||||
let ty = if let Some((_, ty)) = field {
|
||||
ty.clone()
|
||||
} else {
|
||||
return Err(syn::Error::new(
|
||||
route_span,
|
||||
format!("Could not find a field with the name '{}'", query_ident),
|
||||
));
|
||||
};
|
||||
|
||||
Ok(QuerySegment::Single(FullQuerySegment {
|
||||
ident: query_ident,
|
||||
ty,
|
||||
}))
|
||||
} else {
|
||||
let mut query_arguments = Vec::new();
|
||||
for segment in query.split('&') {
|
||||
if segment.is_empty() {
|
||||
return Err(syn::Error::new(
|
||||
route_span,
|
||||
"Query segments should be non-empty",
|
||||
));
|
||||
}
|
||||
if let Some(query_argument) = segment.strip_prefix(':') {
|
||||
let query_ident = Ident::new(query_argument, proc_macro2::Span::call_site());
|
||||
let field = fields.find(|(name, _)| *name == &query_ident);
|
||||
|
||||
let ty = if let Some((_, ty)) = field {
|
||||
ty.clone()
|
||||
} else {
|
||||
return Err(syn::Error::new(
|
||||
route_span,
|
||||
format!("Could not find a field with the name '{}'", query_ident),
|
||||
));
|
||||
};
|
||||
|
||||
query_arguments.push(QueryArgument {
|
||||
ident: query_ident,
|
||||
ty,
|
||||
});
|
||||
} else {
|
||||
return Err(syn::Error::new(
|
||||
route_span,
|
||||
"Query segments should be a : followed by the name of the query argument",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(QuerySegment::Segments(query_arguments))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -71,7 +131,10 @@ impl FullQuerySegment {
|
||||
pub fn write(&self) -> TokenStream2 {
|
||||
let ident = &self.ident;
|
||||
quote! {
|
||||
write!(f, "?{}", #ident)?;
|
||||
{
|
||||
let as_string = #ident.to_string();
|
||||
write!(f, "?{}", dioxus_router::exports::urlencoding::encode(&as_string))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,7 +160,10 @@ impl QueryArgument {
|
||||
pub fn write(&self) -> TokenStream2 {
|
||||
let ident = &self.ident;
|
||||
quote! {
|
||||
write!(f, "{}={}", stringify!(#ident), #ident)?;
|
||||
{
|
||||
let as_string = #ident.to_string();
|
||||
write!(f, "{}={}", stringify!(#ident), dioxus_router::exports::urlencoding::encode(&as_string))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ use quote::{format_ident, quote};
|
||||
use syn::LitStr;
|
||||
|
||||
use crate::{
|
||||
hash::HashFragment,
|
||||
nest::NestId,
|
||||
query::QuerySegment,
|
||||
segment::{create_error_type, parse_route_segments, RouteSegment},
|
||||
@@ -14,6 +15,7 @@ pub(crate) struct Redirect {
|
||||
pub nests: Vec<NestId>,
|
||||
pub segments: Vec<RouteSegment>,
|
||||
pub query: Option<QuerySegment>,
|
||||
pub hash: Option<HashFragment>,
|
||||
pub function: syn::ExprClosure,
|
||||
pub index: usize,
|
||||
}
|
||||
@@ -40,6 +42,13 @@ impl Redirect {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_hash(&self) -> TokenStream {
|
||||
match &self.hash {
|
||||
Some(hash) => hash.parse(),
|
||||
None => quote! {},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(
|
||||
input: syn::parse::ParseStream,
|
||||
active_nests: Vec<NestId>,
|
||||
@@ -73,7 +82,7 @@ impl Redirect {
|
||||
}
|
||||
}
|
||||
|
||||
let (segments, query) = parse_route_segments(
|
||||
let (segments, query, hash) = parse_route_segments(
|
||||
path.span(),
|
||||
#[allow(clippy::map_identity)]
|
||||
closure_arguments.iter().map(|(name, ty)| (name, ty)),
|
||||
@@ -85,6 +94,7 @@ impl Redirect {
|
||||
nests: active_nests,
|
||||
segments,
|
||||
query,
|
||||
hash,
|
||||
function,
|
||||
index,
|
||||
})
|
||||
|
||||
@@ -9,6 +9,7 @@ use syn::{Ident, LitStr};
|
||||
|
||||
use proc_macro2::TokenStream as TokenStream2;
|
||||
|
||||
use crate::hash::HashFragment;
|
||||
use crate::layout::Layout;
|
||||
use crate::layout::LayoutId;
|
||||
use crate::nest::Nest;
|
||||
@@ -56,6 +57,7 @@ pub(crate) struct Route {
|
||||
pub route: String,
|
||||
pub segments: Vec<RouteSegment>,
|
||||
pub query: Option<QuerySegment>,
|
||||
pub hash: Option<HashFragment>,
|
||||
pub nests: Vec<NestId>,
|
||||
pub layouts: Vec<LayoutId>,
|
||||
fields: Vec<(Ident, Type)>,
|
||||
@@ -144,7 +146,7 @@ impl Route {
|
||||
_ => Vec::new(),
|
||||
};
|
||||
|
||||
let (route_segments, query) = {
|
||||
let (route_segments, query, hash) = {
|
||||
parse_route_segments(
|
||||
variant.ident.span(),
|
||||
fields.iter().map(|f| (&f.0, &f.1)),
|
||||
@@ -158,6 +160,7 @@ impl Route {
|
||||
segments: route_segments,
|
||||
route,
|
||||
query,
|
||||
hash,
|
||||
nests,
|
||||
layouts,
|
||||
fields,
|
||||
@@ -167,7 +170,8 @@ impl Route {
|
||||
pub fn display_match(&self, nests: &[Nest]) -> TokenStream2 {
|
||||
let name = &self.route_name;
|
||||
let dynamic_segments = self.dynamic_segments();
|
||||
let write_query = self.query.as_ref().map(|q| q.write());
|
||||
let write_query: Option<TokenStream2> = self.query.as_ref().map(|q| q.write());
|
||||
let write_hash = self.hash.as_ref().map(|q| q.write());
|
||||
|
||||
match &self.ty {
|
||||
RouteType::Child(field) => {
|
||||
@@ -200,6 +204,7 @@ impl Route {
|
||||
#(#write_nests)*
|
||||
#(#write_segments)*
|
||||
#write_query
|
||||
#write_hash
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -286,6 +291,11 @@ impl Route {
|
||||
from_route = true
|
||||
}
|
||||
}
|
||||
if let Some(hash) = &self.hash {
|
||||
if hash.contains_ident(name) {
|
||||
from_route = true
|
||||
}
|
||||
}
|
||||
|
||||
if from_route {
|
||||
quote! {#name}
|
||||
@@ -337,6 +347,13 @@ impl Route {
|
||||
None => quote! {},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_hash(&self) -> TokenStream2 {
|
||||
match &self.hash {
|
||||
Some(hash) => hash.parse(),
|
||||
None => quote! {},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -337,6 +337,7 @@ impl<'a> RouteTreeSegmentData<'a> {
|
||||
|
||||
let construct_variant = route.construct(nests, enum_name);
|
||||
let parse_query = route.parse_query();
|
||||
let parse_hash = route.parse_hash();
|
||||
|
||||
let insure_not_trailing = match route.ty {
|
||||
RouteType::Leaf { .. } => route
|
||||
@@ -356,6 +357,7 @@ impl<'a> RouteTreeSegmentData<'a> {
|
||||
enum_variant,
|
||||
&variant_parse_error,
|
||||
parse_query,
|
||||
parse_hash,
|
||||
),
|
||||
&error_enum_name,
|
||||
enum_variant,
|
||||
@@ -426,6 +428,7 @@ impl<'a> RouteTreeSegmentData<'a> {
|
||||
.skip_while(|(_, seg)| matches!(seg, RouteSegment::Static(_)));
|
||||
|
||||
let parse_query = redirect.parse_query();
|
||||
let parse_hash = redirect.parse_hash();
|
||||
|
||||
let insure_not_trailing = redirect
|
||||
.segments
|
||||
@@ -454,6 +457,7 @@ impl<'a> RouteTreeSegmentData<'a> {
|
||||
enum_variant,
|
||||
&variant_parse_error,
|
||||
parse_query,
|
||||
parse_hash,
|
||||
),
|
||||
&error_enum_name,
|
||||
enum_variant,
|
||||
@@ -501,6 +505,7 @@ fn return_constructed(
|
||||
enum_variant: &Ident,
|
||||
variant_parse_error: &Ident,
|
||||
parse_query: TokenStream,
|
||||
parse_hash: TokenStream,
|
||||
) -> TokenStream {
|
||||
if insure_not_trailing {
|
||||
quote! {
|
||||
@@ -514,6 +519,7 @@ fn return_constructed(
|
||||
// This is the last segment, return the parsed route
|
||||
(None, _) | (Some(""), None) => {
|
||||
#parse_query
|
||||
#parse_hash
|
||||
return Ok(#construct_variant);
|
||||
}
|
||||
_ => {
|
||||
@@ -530,6 +536,7 @@ fn return_constructed(
|
||||
} else {
|
||||
quote! {
|
||||
#parse_query
|
||||
#parse_hash
|
||||
return Ok(#construct_variant);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ use syn::{Ident, Type};
|
||||
|
||||
use proc_macro2::{Span, TokenStream as TokenStream2};
|
||||
|
||||
use crate::query::{FullQuerySegment, QueryArgument, QuerySegment};
|
||||
use crate::{hash::HashFragment, query::QuerySegment};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum RouteSegment {
|
||||
@@ -24,7 +24,12 @@ impl RouteSegment {
|
||||
pub fn write_segment(&self) -> TokenStream2 {
|
||||
match self {
|
||||
Self::Static(segment) => quote! { write!(f, "/{}", #segment)?; },
|
||||
Self::Dynamic(ident, _) => quote! { write!(f, "/{}", #ident)?; },
|
||||
Self::Dynamic(ident, _) => quote! {
|
||||
{
|
||||
let as_string = #ident.to_string();
|
||||
write!(f, "/{}", dioxus_router::exports::urlencoding::encode(&as_string))?;
|
||||
}
|
||||
},
|
||||
Self::CatchAll(ident, _) => quote! { #ident.display_route_segments(f)?; },
|
||||
}
|
||||
}
|
||||
@@ -130,15 +135,38 @@ pub fn static_segment_idx(idx: usize) -> Ident {
|
||||
|
||||
pub fn parse_route_segments<'a>(
|
||||
route_span: Span,
|
||||
fields: impl Iterator<Item = (&'a Ident, &'a Type)> + Clone,
|
||||
mut fields: impl Iterator<Item = (&'a Ident, &'a Type)> + Clone,
|
||||
route: &str,
|
||||
) -> syn::Result<(Vec<RouteSegment>, Option<QuerySegment>)> {
|
||||
) -> syn::Result<(
|
||||
Vec<RouteSegment>,
|
||||
Option<QuerySegment>,
|
||||
Option<HashFragment>,
|
||||
)> {
|
||||
let mut route_segments = Vec::new();
|
||||
|
||||
let (route_string, query) = match route.rsplit_once('?') {
|
||||
Some((route, query)) => (route, Some(query)),
|
||||
let (route_string, hash) = match route.rsplit_once('#') {
|
||||
Some((route, hash)) => (
|
||||
route,
|
||||
Some(HashFragment::parse_from_str(
|
||||
route_span,
|
||||
fields.clone(),
|
||||
hash,
|
||||
)?),
|
||||
),
|
||||
None => (route, None),
|
||||
};
|
||||
|
||||
let (route_string, query) = match route_string.rsplit_once('?') {
|
||||
Some((route, query)) => (
|
||||
route,
|
||||
Some(QuerySegment::parse_from_str(
|
||||
route_span,
|
||||
fields.clone(),
|
||||
query,
|
||||
)?),
|
||||
),
|
||||
None => (route_string, None),
|
||||
};
|
||||
let mut iterator = route_string.split('/');
|
||||
|
||||
// skip the first empty segment
|
||||
@@ -198,66 +226,7 @@ pub fn parse_route_segments<'a>(
|
||||
}
|
||||
}
|
||||
|
||||
// check if the route has a query string
|
||||
let parsed_query = match query {
|
||||
Some(query) => {
|
||||
if let Some(query) = query.strip_prefix(":..") {
|
||||
let query_ident = Ident::new(query, Span::call_site());
|
||||
let field = fields.clone().find(|(name, _)| *name == &query_ident);
|
||||
|
||||
let ty = if let Some((_, ty)) = field {
|
||||
ty.clone()
|
||||
} else {
|
||||
return Err(syn::Error::new(
|
||||
route_span,
|
||||
format!("Could not find a field with the name '{}'", query_ident),
|
||||
));
|
||||
};
|
||||
|
||||
Some(QuerySegment::Single(FullQuerySegment {
|
||||
ident: query_ident,
|
||||
ty,
|
||||
}))
|
||||
} else {
|
||||
let mut query_arguments = Vec::new();
|
||||
for segment in query.split('&') {
|
||||
if segment.is_empty() {
|
||||
return Err(syn::Error::new(
|
||||
route_span,
|
||||
"Query segments should be non-empty",
|
||||
));
|
||||
}
|
||||
if let Some(query_argument) = segment.strip_prefix(':') {
|
||||
let query_ident = Ident::new(query_argument, Span::call_site());
|
||||
let field = fields.clone().find(|(name, _)| *name == &query_ident);
|
||||
|
||||
let ty = if let Some((_, ty)) = field {
|
||||
ty.clone()
|
||||
} else {
|
||||
return Err(syn::Error::new(
|
||||
route_span,
|
||||
format!("Could not find a field with the name '{}'", query_ident),
|
||||
));
|
||||
};
|
||||
|
||||
query_arguments.push(QueryArgument {
|
||||
ident: query_ident,
|
||||
ty,
|
||||
});
|
||||
} else {
|
||||
return Err(syn::Error::new(
|
||||
route_span,
|
||||
"Query segments should be a : followed by the name of the query argument",
|
||||
));
|
||||
}
|
||||
}
|
||||
Some(QuerySegment::Segments(query_arguments))
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
Ok((route_segments, parsed_query))
|
||||
Ok((route_segments, query, hash))
|
||||
}
|
||||
|
||||
pub(crate) fn create_error_type(
|
||||
|
||||
@@ -76,7 +76,6 @@ impl RouterContext {
|
||||
mark_dirty: Arc<dyn Fn(ScopeId) + Sync + Send>,
|
||||
) -> Self
|
||||
where
|
||||
R: Clone,
|
||||
<R as std::str::FromStr>::Err: std::fmt::Display,
|
||||
{
|
||||
let subscriber_update = mark_dirty.clone();
|
||||
|
||||
@@ -128,7 +128,8 @@ where
|
||||
fn route_from_location(&self) -> R {
|
||||
let location = self.window.location();
|
||||
let path = location.pathname().unwrap_or_else(|_| "/".into())
|
||||
+ &location.search().unwrap_or("".into());
|
||||
+ &location.search().unwrap_or("".into())
|
||||
+ &location.hash().unwrap_or("".into());
|
||||
let path = match self.prefix {
|
||||
None => path,
|
||||
Some(ref prefix) => {
|
||||
|
||||
@@ -36,7 +36,7 @@ pub trait FromQuery {
|
||||
|
||||
impl<T: for<'a> From<&'a str>> FromQuery for T {
|
||||
fn from_query(query: &str) -> Self {
|
||||
T::from(&*urlencoding::decode(query).expect("Failed to decode url encoding"))
|
||||
T::from(query)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,14 +58,7 @@ where
|
||||
type Err = <T as FromStr>::Err;
|
||||
|
||||
fn from_query_argument(argument: &str) -> Result<Self, Self::Err> {
|
||||
let result = match urlencoding::decode(argument) {
|
||||
Ok(argument) => T::from_str(&argument),
|
||||
Err(err) => {
|
||||
tracing::error!("Failed to decode url encoding: {}", err);
|
||||
T::from_str(argument)
|
||||
}
|
||||
};
|
||||
match result {
|
||||
match T::from_str(argument) {
|
||||
Ok(result) => Ok(result),
|
||||
Err(err) => {
|
||||
tracing::error!("Failed to parse query argument: {}", err);
|
||||
@@ -75,6 +68,82 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// Something that can be created from an entire hash fragment.
|
||||
///
|
||||
/// This trait needs to be implemented if you want to turn a hash fragment into a struct.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use dioxus::prelude::*;
|
||||
///
|
||||
/// #[derive(Routable, Clone)]
|
||||
/// #[rustfmt::skip]
|
||||
/// enum Route {
|
||||
/// // State is stored in the url hash
|
||||
/// #[route("/#:url_hash")]
|
||||
/// Home {
|
||||
/// url_hash: State,
|
||||
/// },
|
||||
/// }
|
||||
///
|
||||
/// #[component]
|
||||
/// fn Home(url_hash: State) -> Element {
|
||||
/// todo!()
|
||||
/// }
|
||||
///
|
||||
///
|
||||
/// #[derive(Clone, PartialEq, Default)]
|
||||
/// struct State {
|
||||
/// count: usize,
|
||||
/// other_count: usize
|
||||
/// }
|
||||
///
|
||||
/// // The hash segment will be displayed as a string (this will be url encoded automatically)
|
||||
/// impl std::fmt::Display for State {
|
||||
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
/// write!(f, "{}-{}", self.count, self.other_count)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // We need to parse the hash fragment into a struct from the string (this will be url decoded automatically)
|
||||
/// impl FromHashFragment for State {
|
||||
/// fn from_hash_fragment(hash: &str) -> Self {
|
||||
/// let Some((first, second)) = hash.split_once('-') else {
|
||||
/// // URL fragment parsing shouldn't fail. You can return a default value if you want
|
||||
/// return Default::default();
|
||||
/// };
|
||||
///
|
||||
/// let first = first.parse().unwrap();
|
||||
/// let second = second.parse().unwrap();
|
||||
///
|
||||
/// State {
|
||||
/// count: first,
|
||||
/// other_count: second,
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
pub trait FromHashFragment {
|
||||
/// Create an instance of `Self` from a hash fragment.
|
||||
fn from_hash_fragment(hash: &str) -> Self;
|
||||
}
|
||||
|
||||
impl<T> FromHashFragment for T
|
||||
where
|
||||
T: FromStr + Default,
|
||||
T::Err: std::fmt::Display,
|
||||
{
|
||||
fn from_hash_fragment(hash: &str) -> Self {
|
||||
match T::from_str(hash) {
|
||||
Ok(value) => value,
|
||||
Err(err) => {
|
||||
tracing::error!("Failed to parse hash fragment: {}", err);
|
||||
Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Something that can be created from a route segment.
|
||||
pub trait FromRouteSegment: Sized {
|
||||
/// The error that can occur when parsing a route segment.
|
||||
@@ -91,13 +160,7 @@ where
|
||||
type Err = <T as FromStr>::Err;
|
||||
|
||||
fn from_route_segment(route: &str) -> Result<Self, Self::Err> {
|
||||
match urlencoding::decode(route) {
|
||||
Ok(segment) => T::from_str(&segment),
|
||||
Err(err) => {
|
||||
tracing::error!("Failed to decode url encoding: {}", err);
|
||||
T::from_str(route)
|
||||
}
|
||||
}
|
||||
T::from_str(route)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,7 +172,7 @@ fn full_circle() {
|
||||
|
||||
/// Something that can be converted to route segments.
|
||||
pub trait ToRouteSegments {
|
||||
/// Display the route segments.
|
||||
/// Display the route segments. You must url encode the segments.
|
||||
fn display_route_segments(self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
|
||||
}
|
||||
|
||||
@@ -121,13 +184,8 @@ where
|
||||
for segment in self {
|
||||
write!(f, "/")?;
|
||||
let segment = segment.to_string();
|
||||
match urlencoding::decode(&segment) {
|
||||
Ok(segment) => write!(f, "{}", segment)?,
|
||||
Err(err) => {
|
||||
tracing::error!("Failed to decode url encoding: {}", err);
|
||||
write!(f, "{}", segment)?
|
||||
}
|
||||
}
|
||||
let encoded = urlencoding::encode(&segment);
|
||||
write!(f, "{}", encoded)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
use crate::contexts::router::RoutingCallback;
|
||||
use crate::history::HistoryProvider;
|
||||
use crate::prelude::*;
|
||||
use crate::routable::Routable;
|
||||
use dioxus_lib::prelude::*;
|
||||
use std::sync::Arc;
|
||||
|
||||
|
||||
Reference in new issue
Block a user