Skip to main content

rustango_cms/
routable.rs

1//! `routable_page` — routable pages. A single `Page` row can serve multiple URL patterns
2//! under its canonical url_path.
3//!
4//! ## Why
5//!
6//! Archive / category index pages typically own a stable canonical
7//! URL (`/blog/`) plus a family of sub-paths the framework's slug
8//! resolver shouldn't have to materialize as real `cms_page` rows
9//! — `/blog/archive/2026/`, `/blog/tag/rust/`, etc. The
10//! routable-page surface lets the handler declare those patterns
11//! and serve them through the same Tera template (with the
12//! capture groups available in the context).
13//!
14//! ## API
15//!
16//! Handlers override [`crate::PageTypeHandler::routes`] to return
17//! a list of [`RouteSpec`] entries. Each spec carries a regex
18//! pattern (matched against the suffix BELOW the page's
19//! `url_path`) and a stable name. When the public router can't
20//! find an exact `url_path` match, it walks ancestor candidates
21//! looking for a handler whose routes match the remaining suffix.
22//! On match, the matched [`Page`](crate::page::Page) is rendered with two extra ctx
23//! keys: `route_name` (the matched [`RouteSpec::name`]) and
24//! `route_captures` (a `{name → value}` map of regex named groups).
25//!
26//! Handlers can also override [`crate::PageTypeHandler::route_context`]
27//! to inject route-specific data (e.g. fetch the year's posts when
28//! `archive_year` matched) — the returned map is merged into the
29//! Tera context before render. Same precedence rule as
30//! [`crate::PageTypeHandler::public_context`]: framework
31//! keys land last and win every collision.
32
33use std::collections::HashMap;
34
35use regex::Regex;
36
37/// What a matched routable pattern renders — see
38/// [`crate::PageTypeHandler::route_outcome`].
39#[derive(Debug, Clone, PartialEq, Eq, Default)]
40pub enum RouteOutcome {
41    /// Render the page with its usual template (override, else the
42    /// type's).
43    #[default]
44    Render,
45    /// Render with this template instead. A name Tera does not know
46    /// falls back to [`Self::Render`].
47    Template(String),
48    /// The record the URL names does not exist: the site's 404 page,
49    /// with status 404.
50    NotFound,
51}
52
53/// A single named URL pattern. The pattern is anchored on both
54/// ends (`^…$`) by the constructor; callers can lean on
55/// `^` / `$` themselves but don't have to.
56///
57/// Suffix-relative — when the rendered page's `url_path` is
58/// `/blog`, a request to `/blog/archive/2026` matches a route
59/// pattern of `^archive/(?P<year>\d+)$`.
60#[derive(Clone)]
61pub struct RouteSpec {
62    pub pattern: Regex,
63    pub name: &'static str,
64}
65
66impl RouteSpec {
67    /// Construct a route. The pattern is anchored automatically
68    /// (`^…$`) so handlers don't have to remember the anchors. On
69    /// invalid regex the call panics — callers are expected to
70    /// declare these as static-shape strings at handler-build
71    /// time, so a malformed pattern is a bug, not a runtime
72    /// recoverable.
73    #[must_use]
74    pub fn new(pattern: &str, name: &'static str) -> Self {
75        let anchored = anchor(pattern);
76        Self {
77            pattern: Regex::new(&anchored)
78                .unwrap_or_else(|e| panic!("RouteSpec: invalid pattern `{pattern}`: {e}")),
79            name,
80        }
81    }
82}
83
84impl std::fmt::Debug for RouteSpec {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        f.debug_struct("RouteSpec")
87            .field("pattern", &self.pattern.as_str())
88            .field("name", &self.name)
89            .finish()
90    }
91}
92
93fn anchor(pattern: &str) -> String {
94    let lead = if pattern.starts_with('^') { "" } else { "^" };
95    let trail = if pattern.ends_with('$') { "" } else { "$" };
96    format!("{lead}{pattern}{trail}")
97}
98
99/// Result of attempting to match a route on a page.
100#[derive(Debug, Clone)]
101pub struct RouteMatch {
102    pub name: &'static str,
103    pub captures: HashMap<String, String>,
104}
105
106/// Walk a handler's routes against `suffix` (the request path with
107/// the page's `url_path` stripped off — without the leading `/`).
108/// Returns the first matching `RouteMatch`, or `None` when no
109/// route accepts the suffix.
110pub fn match_routes(routes: &[RouteSpec], suffix: &str) -> Option<RouteMatch> {
111    let stripped = suffix.trim_start_matches('/').trim_end_matches('/');
112    for route in routes {
113        if let Some(captures) = route.pattern.captures(stripped) {
114            let mut named: HashMap<String, String> = HashMap::new();
115            for name in route.pattern.capture_names().flatten() {
116                if let Some(m) = captures.name(name) {
117                    named.insert(name.to_owned(), m.as_str().to_owned());
118                }
119            }
120            return Some(RouteMatch {
121                name: route.name,
122                captures: named,
123            });
124        }
125    }
126    None
127}
128
129/// Reverse a named route into the URL suffix below the page's
130/// `url_path`. Returns
131/// `None` when no route has `name` or its pattern isn't reversible
132/// (see [`reverse_pattern`]). Combine the suffix with the page's
133/// `url_path` for a full URL — the `routable_url()` Tera function does
134/// exactly that.
135#[must_use]
136pub fn reverse(
137    routes: &[RouteSpec],
138    name: &str,
139    captures: &HashMap<String, String>,
140) -> Option<String> {
141    let route = routes.iter().find(|r| r.name == name)?;
142    reverse_pattern(route.pattern.as_str(), captures)
143}
144
145/// Best-effort reverse of an anchored regex `pattern`: substitute
146/// `captures` into each `(?P<name>…)` group and emit the literal
147/// segments between them. Returns `None` when the pattern can't be
148/// reversed unambiguously — a non-named group, a **quantified** group,
149/// a character class / metacharacter in the literal text (`\d`, `.`,
150/// `+`, `[`, `|`, …), or a capture with no supplied value.
151///
152/// This covers the routable shape people actually write —
153/// `^archive/(?P<year>\d{4})/(?P<month>\d{2})$` — and bows out of the
154/// genuinely-ambiguous ones rather than guessing.
155#[must_use]
156pub fn reverse_pattern(pattern: &str, captures: &HashMap<String, String>) -> Option<String> {
157    let mut body = pattern;
158    body = body.strip_prefix('^').unwrap_or(body);
159    body = body.strip_suffix('$').unwrap_or(body);
160    let chars: Vec<char> = body.chars().collect();
161    let mut out = String::new();
162    let mut i = 0;
163    while i < chars.len() {
164        match chars[i] {
165            '\\' => {
166                // Escaped char: a metachar (`\.`, `\/`, `\-`) is a
167                // literal; an escaped letter/digit (`\d`, `\w`, `\b`)
168                // is a class — not reversible.
169                i += 1;
170                let e = *chars.get(i)?;
171                if e.is_ascii_alphanumeric() {
172                    return None;
173                }
174                out.push(e);
175                i += 1;
176            }
177            '(' => {
178                // Only named groups are reversible.
179                if chars.get(i + 1) == Some(&'?')
180                    && chars.get(i + 2) == Some(&'P')
181                    && chars.get(i + 3) == Some(&'<')
182                {
183                    let mut j = i + 4;
184                    let mut name = String::new();
185                    while j < chars.len() && chars[j] != '>' {
186                        name.push(chars[j]);
187                        j += 1;
188                    }
189                    if j >= chars.len() {
190                        return None; // unterminated group name
191                    }
192                    // Skip to the matching ')' (depth-counted, escapes
193                    // skipped). The inner pattern is irrelevant — the
194                    // supplied capture value replaces it.
195                    let mut depth = 1;
196                    let mut k = j + 1;
197                    while k < chars.len() {
198                        match chars[k] {
199                            '\\' => {
200                                k += 2;
201                                continue;
202                            }
203                            '(' => depth += 1,
204                            ')' => {
205                                depth -= 1;
206                                if depth == 0 {
207                                    k += 1;
208                                    break;
209                                }
210                            }
211                            _ => {}
212                        }
213                        k += 1;
214                    }
215                    if depth != 0 {
216                        return None; // unbalanced parens
217                    }
218                    // A quantifier on the group (`(…)?`, `(…)+`, `(…){2}`)
219                    // makes the reverse ambiguous.
220                    if matches!(chars.get(k), Some('?' | '*' | '+' | '{')) {
221                        return None;
222                    }
223                    out.push_str(captures.get(&name)?);
224                    i = k;
225                } else {
226                    return None; // non-named / non-capturing group
227                }
228            }
229            // A bare metacharacter in the literal text means the
230            // pattern isn't a fixed string — can't reverse it.
231            '.' | '*' | '+' | '?' | '[' | ']' | '{' | '}' | '|' | ')' => return None,
232            c => {
233                out.push(c);
234                i += 1;
235            }
236        }
237    }
238    Some(out)
239}
240
241/// Register the `routable_url(…)` Tera function. Two call shapes (extra kwargs are the
242/// named captures):
243///
244/// ```tera
245/// {# by page type + route name (looks up the handler's RouteSpec) #}
246/// {{ routable_url(path=page.url_path, type=page.type_name, route="archive_year", year=2026) }}
247/// {# or reverse a pattern directly #}
248/// {{ routable_url(path=page.url_path, pattern="archive/(?P<year>\d{4})", year=2026) }}
249/// ```
250///
251/// Returns the full URL (`{path}/{suffix}`), or null when the route /
252/// pattern can't be reversed.
253pub fn register_tera_function(tera: &mut tera::Tera) {
254    tera.register_function("routable_url", routable_url_fn);
255}
256
257fn routable_url_fn(args: &HashMap<String, tera::Value>) -> tera::Result<tera::Value> {
258    let path = args.get("path").and_then(tera::Value::as_str).unwrap_or("");
259    // Captures = every kwarg except the reserved control keys.
260    let reserved = ["path", "type", "route", "pattern"];
261    let mut captures: HashMap<String, String> = HashMap::new();
262    for (k, v) in args {
263        if reserved.contains(&k.as_str()) {
264            continue;
265        }
266        // Strings unwrap to their text; numbers/bools to their literal
267        // (Value::to_string would JSON-quote a string).
268        let s = match v {
269            tera::Value::String(s) => s.clone(),
270            other => other.to_string(),
271        };
272        captures.insert(k.clone(), s);
273    }
274    let suffix = if let Some(pattern) = args.get("pattern").and_then(tera::Value::as_str) {
275        reverse_pattern(pattern, &captures)
276    } else {
277        let type_name = args.get("type").and_then(tera::Value::as_str).unwrap_or("");
278        let route = args
279            .get("route")
280            .and_then(tera::Value::as_str)
281            .unwrap_or("");
282        if type_name.is_empty() || route.is_empty() {
283            return Ok(tera::Value::Null);
284        }
285        match crate::page_type::find_handler(type_name) {
286            Some(h) => reverse(&h.routes(), route, &captures),
287            None => None,
288        }
289    };
290    Ok(match suffix {
291        Some(s) => tera::Value::String(format!("{}/{s}", path.trim_end_matches('/'))),
292        None => tera::Value::Null,
293    })
294}
295
296/// Compute the parent-prefix candidates from `request_path`,
297/// ordered from longest (most specific) to shortest (root). Each
298/// candidate is the prefix of `request_path` up to a path
299/// boundary — i.e. `/blog/archive/2026` produces `/blog/archive`,
300/// `/blog`, `/` (in that order).
301///
302/// Used by the resolver to walk up the tree when an exact
303/// `url_path` lookup misses: try each ancestor's handler routes
304/// before falling all the way through to a 404.
305#[must_use]
306pub fn ancestor_prefixes(request_path: &str) -> Vec<String> {
307    let canon = crate::resolver::canonical_request_path(request_path);
308    if canon == "/" {
309        return Vec::new();
310    }
311    let mut out: Vec<String> = Vec::new();
312    let mut working = canon.as_str();
313    // Strip the leaf segment first — we already missed on the full
314    // path in the exact lookup, no point retrying it.
315    while let Some(slash) = working.rfind('/') {
316        let parent = if slash == 0 { "/" } else { &working[..slash] };
317        out.push(parent.to_owned());
318        if parent == "/" {
319            break;
320        }
321        working = parent;
322    }
323    out
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    #[test]
331    fn anchors_pattern_when_not_anchored() {
332        assert_eq!(anchor("foo"), "^foo$");
333        assert_eq!(anchor("^foo"), "^foo$");
334        assert_eq!(anchor("foo$"), "^foo$");
335        assert_eq!(anchor("^foo$"), "^foo$");
336    }
337
338    #[test]
339    fn match_routes_finds_named_captures() {
340        let routes = vec![
341            RouteSpec::new(r"archive/(?P<year>\d{4})", "archive_year"),
342            RouteSpec::new(r"tag/(?P<slug>[a-z0-9-]+)", "tag"),
343        ];
344        let m = match_routes(&routes, "archive/2026").expect("match");
345        assert_eq!(m.name, "archive_year");
346        assert_eq!(m.captures.get("year"), Some(&"2026".to_owned()));
347    }
348
349    fn caps(pairs: &[(&str, &str)]) -> HashMap<String, String> {
350        pairs
351            .iter()
352            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
353            .collect()
354    }
355
356    #[test]
357    fn reverse_substitutes_named_groups_and_literals() {
358        let routes = vec![RouteSpec::new(
359            r"archive/(?P<year>\d{4})/(?P<month>\d{2})",
360            "archive_ym",
361        )];
362        let url = reverse(
363            &routes,
364            "archive_ym",
365            &caps(&[("year", "2026"), ("month", "06")]),
366        );
367        assert_eq!(url.as_deref(), Some("archive/2026/06"));
368    }
369
370    #[test]
371    fn reverse_round_trips_with_match() {
372        // The suffix `reverse` produces must match the same route.
373        let routes = vec![RouteSpec::new(r"tag/(?P<slug>[a-z0-9-]+)", "tag")];
374        let suffix = reverse(&routes, "tag", &caps(&[("slug", "rust-lang")])).unwrap();
375        assert_eq!(suffix, "tag/rust-lang");
376        let m = match_routes(&routes, &suffix).expect("re-match");
377        assert_eq!(m.name, "tag");
378        assert_eq!(m.captures.get("slug"), Some(&"rust-lang".to_owned()));
379    }
380
381    #[test]
382    fn reverse_unescapes_literal_metachars() {
383        assert_eq!(
384            reverse_pattern(r"^feed\.rss$", &caps(&[])).as_deref(),
385            Some("feed.rss")
386        );
387    }
388
389    #[test]
390    fn reverse_unknown_route_or_missing_capture_is_none() {
391        let routes = vec![RouteSpec::new(r"tag/(?P<slug>[a-z]+)", "tag")];
392        assert!(reverse(&routes, "nope", &caps(&[("slug", "x")])).is_none());
393        assert!(reverse(&routes, "tag", &caps(&[])).is_none()); // missing slug
394    }
395
396    #[test]
397    fn reverse_bows_out_of_unreversible_patterns() {
398        // Bare class outside a group, non-named group, alternation,
399        // quantified group — all ambiguous.
400        assert!(reverse_pattern(r"^posts/\d+$", &caps(&[])).is_none());
401        assert!(reverse_pattern(r"^(?:a|b)/x$", &caps(&[])).is_none());
402        assert!(reverse_pattern(r"^a.b$", &caps(&[])).is_none());
403        assert!(reverse_pattern(r"^(?P<x>\d)+$", &caps(&[("x", "1")])).is_none());
404    }
405
406    fn render(src: &str) -> String {
407        let mut tera = tera::Tera::default();
408        register_tera_function(&mut tera);
409        tera.add_raw_template("t.html", src).unwrap();
410        tera.render("t.html", &tera::Context::new()).unwrap()
411    }
412
413    #[test]
414    fn tera_routable_url_reverses_pattern_arg() {
415        // `pattern` shape needs no registered handler. Path trailing
416        // slash is normalised so we don't get a double slash. `| safe`
417        // mirrors the other URL helpers — Tera would otherwise escape
418        // the slashes (browsers decode them, but raw reads cleaner).
419        let out = render(
420            r#"{{ routable_url(path="/blog/", pattern="tag/(?P<slug>[a-z]+)", slug="rust") | safe }}"#,
421        );
422        assert_eq!(out, "/blog/tag/rust");
423    }
424
425    #[test]
426    fn tera_routable_url_null_when_unreversible() {
427        // Missing capture → null → empty render.
428        let out = render(
429            r#"{% set u = routable_url(path="/blog", pattern="tag/(?P<slug>[a-z]+)") %}{% if u %}{{ u }}{% else %}none{% endif %}"#,
430        );
431        assert_eq!(out, "none");
432    }
433
434    #[test]
435    fn match_routes_tries_each_in_order() {
436        let routes = vec![
437            RouteSpec::new(r"archive/(?P<year>\d{4})", "archive_year"),
438            RouteSpec::new(r"tag/(?P<slug>[a-z0-9-]+)", "tag"),
439        ];
440        let m = match_routes(&routes, "tag/rust").expect("match");
441        assert_eq!(m.name, "tag");
442        assert_eq!(m.captures.get("slug"), Some(&"rust".to_owned()));
443    }
444
445    #[test]
446    fn match_routes_returns_none_when_no_pattern_accepts() {
447        let routes = vec![RouteSpec::new(r"archive/(?P<year>\d{4})", "archive_year")];
448        assert!(match_routes(&routes, "foo/bar").is_none());
449    }
450
451    #[test]
452    fn match_routes_strips_leading_and_trailing_slashes() {
453        let routes = vec![RouteSpec::new(r"archive/(?P<year>\d{4})", "archive_year")];
454        // The resolver hands `/archive/2026/`; the handler's
455        // pattern is anchored, so we strip the boundary slashes.
456        let m = match_routes(&routes, "/archive/2026/").expect("match");
457        assert_eq!(m.name, "archive_year");
458    }
459
460    #[test]
461    fn ancestor_prefixes_walks_up_one_segment_at_a_time() {
462        assert_eq!(
463            ancestor_prefixes("/blog/archive/2026"),
464            vec!["/blog/archive", "/blog", "/"],
465        );
466        assert_eq!(
467            ancestor_prefixes("/blog/archive/2026/"),
468            vec!["/blog/archive", "/blog", "/"],
469        );
470        assert_eq!(ancestor_prefixes("/blog"), vec!["/"]);
471    }
472
473    #[test]
474    fn ancestor_prefixes_empty_for_root() {
475        assert!(ancestor_prefixes("/").is_empty());
476        assert!(ancestor_prefixes("").is_empty());
477    }
478
479    #[test]
480    fn captures_without_named_groups_yields_empty_map() {
481        let routes = vec![RouteSpec::new(r"archive/\d+", "archive_any")];
482        let m = match_routes(&routes, "archive/2026").expect("match");
483        assert!(m.captures.is_empty());
484    }
485}