Skip to main content

egui_kit/
href.rs

1//! [`href`]: building urls from route patterns.
2
3use core::fmt;
4
5use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};
6use serde::Serialize;
7
8use crate::router::Pattern;
9
10/// What a fragment can't contain unencoded, as in the URL standard.
11const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`');
12
13/// Builds a url from a route pattern, percent-encoding the parameters, so that the router
14/// matches it and decodes the same values.
15///
16/// ```
17/// use egui_kit::href;
18/// use serde::Serialize;
19///
20/// #[derive(Serialize)]
21/// struct BlogQuery {
22///     tag: Option<String>,
23///     page: u32,
24/// }
25///
26/// let url = href("/blog/{slug}").param("slug", "hello world");
27/// assert_eq!(url.to_string(), "/blog/hello%20world");
28///
29/// let query = BlogQuery { tag: Some("egui".into()), page: 2 };
30/// let url = href("/{?lang}/blog").query(&query).fragment("top");
31/// assert_eq!(url.to_string(), "/blog?tag=egui&page=2#top");
32/// ```
33///
34/// [`Nav::goto`](crate::extract::Nav::goto) and friends take it directly,
35/// [`Nav::link`](crate::extract::Nav::link) as `&href(..).to_string()`.
36///
37/// Panics on an invalid pattern, like [`Router::page`](crate::Router::page). Turning it into a
38/// url panics if a required parameter is missing.
39pub fn href(pattern: &str) -> Href {
40    Href {
41        pattern: Pattern::parse(pattern),
42        params: Vec::new(),
43        query: None,
44        fragment: None,
45    }
46}
47
48/// A url being built from a route pattern, see [`href`]. Turned into a url with
49/// [`Display`](fmt::Display) or [`String::from`].
50#[derive(Debug, Clone)]
51#[must_use]
52pub struct Href {
53    pattern: Pattern,
54    params: Vec<(String, String)>,
55    query: Option<String>,
56    fragment: Option<String>,
57}
58
59impl Href {
60    /// Sets the parameter `name`: `{name}`, `{name=matcher}`, `{?name}` (left out of the url
61    /// unless set) or `{*name}` (whose value may contain slashes).
62    ///
63    /// Panics if the pattern has no such parameter.
64    pub fn param(mut self, name: &str, value: impl fmt::Display) -> Self {
65        assert!(
66            self.pattern.has_param(name),
67            "`{}` has no parameter `{name}`",
68            self.pattern.as_str()
69        );
70        let value = value.to_string();
71        match self.params.iter_mut().find(|(param, _)| param == name) {
72            Some((_, old)) => *old = value,
73            None => self.params.push((name.to_owned(), value)),
74        }
75        self
76    }
77
78    /// Sets the query from a flat struct or a sequence of pairs, with `serde_urlencoded` (the
79    /// format [`Query`](crate::extract::Query) reads). `None` fields are left out, and an empty
80    /// query adds no `?`. Replaces an earlier query.
81    ///
82    /// Panics if `query` can't be serialized, e.g. a struct with nested structs.
83    pub fn query(mut self, query: &impl Serialize) -> Self {
84        let query = serde_urlencoded::to_string(query)
85            .unwrap_or_else(|error| panic!("href: can't serialize the query: {error}"));
86        self.query = Some(query).filter(|query| !query.is_empty());
87        self
88    }
89
90    /// Sets the `#fragment` (without the `#`). Spaces, quotes, `<`, `>` and backticks are
91    /// percent-encoded.
92    pub fn fragment(mut self, fragment: &str) -> Self {
93        self.fragment = Some(utf8_percent_encode(fragment, FRAGMENT).to_string());
94        self
95    }
96}
97
98impl fmt::Display for Href {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.write_str(&self.pattern.fill(&self.params))?;
101        if let Some(query) = &self.query {
102            write!(f, "?{query}")?;
103        }
104        if let Some(fragment) = &self.fragment {
105            write!(f, "#{fragment}")?;
106        }
107        Ok(())
108    }
109}
110
111impl From<Href> for String {
112    fn from(href: Href) -> Self {
113        href.to_string()
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use serde::Serialize;
120
121    use super::href;
122
123    #[derive(Serialize)]
124    struct Filter {
125        tag: Option<&'static str>,
126        q: &'static str,
127    }
128
129    #[test]
130    fn params() {
131        let url = href("/users/{id=int}/{?tab}").param("id", 7);
132        assert_eq!(url.to_string(), "/users/7");
133        let url = url.param("tab", "posts").param("id", 8);
134        assert_eq!(String::from(url), "/users/8/posts");
135        let url = href("/files/{*path}").param("path", "a b/c?");
136        assert_eq!(url.to_string(), "/files/a%20b/c%3F");
137    }
138
139    #[test]
140    fn query_and_fragment() {
141        let filter = Filter {
142            tag: None,
143            q: "a&b c",
144        };
145        let url = href("/blog").query(&filter).fragment("top");
146        assert_eq!(url.to_string(), "/blog?q=a%26b+c#top");
147        let url = href("/blog").query(&[("tag", "x")]).query(&());
148        assert_eq!(url.to_string(), "/blog");
149        assert_eq!(href("/").fragment("a b").to_string(), "/#a%20b");
150    }
151
152    #[test]
153    #[should_panic(expected = "`/blog/{slug}` is missing the parameter `slug`")]
154    fn missing_param() {
155        let _ = href("/blog/{slug}").to_string();
156    }
157
158    #[test]
159    #[should_panic(expected = "`/blog/{slug}` has no parameter `id`")]
160    fn unknown_param() {
161        let _ = href("/blog/{slug}").param("id", 1);
162    }
163
164    #[test]
165    #[should_panic(expected = "href: can't serialize the query")]
166    fn nested_query() {
167        #[derive(Serialize)]
168        struct Outer {
169            inner: Filter,
170        }
171        let outer = Outer {
172            inner: Filter { tag: None, q: "" },
173        };
174        let _ = href("/").query(&outer);
175    }
176
177    #[test]
178    #[should_panic(expected = "invalid route")]
179    fn invalid_pattern() {
180        let _ = href("/{*rest}/x");
181    }
182}