Skip to main content

egui_kit/
router.rs

1//! The route builder.
2
3mod 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
16/// The route builder.
17///
18/// A router's [layout](Self::layout), [error page](Self::error) and [hooks](Self::hook) apply to
19/// all of its pages and to all routers [nested](Self::nest) inside it. The order of the builder calls does not matter.
20///
21/// Paths are made of static segments and parameters: `{id}`, `{id=matcher}`, optional
22/// `{?lang}` / `{?lang=matcher}` and a trailing `{*rest}`.
23pub 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    /// Adds a page at `path`, e.g. `/`, `/about`, `/blog/{slug}` or `/files/{*path}`.
53    ///
54    /// # Panics
55    /// When the pattern is invalid. Conflicting routes panic when the app is built.
56    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    /// Mounts `router` below `prefix`. The prefix may contain parameters, e.g. `/users/{id}`,
63    /// which are then available to the nested hooks, layouts and pages.
64    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    /// Adds the routes of `router` at the same level, keeping its layout, hooks and error page
71    /// scoped to its own routes.
72    ///
73    /// Paths that match no route are a 404 of this router, not of `router`: its error page only
74    /// shows the errors of its own routes.
75    pub fn merge(self, router: Self) -> Self {
76        self.nest("/", router)
77    }
78
79    /// Names this router, so pages and layouts below it can
80    /// [reset their layouts](Page::reset_layouts_to) up to here.
81    pub fn named(mut self, name: impl Into<String>) -> Self {
82        self.name = Some(name.into());
83        self
84    }
85
86    /// Sets the layout wrapping all pages of this router.
87    ///
88    /// # Panics
89    /// When a layout was already set.
90    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    /// Sets the error page for errors of this router's routes, including
97    /// paths below its prefix that match no route (404). For a router [merged](Self::merge) into
98    /// another, those 404s go to the other router's error page.
99    ///
100    /// The view extracts the error as `&RouteError`, like a page extracts its data.
101    /// It is rendered inside this router's layout. Errors raised by the layout's own `load`
102    /// (or this router's hooks) are handled by the error page of a parent router.
103    ///
104    /// # Panics
105    /// When an error page was already set.
106    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    /// Adds a hook that runs before every navigation to a route of this router (and its nested
119    /// routers), before any `load`. Hooks of outer routers run first. Hooks also run when a
120    /// route is [preloaded](crate::extract::Nav::preload), so keep them free of side effects.
121    ///
122    /// A hook is an async handler with extractor arguments, returning `Result<(), E>` where
123    /// `E: Into<Rejection>`: return an error to show the error page, or a redirect.
124    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    /// Registers a parameter matcher, usable as `{param=name}` in any route of the app.
134    /// A route only matches if the matcher accepts the
135    /// segment; otherwise other routes are tried.
136    ///
137    /// ```
138    /// # use egui_kit::Router;
139    /// let router = Router::<()>::new().matcher("int", |s| s.parse::<u64>().is_ok());
140    /// ```
141    ///
142    /// # Panics
143    /// When building an app with two matchers of the same name, or a route using an unknown one.
144    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    /// Builds the app, using the browser's history on wasm and an in-memory history elsewhere.
154    pub fn with_state(self, state: S) -> RouterApp<S> {
155        self.with_state_and_history(state, history::default_history())
156    }
157
158    /// Builds the app with a custom [`History`].
159    ///
160    /// # Panics
161    /// When routes conflict or refer to unknown matchers or router names.
162    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    /// `parent_prefix` is `None` for the root router.
174    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        // A merged router shares its parent's prefix, whose fallback comes first and wins.
202        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
218/// Drops the layouts of the levels below the reset target. Hooks and error pages stay.
219fn 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
240/// What a [`Router`](crate::Router) contributes to all routes below it.
241pub(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    /// How many path parameters this level's prefix has: its hooks and layout see only those.
247    pub(crate) params: usize,
248}
249
250impl<S> Level<S> {
251    /// The same level, without its layout (for routes that reset their layouts).
252    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}