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
40impl Request {
41    pub(crate) fn new(url: &str) -> Self {
42        let (path, query) = match url.split_once('?') {
43            Some((path, query)) => (path, Some(query.to_owned())),
44            None => (url, None),
45        };
46        Self {
47            path: crate::router::normalize(path),
48            query: query.filter(|q| !q.is_empty()),
49            params: Vec::new(),
50            route: String::new(),
51            deps: Rc::default(),
52            parent: None,
53        }
54    }
55
56    pub(crate) fn with_route(mut self, route: &str, params: Vec<Param>) -> Self {
57        self.route = route.to_owned();
58        self.params = params;
59        self
60    }
61
62    /// A copy for one hook or load: only the first `params` parameters, a fresh dependency
63    /// tracker, and access to the parent layouts' data.
64    pub(crate) fn for_handler(&self, params: usize, parent: Option<ParentHandle>) -> Self {
65        Self {
66            params: self.params[..params.min(self.params.len())].to_vec(),
67            deps: Rc::default(),
68            parent,
69            ..self.clone()
70        }
71    }
72
73    fn track(&self, update: impl FnOnce(&mut Deps)) {
74        let mut deps = self.deps.get();
75        update(&mut deps);
76        self.deps.set(deps);
77    }
78
79    /// The path, e.g. `/blog/hello-world`.
80    pub fn path(&self) -> &str {
81        self.track(|deps| deps.path = true);
82        &self.path
83    }
84
85    /// The raw query string without the leading `?`.
86    pub fn query(&self) -> Option<&str> {
87        self.track(|deps| deps.query = true);
88        self.query.as_deref()
89    }
90
91    /// Path and query, e.g. `/blog?page=2`.
92    pub fn url(&self) -> String {
93        self.track(|deps| {
94            deps.path = true;
95            deps.query = true;
96        });
97        self.untracked_url()
98    }
99
100    /// The pattern of the matched route, e.g. `/blog/{slug}`.
101    pub fn route(&self) -> &str {
102        &self.route
103    }
104
105    /// A single (percent-decoded) path parameter. `None` if the route has no such parameter,
106    /// or it is an optional parameter that is absent.
107    pub fn param(&self, name: &str) -> Option<&str> {
108        self.track(|deps| deps.params = true);
109        self.params
110            .iter()
111            .find(|param| param.name == name)
112            .and_then(|param| param.value.as_deref())
113    }
114
115    pub(crate) fn params(&self) -> &[Param] {
116        self.track(|deps| deps.params = true);
117        &self.params
118    }
119
120    pub(crate) fn untracked_path(&self) -> &str {
121        &self.path
122    }
123
124    pub(crate) fn untracked_url(&self) -> String {
125        match &self.query {
126            Some(query) => format!("{}?{query}", self.path),
127            None => self.path.clone(),
128        }
129    }
130
131    /// Whether a load that depended on `deps` of `self` sees the same values in `other`.
132    pub(crate) fn same_for(&self, deps: Deps, other: &Self) -> bool {
133        (!deps.path || self.path == other.path)
134            && (!deps.query || self.query == other.query)
135            && (!deps.params || self.params == other.params)
136    }
137}
138
139impl fmt::Debug for Request {
140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141        f.debug_struct("Request")
142            .field("path", &self.path)
143            .field("query", &self.query)
144            .field("params", &self.params)
145            .field("route", &self.route)
146            .finish_non_exhaustive()
147    }
148}