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
@@ -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(
|
||||
|
||||
Reference in new issue
Block a user