-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.tsx
104 lines (82 loc) · 2.56 KB
/
router.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import { router as expoRouter } from 'expo-router';
export type RoutableComponent = (props: {routeExecution: RouteExecution}) => JSX.Element
export type Route = {
pattern: string,
regexp: RegExp,
pathParameters: string[],
}
export type RouteExecution = {
route: Route,
args: Record<string, string>,
}
export class Router {
prefix?: string;
routes: Map<Route, RoutableComponent> = new Map();
setPrefix(prefix: string): this {
this.prefix = prefix;
return this;
}
private extractPathParameters(route: string): string[] {
const parameterRegex = /{([^}]+)}/g;
const pathParameters: string[] = [];
let match: ReturnType<RegExp["exec"]> | null;
while ((match = parameterRegex.exec(route)) !== null) {
pathParameters.push(match[1]);
}
return pathParameters;
}
addRoute(pattern: string, Component: RoutableComponent): this {
const fullPattern = this.prefix ? `${this.prefix}${pattern}` : pattern;
const pathParameters = this.extractPathParameters(fullPattern);
const regexp = new RegExp(fullPattern.replace(/{([^}]+)}/g, "([^/]+)"));
const route = {pattern: fullPattern, regexp, pathParameters};
this.routes.set(route, Component);
return this;
}
execute(path: string, props?: JSX.Element['props']): JSX.Element | null {
for (const [route, Component] of this.routes) {
const match = route.regexp.exec(path);
if (match) {
const args: Record<string, string> = {};
for (let i = 0; i < route.pathParameters.length; i++) {
args[route.pathParameters[i]] = match[i + 1];
}
if (props) {
return <Component routeExecution={{route, args}} {...props} />;
}
return <Component routeExecution={{route, args}} />;
}
}
return null;
}
navigate(href: Parameters<(typeof expoRouter)['navigate']>[0]) {
return expoRouter.navigate(href);
}
push(href: Parameters<(typeof expoRouter)['push']>[0]) {
return expoRouter.push(href);
}
replace(href: Parameters<(typeof expoRouter)['replace']>[0]) {
return expoRouter.replace(href);
}
back() {
return expoRouter.back();
}
canGoBack() {
return expoRouter.canGoBack();
}
}
const routers = new Map<string | undefined, Router>();
export default function router(prefix?: string): Router {
if (!routers.has(prefix)) {
const r = new Router();
if (prefix) {
r.setPrefix(prefix);
}
routers.set(prefix, r);
}
const r = routers.get(prefix);
if (!r) {
throw new Error(`router(${prefix}) returned undefined`);
}
return r;
}