lib.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. extern crate proc_macro;
  2. use layout::Layout;
  3. use nest::{Nest, NestId};
  4. use proc_macro::TokenStream;
  5. use quote::{__private::Span, format_ident, quote, ToTokens};
  6. use redirect::Redirect;
  7. use route::{Route, RouteType};
  8. use segment::RouteSegment;
  9. use syn::{parse::ParseStream, parse_macro_input, Ident, Token, Type};
  10. use proc_macro2::TokenStream as TokenStream2;
  11. use crate::{layout::LayoutId, route_tree::RouteTree};
  12. mod layout;
  13. mod nest;
  14. mod query;
  15. mod redirect;
  16. mod route;
  17. mod route_tree;
  18. mod segment;
  19. /// Derives the Routable trait for an enum of routes
  20. ///
  21. /// Each variant must:
  22. /// 1. Be struct-like with {}'s
  23. /// 2. Contain all of the dynamic parameters of the current and nested routes
  24. /// 3. Have a #[route("route")] attribute
  25. ///
  26. /// Route Segments:
  27. /// 1. Static Segments: "/static"
  28. /// 2. Dynamic Segments: "/:dynamic" (where dynamic has a type that is FromStr in all child Variants)
  29. /// 3. Catch all Segments: "/:...segments" (where segments has a type that is FromSegments in all child Variants)
  30. /// 4. Query Segments: "/?:query" (where query has a type that is FromQuery in all child Variants)
  31. ///
  32. /// Routes are matched:
  33. /// 1. By there specificity this order: Query Routes ("/?:query"), Static Routes ("/route"), Dynamic Routes ("/:route"), Catch All Routes ("/:...route")
  34. /// 2. By the order they are defined in the enum
  35. ///
  36. /// All features:
  37. /// ```rust, skip
  38. /// #[rustfmt::skip]
  39. /// #[derive(Clone, Debug, PartialEq, Routable)]
  40. /// enum Route {
  41. /// // Define routes with the route macro. If the name of the component is not the same as the variant, you can specify it as the second parameter and the props type as the third
  42. /// #[route("/", IndexComponent, ComponentProps)]
  43. /// Index {},
  44. /// // Nests with parameters have types taken from child routes
  45. /// // Everything inside the nest has the added parameter `user_id: usize`
  46. /// #[nest("/user/:user_id")]
  47. /// // All children of layouts will be rendered inside the Outlet in the layout component
  48. /// // Creates a Layout UserFrame that has the parameter `user_id: usize`
  49. /// #[layout(UserFrame)]
  50. /// // If there is a component with the name Route1 and props with the name Route1Props, you do not need to pass in the component and type
  51. /// #[route("/:dynamic?:query")]
  52. /// Route1 {
  53. /// // The type is taken from the first instance of the dynamic parameter
  54. /// user_id: usize,
  55. /// dynamic: usize,
  56. /// query: String,
  57. /// extra: String,
  58. /// },
  59. /// #[route("/hello_world")]
  60. /// // You can opt out of the layout by using the `!` prefix
  61. /// #[layout(!UserFrame)]
  62. /// Route2 { user_id: usize },
  63. /// // End layouts with #[end_layout]
  64. /// #[end_layout]
  65. /// // End nests with #[end_nest]
  66. /// #[end_nest]
  67. /// // Redirects take a path and a function that takes the parameters from the path and returns a new route
  68. /// #[redirect("/:id/user", |id: usize| Route::Route3 { dynamic: id.to_string()})]
  69. /// #[route("/:dynamic")]
  70. /// Route3 { dynamic: String },
  71. /// #[child]
  72. /// NestedRoute(NestedRoute),
  73. /// }
  74. /// ```
  75. ///
  76. /// # `#[route("path", component, props)]`
  77. ///
  78. /// The `#[route]` attribute is used to define a route. It takes up to 3 parameters:
  79. /// - `path`: The path to the enum variant (relative to the parent nest)
  80. /// - (optional) `component`: The component to render when the route is matched. If not specified, the name of the variant is used
  81. /// - (optional) `props`: The props type for the component. If not specified, the name of the variant with `Props` appended is used
  82. ///
  83. /// Routes are the most basic attribute. They allow you to define a route and the component to render when the route is matched. The component must take all dynamic parameters of the route and all parent nests.
  84. /// The next variant will be tied to the component. If you link to that variant, the component will be rendered.
  85. ///
  86. /// ```rust, skip
  87. /// #[derive(Clone, Debug, PartialEq, Routable)]
  88. /// enum Route {
  89. /// // Define routes that renders the IndexComponent that takes the IndexProps
  90. /// // The Index component will be rendered when the route is matched (e.g. when the user navigates to /)
  91. /// #[route("/", Index, IndexProps)]
  92. /// Index {},
  93. /// }
  94. /// ```
  95. ///
  96. /// # `#[redirect("path", function)]`
  97. ///
  98. /// The `#[redirect]` attribute is used to define a redirect. It takes 2 parameters:
  99. /// - `path`: The path to the enum variant (relative to the parent nest)
  100. /// - `function`: A function that takes the parameters from the path and returns a new route
  101. ///
  102. /// ```rust, skip
  103. /// #[derive(Clone, Debug, PartialEq, Routable)]
  104. /// enum Route {
  105. /// // Redirects the /:id route to the Index route
  106. /// #[redirect("/:id", |_: usize| Route::Index {})]
  107. /// #[route("/", Index, IndexProps)]
  108. /// Index {},
  109. /// }
  110. /// ```
  111. ///
  112. /// Redirects allow you to redirect a route to another route. The function must take all dynamic parameters of the route and all parent nests.
  113. ///
  114. /// # `#[nest("path")]`
  115. ///
  116. /// The `#[nest]` attribute is used to define a nest. It takes 1 parameter:
  117. /// - `path`: The path to the nest (relative to the parent nest)
  118. ///
  119. /// Nests effect all nests, routes and redirects defined until the next `#[end_nest]` attribute. All children of nests are relative to the nest route and must include all dynamic parameters of the nest.
  120. ///
  121. /// ```rust, skip
  122. /// #[derive(Clone, Debug, PartialEq, Routable)]
  123. /// enum Route {
  124. /// // Nests all child routes in the /blog route
  125. /// #[nest("/blog")]
  126. /// // This is at /blog/:id
  127. /// #[redirect("/:id", |_: usize| Route::Index {})]
  128. /// // This is at /blog
  129. /// #[route("/", Index, IndexProps)]
  130. /// Index {},
  131. /// }
  132. /// ```
  133. ///
  134. /// # `#[end_nest]`
  135. ///
  136. /// The `#[end_nest]` attribute is used to end a nest. It takes no parameters.
  137. ///
  138. /// ```rust, skip
  139. /// #[derive(Clone, Debug, PartialEq, Routable)]
  140. /// enum Route {
  141. /// #[nest("/blog")]
  142. /// // This is at /blog/:id
  143. /// #[redirect("/:id", |_: usize| Route::Index {})]
  144. /// // This is at /blog
  145. /// #[route("/", Index, IndexProps)]
  146. /// Index {},
  147. /// // Ends the nest
  148. /// #[end_nest]
  149. /// // This is at /
  150. /// #[route("/")]
  151. /// Home {},
  152. /// }
  153. /// ```
  154. ///
  155. /// # `#[layout(component)]`
  156. ///
  157. /// The `#[layout]` attribute is used to define a layout. It takes 2 parameters:
  158. /// - `component`: The component to render when the route is matched. If not specified, the name of the variant is used
  159. /// - (optional) `props`: The props type for the component. If not specified, the name of the variant with `Props` appended is used
  160. ///
  161. /// The layout component allows you to wrap all children of the layout in a component. The child routes are rendered in the Outlet of the layout component. The layout component must take all dynamic parameters of the nests it is nested in.
  162. ///
  163. /// ```rust, skip
  164. /// #[derive(Clone, Debug, PartialEq, Routable)]
  165. /// enum Route {
  166. /// #[layout(BlogFrame)]
  167. /// #[redirect("/:id", |_: usize| Route::Index {})]
  168. /// // Index will be rendered in the Outlet of the BlogFrame component
  169. /// #[route("/", Index, IndexProps)]
  170. /// Index {},
  171. /// }
  172. /// ```
  173. ///
  174. /// # `#[end_layout]`
  175. ///
  176. /// The `#[end_layout]` attribute is used to end a layout. It takes no parameters.
  177. ///
  178. /// ```rust, skip
  179. /// #[derive(Clone, Debug, PartialEq, Routable)]
  180. /// enum Route {
  181. /// #[layout(BlogFrame)]
  182. /// #[redirect("/:id", |_: usize| Route::Index {})]
  183. /// // Index will be rendered in the Outlet of the BlogFrame component
  184. /// #[route("/", Index, IndexProps)]
  185. /// Index {},
  186. /// // Ends the layout
  187. /// #[end_layout]
  188. /// // This will be rendered standalone
  189. /// #[route("/")]
  190. /// Home {},
  191. /// }
  192. /// ```
  193. #[proc_macro_derive(
  194. Routable,
  195. attributes(route, nest, end_nest, layout, end_layout, redirect, child)
  196. )]
  197. pub fn routable(input: TokenStream) -> TokenStream {
  198. let routes_enum = parse_macro_input!(input as syn::ItemEnum);
  199. let route_enum = match RouteEnum::parse(routes_enum) {
  200. Ok(route_enum) => route_enum,
  201. Err(err) => return err.to_compile_error().into(),
  202. };
  203. let error_type = route_enum.error_type();
  204. let parse_impl = route_enum.parse_impl();
  205. let display_impl = route_enum.impl_display();
  206. let routable_impl = route_enum.routable_impl();
  207. let name = &route_enum.name;
  208. let vis = &route_enum.vis;
  209. quote! {
  210. #vis fn Outlet(cx: dioxus::prelude::Scope) -> dioxus::prelude::Element {
  211. dioxus_router::prelude::GenericOutlet::<#name>(cx)
  212. }
  213. #vis fn Router(cx: dioxus::prelude::Scope<dioxus_router::prelude::GenericRouterProps<#name>>) -> dioxus::prelude::Element {
  214. dioxus_router::prelude::GenericRouter(cx)
  215. }
  216. #vis fn Link<'a>(cx: dioxus::prelude::Scope<'a, dioxus_router::prelude::GenericLinkProps<'a, #name>>) -> dioxus::prelude::Element<'a> {
  217. dioxus_router::prelude::GenericLink(cx)
  218. }
  219. #vis fn GoBackButton<'a>(cx: dioxus::prelude::Scope<'a, dioxus_router::prelude::GenericHistoryButtonProps<'a>>) -> dioxus::prelude::Element<'a> {
  220. dioxus_router::prelude::GenericGoBackButton::<#name>(cx)
  221. }
  222. #vis fn GoForwardButton<'a>(cx: dioxus::prelude::Scope<'a, dioxus_router::prelude::GenericHistoryButtonProps<'a>>) -> dioxus::prelude::Element<'a> {
  223. dioxus_router::prelude::GenericGoForwardButton::<#name>(cx)
  224. }
  225. #vis fn use_route(cx: &dioxus::prelude::ScopeState) -> Option<#name> {
  226. dioxus_router::prelude::use_generic_route(cx)
  227. }
  228. #vis fn use_navigator(cx: &dioxus::prelude::ScopeState) -> &dioxus_router::prelude::GenericNavigator<#name> {
  229. dioxus_router::prelude::use_generic_navigator(cx)
  230. }
  231. #error_type
  232. #display_impl
  233. #routable_impl
  234. #parse_impl
  235. }
  236. .into()
  237. }
  238. struct RouteEnum {
  239. vis: syn::Visibility,
  240. name: Ident,
  241. redirects: Vec<Redirect>,
  242. routes: Vec<Route>,
  243. nests: Vec<Nest>,
  244. layouts: Vec<Layout>,
  245. site_map: Vec<SiteMapSegment>,
  246. }
  247. impl RouteEnum {
  248. fn parse(data: syn::ItemEnum) -> syn::Result<Self> {
  249. let name = &data.ident;
  250. let vis = &data.vis;
  251. let mut site_map = Vec::new();
  252. let mut site_map_stack: Vec<Vec<SiteMapSegment>> = Vec::new();
  253. let mut routes = Vec::new();
  254. let mut redirects = Vec::new();
  255. let mut layouts: Vec<Layout> = Vec::new();
  256. let mut layout_stack = Vec::new();
  257. let mut nests = Vec::new();
  258. let mut nest_stack = Vec::new();
  259. for variant in &data.variants {
  260. let mut excluded = Vec::new();
  261. // Apply the any nesting attributes in order
  262. for attr in &variant.attrs {
  263. if attr.path.is_ident("nest") {
  264. let mut children_routes = Vec::new();
  265. {
  266. // add all of the variants of the enum to the children_routes until we hit an end_nest
  267. let mut level = 0;
  268. 'o: for variant in &data.variants {
  269. children_routes.push(variant.fields.clone());
  270. for attr in &variant.attrs {
  271. if attr.path.is_ident("nest") {
  272. level += 1;
  273. } else if attr.path.is_ident("end_nest") {
  274. level -= 1;
  275. if level < 0 {
  276. break 'o;
  277. }
  278. }
  279. }
  280. }
  281. }
  282. let nest_index = nests.len();
  283. let parser = |input: ParseStream| {
  284. Nest::parse(
  285. input,
  286. children_routes
  287. .iter()
  288. .filter_map(|f: &syn::Fields| match f {
  289. syn::Fields::Named(fields) => Some(fields.clone()),
  290. _ => None,
  291. })
  292. .collect(),
  293. nest_index,
  294. )
  295. };
  296. let nest = attr.parse_args_with(parser)?;
  297. // add the current segment to the site map stack
  298. let segments: Vec<_> = nest
  299. .segments
  300. .iter()
  301. .map(|seg| {
  302. let segment_type = seg.into();
  303. SiteMapSegment {
  304. segment_type,
  305. children: Vec::new(),
  306. }
  307. })
  308. .collect();
  309. if !segments.is_empty() {
  310. site_map_stack.push(segments);
  311. }
  312. nests.push(nest);
  313. nest_stack.push(NestId(nest_index));
  314. } else if attr.path.is_ident("end_nest") {
  315. nest_stack.pop();
  316. // pop the current nest segment off the stack and add it to the parent or the site map
  317. if let Some(segment) = site_map_stack.pop() {
  318. let children = site_map_stack
  319. .last_mut()
  320. .map(|seg| &mut seg.last_mut().unwrap().children)
  321. .unwrap_or(&mut site_map);
  322. // Turn the list of segments in the segments stack into a tree
  323. let mut iter = segment.into_iter().rev();
  324. let mut current = iter.next().unwrap();
  325. for mut segment in iter {
  326. segment.children.push(current);
  327. current = segment;
  328. }
  329. children.push(current);
  330. }
  331. } else if attr.path.is_ident("layout") {
  332. let parser = |input: ParseStream| {
  333. let bang: Option<Token![!]> = input.parse().ok();
  334. let exclude = bang.is_some();
  335. Ok((
  336. exclude,
  337. Layout::parse(input, nest_stack.iter().rev().cloned().collect())?,
  338. ))
  339. };
  340. let (exclude, layout): (bool, Layout) = attr.parse_args_with(parser)?;
  341. if exclude {
  342. let Some(layout_index) =
  343. layouts.iter().position(|l| l.comp == layout.comp) else {
  344. return Err(syn::Error::new(
  345. Span::call_site(),
  346. "Attempted to exclude a layout that does not exist",
  347. ));
  348. };
  349. excluded.push(LayoutId(layout_index));
  350. } else {
  351. let layout_index = layouts.len();
  352. layouts.push(layout);
  353. layout_stack.push(LayoutId(layout_index));
  354. }
  355. } else if attr.path.is_ident("end_layout") {
  356. layout_stack.pop();
  357. } else if attr.path.is_ident("redirect") {
  358. let parser = |input: ParseStream| {
  359. Redirect::parse(
  360. input,
  361. nest_stack.iter().rev().cloned().collect(),
  362. redirects.len(),
  363. )
  364. };
  365. let redirect = attr.parse_args_with(parser)?;
  366. redirects.push(redirect);
  367. }
  368. }
  369. let mut active_nests = nest_stack.clone();
  370. active_nests.reverse();
  371. let mut active_layouts = layout_stack.clone();
  372. active_layouts.retain(|&id| !excluded.contains(&id));
  373. let route = Route::parse(active_nests, active_layouts, variant.clone())?;
  374. // add the route to the site map
  375. let mut segment = SiteMapSegment::new(&route.segments);
  376. if let RouteType::Child(child) = &route.ty {
  377. let new_segment = SiteMapSegment {
  378. segment_type: SegmentType::Child(child.ty.clone()),
  379. children: Vec::new(),
  380. };
  381. match &mut segment {
  382. Some(segment) => {
  383. fn set_last_child_to(
  384. segment: &mut SiteMapSegment,
  385. new_segment: SiteMapSegment,
  386. ) {
  387. if let Some(last) = segment.children.last_mut() {
  388. set_last_child_to(last, new_segment);
  389. } else {
  390. segment.children = vec![new_segment];
  391. }
  392. }
  393. set_last_child_to(segment, new_segment);
  394. }
  395. None => {
  396. segment = Some(new_segment);
  397. }
  398. }
  399. }
  400. if let Some(segment) = segment {
  401. let parent = site_map_stack.last_mut();
  402. let children = match parent {
  403. Some(parent) => &mut parent.last_mut().unwrap().children,
  404. None => &mut site_map,
  405. };
  406. children.push(segment);
  407. }
  408. routes.push(route);
  409. }
  410. let myself = Self {
  411. vis: vis.clone(),
  412. name: name.clone(),
  413. routes,
  414. redirects,
  415. nests,
  416. layouts,
  417. site_map,
  418. };
  419. Ok(myself)
  420. }
  421. fn impl_display(&self) -> TokenStream2 {
  422. let mut display_match = Vec::new();
  423. for route in &self.routes {
  424. display_match.push(route.display_match(&self.nests));
  425. }
  426. let name = &self.name;
  427. quote! {
  428. impl std::fmt::Display for #name {
  429. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  430. #[allow(unused)]
  431. match self {
  432. #(#display_match)*
  433. }
  434. Ok(())
  435. }
  436. }
  437. }
  438. }
  439. fn parse_impl(&self) -> TokenStream2 {
  440. let tree = RouteTree::new(&self.routes, &self.nests, &self.redirects);
  441. let name = &self.name;
  442. let error_name = format_ident!("{}MatchError", self.name);
  443. let tokens = tree.roots.iter().map(|&id| {
  444. let route = tree.get(id).unwrap();
  445. route.to_tokens(&self.nests, &tree, self.name.clone(), error_name.clone())
  446. });
  447. quote! {
  448. impl<'a> core::convert::TryFrom<&'a str> for #name {
  449. type Error = <Self as std::str::FromStr>::Err;
  450. fn try_from(s: &'a str) -> Result<Self, Self::Error> {
  451. s.parse()
  452. }
  453. }
  454. impl std::str::FromStr for #name {
  455. type Err = dioxus_router::routable::RouteParseError<#error_name>;
  456. fn from_str(s: &str) -> Result<Self, Self::Err> {
  457. let route = s;
  458. let (route, query) = route.split_once('?').unwrap_or((route, ""));
  459. let mut segments = route.split('/');
  460. // skip the first empty segment
  461. if s.starts_with('/') {
  462. segments.next();
  463. }
  464. let mut errors = Vec::new();
  465. #(#tokens)*
  466. Err(dioxus_router::routable::RouteParseError {
  467. attempted_routes: errors,
  468. })
  469. }
  470. }
  471. }
  472. }
  473. fn error_name(&self) -> Ident {
  474. Ident::new(&(self.name.to_string() + "MatchError"), Span::call_site())
  475. }
  476. fn error_type(&self) -> TokenStream2 {
  477. let match_error_name = self.error_name();
  478. let mut type_defs = Vec::new();
  479. let mut error_variants = Vec::new();
  480. let mut display_match = Vec::new();
  481. for route in &self.routes {
  482. let route_name = &route.route_name;
  483. let error_name = route.error_ident();
  484. let route_str = &route.route;
  485. error_variants.push(quote! { #route_name(#error_name) });
  486. display_match.push(quote! { Self::#route_name(err) => write!(f, "Route '{}' ('{}') did not match:\n{}", stringify!(#route_name), #route_str, err)? });
  487. type_defs.push(route.error_type());
  488. }
  489. for nest in &self.nests {
  490. let error_variant = nest.error_variant();
  491. let error_name = nest.error_ident();
  492. let route_str = &nest.route;
  493. error_variants.push(quote! { #error_variant(#error_name) });
  494. display_match.push(quote! { Self::#error_variant(err) => write!(f, "Nest '{}' ('{}') did not match:\n{}", stringify!(#error_name), #route_str, err)? });
  495. type_defs.push(nest.error_type());
  496. }
  497. for redirect in &self.redirects {
  498. let error_variant = redirect.error_variant();
  499. let error_name = redirect.error_ident();
  500. let route_str = &redirect.route;
  501. error_variants.push(quote! { #error_variant(#error_name) });
  502. display_match.push(quote! { Self::#error_variant(err) => write!(f, "Redirect '{}' ('{}') did not match:\n{}", stringify!(#error_name), #route_str, err)? });
  503. type_defs.push(redirect.error_type());
  504. }
  505. quote! {
  506. #(#type_defs)*
  507. #[allow(non_camel_case_types)]
  508. #[derive(Debug, PartialEq)]
  509. pub enum #match_error_name {
  510. #(#error_variants),*
  511. }
  512. impl std::fmt::Display for #match_error_name {
  513. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  514. match self {
  515. #(#display_match),*
  516. }
  517. Ok(())
  518. }
  519. }
  520. }
  521. }
  522. fn routable_impl(&self) -> TokenStream2 {
  523. let name = &self.name;
  524. let site_map = &self.site_map;
  525. let mut matches = Vec::new();
  526. // Collect all routes matches
  527. for route in &self.routes {
  528. matches.push(route.routable_match(&self.layouts, &self.nests));
  529. }
  530. quote! {
  531. impl dioxus_router::routable::Routable for #name where Self: Clone {
  532. const SITE_MAP: &'static [dioxus_router::routable::SiteMapSegment] = &[
  533. #(#site_map,)*
  534. ];
  535. fn render<'a>(&self, cx: &'a dioxus::prelude::ScopeState, level: usize) -> dioxus::prelude::Element<'a> {
  536. let myself = self.clone();
  537. match (level, myself) {
  538. #(#matches)*
  539. _ => None
  540. }
  541. }
  542. }
  543. }
  544. }
  545. }
  546. struct SiteMapSegment {
  547. pub segment_type: SegmentType,
  548. pub children: Vec<SiteMapSegment>,
  549. }
  550. impl SiteMapSegment {
  551. fn new(segments: &[RouteSegment]) -> Option<Self> {
  552. let mut current = None;
  553. // walk backwards through the new segments, adding children as we go
  554. for segment in segments.iter().rev() {
  555. let segment_type = segment.into();
  556. let mut segment = SiteMapSegment {
  557. segment_type,
  558. children: Vec::new(),
  559. };
  560. // if we have a current segment, add it as a child
  561. if let Some(current) = current.take() {
  562. segment.children.push(current)
  563. }
  564. current = Some(segment);
  565. }
  566. current
  567. }
  568. }
  569. impl ToTokens for SiteMapSegment {
  570. fn to_tokens(&self, tokens: &mut TokenStream2) {
  571. let segment_type = &self.segment_type;
  572. let children = if let SegmentType::Child(ty) = &self.segment_type {
  573. quote! { #ty::SITE_MAP }
  574. } else {
  575. let children = self
  576. .children
  577. .iter()
  578. .map(|child| child.to_token_stream())
  579. .collect::<Vec<_>>();
  580. quote! {
  581. &[
  582. #(#children,)*
  583. ]
  584. }
  585. };
  586. tokens.extend(quote! {
  587. dioxus_router::routable::SiteMapSegment {
  588. segment_type: #segment_type,
  589. children: #children,
  590. }
  591. });
  592. }
  593. }
  594. enum SegmentType {
  595. Static(String),
  596. Dynamic(String),
  597. CatchAll(String),
  598. Child(Type),
  599. }
  600. impl ToTokens for SegmentType {
  601. fn to_tokens(&self, tokens: &mut TokenStream2) {
  602. match self {
  603. SegmentType::Static(s) => {
  604. tokens.extend(quote! { dioxus_router::routable::SegmentType::Static(#s) })
  605. }
  606. SegmentType::Dynamic(s) => {
  607. tokens.extend(quote! { dioxus_router::routable::SegmentType::Dynamic(#s) })
  608. }
  609. SegmentType::CatchAll(s) => {
  610. tokens.extend(quote! { dioxus_router::routable::SegmentType::CatchAll(#s) })
  611. }
  612. SegmentType::Child(_) => {
  613. tokens.extend(quote! { dioxus_router::routable::SegmentType::Child })
  614. }
  615. }
  616. }
  617. }
  618. impl<'a> From<&'a RouteSegment> for SegmentType {
  619. fn from(value: &'a RouteSegment) -> Self {
  620. match value {
  621. segment::RouteSegment::Static(s) => SegmentType::Static(s.to_string()),
  622. segment::RouteSegment::Dynamic(s, _) => SegmentType::Dynamic(s.to_string()),
  623. segment::RouteSegment::CatchAll(s, _) => SegmentType::CatchAll(s.to_string()),
  624. }
  625. }
  626. }