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    pub fn merge(self, router: Self) -> Self {
73        self.nest("/", router)
74    }
75
76    /// Names this router, so pages and layouts below it can
77    /// [reset their layouts](Page::reset_layouts_to) up to here.
78    pub fn named(mut self, name: impl Into<String>) -> Self {
79        self.name = Some(name.into());
80        self
81    }
82
83    /// Sets the layout wrapping all pages of this router.
84    ///
85    /// # Panics
86    /// When a layout was already set.
87    pub fn layout(mut self, layout: Layout<S>) -> Self {
88        assert!(self.layout.is_none(), "a router can only have one layout");
89        self.layout = Some(layout);
90        self
91    }
92
93    /// Sets the error page for errors of this router's routes, including
94    /// paths below its prefix that match no route (404).
95    ///
96    /// The view extracts the error as `&RouteError`, like a page extracts its data.
97    /// It is rendered inside this router's layout. Errors raised by the layout's own `load`
98    /// (or this router's hooks) are handled by the error page of a parent router.
99    ///
100    /// # Panics
101    /// When an error page was already set.
102    pub fn error<V, U>(mut self, view: V) -> Self
103    where
104        V: View<U, S, RouteError>,
105    {
106        assert!(
107            self.error.is_none(),
108            "a router can only have one error page"
109        );
110        self.error = Some(Rc::new(move |ui, cx| view.call(ui, cx)));
111        self
112    }
113
114    /// Adds a hook that runs before every navigation to a route of this router (and its nested
115    /// routers), before any `load`. Hooks of outer routers run first. Hooks also run when a
116    /// route is [preloaded](crate::extract::Nav::preload), so keep them free of side effects.
117    ///
118    /// A hook is an async handler with extractor arguments, returning `Result<(), E>` where
119    /// `E: Into<Rejection>`: return an error to show the error page, or a redirect.
120    pub fn hook<H, T, E>(mut self, hook: H) -> Self
121    where
122        H: Handler<T, S, Output = Result<(), E>>,
123        E: Into<Rejection>,
124    {
125        self.hooks.push(page::erase(hook));
126        self
127    }
128
129    /// Registers a parameter matcher, usable as `{param=name}` in any route of the app.
130    /// A route only matches if the matcher accepts the
131    /// segment; otherwise other routes are tried.
132    ///
133    /// ```
134    /// # use egui_kit::Router;
135    /// let router = Router::<()>::new().matcher("int", |s| s.parse::<u64>().is_ok());
136    /// ```
137    ///
138    /// # Panics
139    /// When building an app with two matchers of the same name, or a route using an unknown one.
140    pub fn matcher(
141        mut self,
142        name: impl Into<String>,
143        matcher: impl Fn(&str) -> bool + 'static,
144    ) -> Self {
145        self.matchers.push((name.into(), Rc::new(matcher)));
146        self
147    }
148
149    /// Builds the app, using the browser's history on wasm and an in-memory history elsewhere.
150    pub fn with_state(self, state: S) -> RouterApp<S> {
151        self.with_state_and_history(state, history::default_history())
152    }
153
154    /// Builds the app with a custom [`History`].
155    ///
156    /// # Panics
157    /// When routes conflict or refer to unknown matchers or router names.
158    pub fn with_state_and_history(self, state: S, history: impl History + 'static) -> RouterApp<S> {
159        RouterApp::new(self.into_table(), state, Box::new(history))
160    }
161
162    pub(crate) fn into_table(self) -> RouteTable<S> {
163        let mut table = RouteTable::default();
164        self.flatten("/", &[], &mut table);
165        table.validate();
166        table
167    }
168
169    fn flatten(self, prefix: &str, parents: &[Rc<Level<S>>], table: &mut RouteTable<S>) {
170        for (name, matcher) in self.matchers {
171            assert!(
172                table.matchers.insert(name.clone(), matcher).is_none(),
173                "duplicate matcher `{name}`"
174            );
175        }
176
177        let layout_reset = self.layout.as_ref().and_then(|layout| layout.reset.clone());
178        let mut levels = match &layout_reset {
179            Some(reset) => reset_layouts(parents, reset),
180            None => parents.to_vec(),
181        };
182        levels.push(Rc::new(Level {
183            name: self.name,
184            hooks: self.hooks,
185            layout: self.layout.map(Rc::new),
186            error: self.error,
187            params: Pattern::parse(prefix).param_count(),
188        }));
189
190        table.add_fallback(prefix, levels.clone());
191        for (path, page) in self.routes {
192            let levels = match &page.reset {
193                Some(reset) => reset_layouts(&levels, reset),
194                None => levels.clone(),
195            };
196            table.add_page(&join(prefix, &path), levels, page);
197        }
198        for (nested_prefix, router) in self.nested {
199            router.flatten(&join(prefix, &nested_prefix), &levels, table);
200        }
201    }
202}
203
204/// Drops the layouts of the levels below the reset target. Hooks and error pages stay.
205fn reset_layouts<S>(levels: &[Rc<Level<S>>], reset: &LayoutReset) -> Vec<Rc<Level<S>>> {
206    let keep = match reset {
207        LayoutReset::Root => 0,
208        LayoutReset::To(name) => levels
209            .iter()
210            .rposition(|level| level.name.as_deref() == Some(name))
211            .unwrap_or_else(|| panic!("no parent router named `{name}` to reset the layouts to")),
212    };
213    levels
214        .iter()
215        .enumerate()
216        .map(|(i, level)| {
217            if i <= keep {
218                Rc::clone(level)
219            } else {
220                Rc::new(level.without_layout())
221            }
222        })
223        .collect()
224}
225
226/// What a [`Router`](crate::Router) contributes to all routes below it.
227pub(crate) struct Level<S> {
228    pub(crate) name: Option<String>,
229    pub(crate) hooks: Vec<ErasedHandler<S>>,
230    pub(crate) layout: Option<Rc<Layout<S>>>,
231    pub(crate) error: Option<ErasedView<S>>,
232    /// How many path parameters this level's prefix has: its hooks and layout see only those.
233    pub(crate) params: usize,
234}
235
236impl<S> Level<S> {
237    /// The same level, without its layout (for routes that reset their layouts).
238    pub(crate) fn without_layout(&self) -> Self {
239        Self {
240            name: self.name.clone(),
241            hooks: self.hooks.clone(),
242            layout: None,
243            error: self.error.clone(),
244            params: self.params,
245        }
246    }
247}