plexus_ui_engine/router/
mod.rs1use serde_json::{Map, Value};
14use std::collections::BTreeMap;
15
16#[derive(Debug, Clone, PartialEq)]
18pub struct Route {
19 pub component: String,
20 pub props: Map<String, Value>,
21}
22
23#[derive(Debug, Clone, Default)]
25pub struct Router {
26 routes: BTreeMap<String, String>,
27}
28
29pub 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 pub fn new(routes: &BTreeMap<String, String>) -> Self {
60 Self { routes: routes.clone() }
61 }
62
63 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 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;