Skip to main content

plexus_ui_engine/router/
mod.rs

1//! UI-6: **the router** — `manifest.routes`: a hash route (`#/ticket/T-1`)
2//! to the component drawn (a layout too) and its props, each `:name`
3//! segment of the pattern a prop. The most specific pattern wins: one with
4//! fewer `:` segments over one with more (`#/ticket/new` over
5//! `#/ticket/:id`).
6//!
7//! STUDIO-3: the service's rows (`ui.routes`, a pattern → a component) are
8//! merged over `manifest.routes` ([`Router::merged`]): a row replaces the
9//! manifest's route for its pattern, or adds one; a row whose component the
10//! version does not hold is passed over, so the manifest's own route (or
11//! none) stands there.
12
13use serde_json::{Map, Value};
14use std::collections::BTreeMap;
15
16/// A resolved route.
17#[derive(Debug, Clone, PartialEq)]
18pub struct Route {
19    pub component: String,
20    pub props: Map<String, Value>,
21}
22
23/// The routes of the live version.
24#[derive(Debug, Clone, Default)]
25pub struct Router {
26    routes: BTreeMap<String, String>,
27}
28
29/// UI-8: a segment percent-decoded — the browser keeps the hash encoded
30/// (`#/f/status%20Ready`), and a prop is the text (`status Ready`); a `%`
31/// that starts no escape, or bytes that are not UTF-8, are kept as written.
32pub fn decode(segment: &str) -> String {
33    let b = segment.as_bytes();
34    let mut out = Vec::with_capacity(b.len());
35    let mut i = 0;
36    while i < b.len() {
37        let hex = |c: u8| (c as char).to_digit(16);
38        if b[i] == b'%' && i + 2 < b.len() {
39            if let (Some(h), Some(l)) = (hex(b[i + 1]), hex(b[i + 2])) {
40                out.push((h * 16 + l) as u8);
41                i += 3;
42                continue;
43            }
44        }
45        out.push(b[i]);
46        i += 1;
47    }
48    String::from_utf8(out).unwrap_or_else(|_| segment.to_string())
49}
50
51fn segments(path: &str) -> Vec<&str> {
52    let path = path.trim_start_matches('#').trim_start_matches('/');
53    let path = path.split(['?']).next().unwrap_or("");
54    path.split('/').filter(|s| !s.is_empty()).collect()
55}
56
57impl Router {
58    /// Over `manifest.routes`.
59    pub fn new(routes: &BTreeMap<String, String>) -> Self {
60        Self { routes: routes.clone() }
61    }
62
63    /// STUDIO-3: over `manifest.routes` with the service's `rows` merged
64    /// in — each row whose component `holds` replacing (or adding) its
65    /// pattern; the rest passed over.
66    pub fn merged(routes: &BTreeMap<String, String>, rows: &BTreeMap<String, String>, holds: impl Fn(&str) -> bool) -> Self {
67        let mut all = routes.clone();
68        for (pattern, component) in rows {
69            if holds(component) {
70                all.insert(pattern.clone(), component.clone());
71            }
72        }
73        Self { routes: all }
74    }
75
76    /// The route `hash` (`#/ticket/T-1`; an empty hash is `#/`) names.
77    pub fn resolve(&self, hash: &str) -> Option<Route> {
78        let want = segments(hash);
79        let mut best: Option<(usize, Route)> = None;
80        for (pattern, component) in &self.routes {
81            let pat = segments(pattern);
82            if pat.len() != want.len() {
83                continue;
84            }
85            let mut props = Map::new();
86            let mut params = 0;
87            let fits = pat.iter().zip(&want).all(|(p, w)| match p.strip_prefix(':') {
88                Some(name) => {
89                    params += 1;
90                    props.insert(name.to_string(), Value::String(decode(w)));
91                    true
92                }
93                None => p == w,
94            });
95            if fits && best.as_ref().is_none_or(|(n, _)| params < *n) {
96                best = Some((params, Route { component: component.clone(), props }));
97            }
98        }
99        best.map(|(_, r)| r)
100    }
101}
102
103#[cfg(test)]
104mod tests;