yew_router/routable.rs
1use std::collections::HashMap;
2
3pub use yew_router_macro::Routable;
4
5/// Marks an `enum` as routable.
6///
7/// # Implementation
8///
9/// Use derive macro to implement it. Although it *is* possible to implement it manually,
10/// it is discouraged.
11///
12/// # Usage
13///
14/// The functions exposed by this trait are **not** supposed to be consumed directly. Instead use
15/// the functions exposed at the [crate's root][crate] to perform operations with the router.
16pub trait Routable: Clone + PartialEq {
17 /// Converts path to an instance of the routes enum.
18 fn from_path(path: &str, params: &HashMap<&str, &str>) -> Option<Self>;
19
20 /// Converts the route to a string that can passed to the history API.
21 fn to_path(&self) -> String;
22
23 /// Lists all the available routes
24 fn routes() -> Vec<&'static str>;
25
26 /// The route to redirect to on 404
27 fn not_found_route() -> Option<Self>;
28
29 /// Match a route based on the path
30 fn recognize(pathname: &str) -> Option<Self>;
31}
32
33/// A special route that accepts any route.
34///
35/// This can be used with [`History`](gloo::history::History) and
36/// [`Location`](gloo::history::Location) when the type of [`Routable`] is unknown.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct AnyRoute {
39 path: String,
40}
41
42impl Routable for AnyRoute {
43 fn from_path(path: &str, params: &HashMap<&str, &str>) -> Option<Self> {
44 // No params allowed.
45 if params.is_empty() {
46 Some(Self {
47 path: path.to_string(),
48 })
49 } else {
50 None
51 }
52 }
53
54 fn to_path(&self) -> String {
55 self.path.to_string()
56 }
57
58 fn routes() -> Vec<&'static str> {
59 vec!["/*path"]
60 }
61
62 fn not_found_route() -> Option<Self> {
63 Some(Self {
64 path: "/404".to_string(),
65 })
66 }
67
68 fn recognize(pathname: &str) -> Option<Self> {
69 Some(Self {
70 path: pathname.to_string(),
71 })
72 }
73}
74
75impl AnyRoute {
76 pub fn new<S: Into<String>>(pathname: S) -> Self {
77 Self {
78 path: pathname.into(),
79 }
80 }
81}