1mod pattern;
4mod table;
5
6use std::rc::Rc;
7
8use crate::app::RouterApp;
9use crate::error::{Rejection, RouteError};
10use crate::history::{self, History};
11use crate::page::{self, ErasedHandler, ErasedView, Handler, Layout, LayoutReset, Page, View};
12use pattern::Matcher;
13pub(crate) use pattern::{Pattern, join, normalize};
14pub(crate) use table::{RouteEntry, RouteTable, Target};
15
16pub struct Router<S> {
24 name: Option<String>,
25 routes: Vec<(String, Page<S>)>,
26 nested: Vec<(String, Self)>,
27 hooks: Vec<ErasedHandler<S>>,
28 layout: Option<Layout<S>>,
29 error: Option<ErasedView<S>>,
30 matchers: Vec<(String, Matcher)>,
31}
32
33impl<S: Clone + 'static> Default for Router<S> {
34 fn default() -> Self {
35 Self::new()
36 }
37}
38
39impl<S: Clone + 'static> Router<S> {
40 pub fn new() -> Self {
41 Self {
42 name: None,
43 routes: Vec::new(),
44 nested: Vec::new(),
45 hooks: Vec::new(),
46 layout: None,
47 error: None,
48 matchers: Vec::new(),
49 }
50 }
51
52 pub fn page(mut self, path: &str, page: Page<S>) -> Self {
57 Pattern::parse(path);
58 self.routes.push((path.to_owned(), page));
59 self
60 }
61
62 pub fn nest(mut self, prefix: &str, router: Self) -> Self {
65 Pattern::parse(prefix);
66 self.nested.push((prefix.to_owned(), router));
67 self
68 }
69
70 pub fn merge(self, router: Self) -> Self {
76 self.nest("/", router)
77 }
78
79 pub fn named(mut self, name: impl Into<String>) -> Self {
82 self.name = Some(name.into());
83 self
84 }
85
86 pub fn layout(mut self, layout: Layout<S>) -> Self {
91 assert!(self.layout.is_none(), "a router can only have one layout");
92 self.layout = Some(layout);
93 self
94 }
95
96 pub fn error<V, U>(mut self, view: V) -> Self
107 where
108 V: View<U, S, RouteError>,
109 {
110 assert!(
111 self.error.is_none(),
112 "a router can only have one error page"
113 );
114 self.error = Some(Rc::new(move |ui, cx| view.call(ui, cx)));
115 self
116 }
117
118 pub fn hook<H, T, E>(mut self, hook: H) -> Self
125 where
126 H: Handler<T, S, Output = Result<(), E>>,
127 E: Into<Rejection>,
128 {
129 self.hooks.push(page::erase(hook));
130 self
131 }
132
133 pub fn matcher(
145 mut self,
146 name: impl Into<String>,
147 matcher: impl Fn(&str) -> bool + 'static,
148 ) -> Self {
149 self.matchers.push((name.into(), Rc::new(matcher)));
150 self
151 }
152
153 pub fn with_state(self, state: S) -> RouterApp<S> {
155 self.with_state_and_history(state, history::default_history())
156 }
157
158 pub fn with_state_and_history(self, state: S, history: impl History + 'static) -> RouterApp<S> {
163 RouterApp::new(self.into_table(), state, Box::new(history))
164 }
165
166 pub(crate) fn into_table(self) -> RouteTable<S> {
167 let mut table = RouteTable::default();
168 self.flatten("/", None, &[], &mut table);
169 table.validate();
170 table
171 }
172
173 fn flatten(
175 self,
176 prefix: &str,
177 parent_prefix: Option<&str>,
178 parents: &[Rc<Level<S>>],
179 table: &mut RouteTable<S>,
180 ) {
181 for (name, matcher) in self.matchers {
182 assert!(
183 table.matchers.insert(name.clone(), matcher).is_none(),
184 "duplicate matcher `{name}`"
185 );
186 }
187
188 let layout_reset = self.layout.as_ref().and_then(|layout| layout.reset.clone());
189 let mut levels = match &layout_reset {
190 Some(reset) => reset_layouts(parents, reset),
191 None => parents.to_vec(),
192 };
193 levels.push(Rc::new(Level {
194 name: self.name,
195 hooks: self.hooks,
196 layout: self.layout.map(Rc::new),
197 error: self.error,
198 params: Pattern::parse(prefix).param_count(),
199 }));
200
201 if parent_prefix != Some(prefix) {
203 table.add_fallback(prefix, levels.clone());
204 }
205 for (path, page) in self.routes {
206 let levels = match &page.reset {
207 Some(reset) => reset_layouts(&levels, reset),
208 None => levels.clone(),
209 };
210 table.add_page(&join(prefix, &path), levels, page);
211 }
212 for (nested_prefix, router) in self.nested {
213 router.flatten(&join(prefix, &nested_prefix), Some(prefix), &levels, table);
214 }
215 }
216}
217
218fn reset_layouts<S>(levels: &[Rc<Level<S>>], reset: &LayoutReset) -> Vec<Rc<Level<S>>> {
220 let keep = match reset {
221 LayoutReset::Root => 0,
222 LayoutReset::To(name) => levels
223 .iter()
224 .rposition(|level| level.name.as_deref() == Some(name))
225 .unwrap_or_else(|| panic!("no parent router named `{name}` to reset the layouts to")),
226 };
227 levels
228 .iter()
229 .enumerate()
230 .map(|(i, level)| {
231 if i <= keep {
232 Rc::clone(level)
233 } else {
234 Rc::new(level.without_layout())
235 }
236 })
237 .collect()
238}
239
240pub(crate) struct Level<S> {
242 pub(crate) name: Option<String>,
243 pub(crate) hooks: Vec<ErasedHandler<S>>,
244 pub(crate) layout: Option<Rc<Layout<S>>>,
245 pub(crate) error: Option<ErasedView<S>>,
246 pub(crate) params: usize,
248}
249
250impl<S> Level<S> {
251 pub(crate) fn without_layout(&self) -> Self {
253 Self {
254 name: self.name.clone(),
255 hooks: self.hooks.clone(),
256 layout: None,
257 error: self.error.clone(),
258 params: self.params,
259 }
260 }
261}