Skip to main content

egui_kit/
request.rs

1//! [`Request`]: the url being navigated to and the parameters of the matched route, which also
2//! records what each load reads from it.
3
4use core::cell::Cell;
5use std::fmt;
6use std::rc::Rc;
7
8use crate::extract::parent::ParentHandle;
9
10/// A path parameter. Optional parameters (`{?lang}`) that are absent have no value.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub(crate) struct Param {
13    pub(crate) name: String,
14    pub(crate) value: Option<String>,
15}
16
17/// What a `load` read from its [`Request`], to decide whether it has to rerun on the next
18/// navigation. Recorded automatically.
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
20pub(crate) struct Deps {
21    pub(crate) path: bool,
22    pub(crate) query: bool,
23    pub(crate) params: bool,
24    pub(crate) parent: bool,
25}
26
27/// The url being navigated to, together with the path parameters of the matched route.
28///
29/// Hooks and layout loads only see the parameters of their own router's prefix; pages see all.
30#[derive(Clone)]
31pub struct Request {
32    path: String,
33    query: Option<String>,
34    params: Vec<Param>,
35    route: String,
36    pub(crate) deps: Rc<Cell<Deps>>,
37    pub(crate) parent: Option<ParentHandle>,
38}
39
40/// Splits `url` into the part before the `#` and the fragment after it (`None` if empty).
41pub(crate) fn split_fragment(url: &str) -> (&str, Option<&str>) {
42    match url.split_once('#') {
43        Some((url, fragment)) => (url, Some(fragment).filter(|f| !f.is_empty())),
44        None => (url, None),
45    }
46}
47
48impl Request {
49    /// The request for `url`. A `#fragment` is dropped: it never affects matching or loads.
50    pub(crate) fn new(url: &str) -> Self {
51        let (url, _) = split_fragment(url);
52        let (path, query) = match url.split_once('?') {
53            Some((path, query)) => (path, Some(query.to_owned())),
54            None => (url, None),
55        };
56        Self {
57            path: crate::router::normalize(path),
58            query: query.filter(|q| !q.is_empty()),
59            params: Vec::new(),
60            route: String::new(),
61            deps: Rc::default(),
62            parent: None,
63        }
64    }
65
66    pub(crate) fn with_route(mut self, route: &str, params: Vec<Param>) -> Self {
67        self.route = route.to_owned();
68        self.params = params;
69        self
70    }
71
72    /// A copy for one hook or load: only the first `params` parameters, a fresh dependency
73    /// tracker, and access to the parent layouts' data.
74    pub(crate) fn for_handler(&self, params: usize, parent: Option<ParentHandle>) -> Self {
75        Self {
76            params: self.params[..params.min(self.params.len())].to_vec(),
77            deps: Rc::default(),
78            parent,
79            ..self.clone()
80        }
81    }
82
83    fn track(&self, update: impl FnOnce(&mut Deps)) {
84        let mut deps = self.deps.get();
85        update(&mut deps);
86        self.deps.set(deps);
87    }
88
89    /// The path, e.g. `/blog/hello-world`.
90    pub fn path(&self) -> &str {
91        self.track(|deps| deps.path = true);
92        &self.path
93    }
94
95    /// The raw query string without the leading `?`.
96    pub fn query(&self) -> Option<&str> {
97        self.track(|deps| deps.query = true);
98        self.query.as_deref()
99    }
100
101    /// Path and query, e.g. `/blog?page=2`.
102    pub fn url(&self) -> String {
103        self.track(|deps| {
104            deps.path = true;
105            deps.query = true;
106        });
107        self.untracked_url()
108    }
109
110    /// The pattern of the matched route, e.g. `/blog/{slug}`.
111    pub fn route(&self) -> &str {
112        &self.route
113    }
114
115    /// A single (percent-decoded) path parameter. `None` if the route has no such parameter,
116    /// or it is an optional parameter that is absent.
117    pub fn param(&self, name: &str) -> Option<&str> {
118        self.track(|deps| deps.params = true);
119        self.params
120            .iter()
121            .find(|param| param.name == name)
122            .and_then(|param| param.value.as_deref())
123    }
124
125    pub(crate) fn params(&self) -> &[Param] {
126        self.track(|deps| deps.params = true);
127        &self.params
128    }
129
130    pub(crate) fn untracked_path(&self) -> &str {
131        &self.path
132    }
133
134    pub(crate) fn untracked_url(&self) -> String {
135        match &self.query {
136            Some(query) => format!("{}?{query}", self.path),
137            None => self.path.clone(),
138        }
139    }
140
141    /// Whether a load that depended on `deps` of `self` sees the same values in `other`.
142    pub(crate) fn same_for(&self, deps: Deps, other: &Self) -> bool {
143        (!deps.path || self.path == other.path)
144            && (!deps.query || self.query == other.query)
145            && (!deps.params || self.params == other.params)
146    }
147}
148
149impl fmt::Debug for Request {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        f.debug_struct("Request")
152            .field("path", &self.path)
153            .field("query", &self.query)
154            .field("params", &self.params)
155            .field("route", &self.route)
156            .finish_non_exhaustive()
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn fragments_are_dropped() {
166        assert_eq!(split_fragment("/a?b#c"), ("/a?b", Some("c")));
167        assert_eq!(split_fragment("/a#"), ("/a", None));
168        assert_eq!(split_fragment("/a"), ("/a", None));
169
170        let request = Request::new("/docs/#install");
171        assert_eq!(request.untracked_url(), "/docs");
172        let request = Request::new("/blog?tag=x#top");
173        assert_eq!(request.untracked_path(), "/blog");
174        assert_eq!(request.query(), Some("tag=x"));
175        assert_eq!(Request::new("/blog?#top").query(), None);
176    }
177}