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