-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.js
134 lines (105 loc) · 2.77 KB
/
route.js
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import { define, Component } from '@xinix/xin';
import { Router } from './router';
export class Route extends Component {
static routeRegExp (str) {
const chunks = str.split('[');
if (chunks.length > 2) {
throw new Error('Invalid use of optional params');
}
const tokens = [];
const re = chunks[0].replace(/{([^}]+)}/g, function (g, token) {
tokens.push(token);
return '([^/]+)';
}).replace(/\//g, '\\/');
let optRe = '';
if (chunks[1]) {
optRe = '(?:' + chunks[1].slice(0, -1).replace(/{([^}]+)}/g, function (g, token) {
const [realToken, re = '[^/]+'] = token.split(':');
tokens.push(realToken);
return `(${re})`;
}).replace(/\//g, '\\/') + ')?';
}
return [new RegExp('^' + re + optRe + '$'), tokens];
}
static isStatic (pattern) {
return !pattern.match(/[[{]/);
}
get props () {
return {
...super.props,
uri: {
type: String,
observer: '__routeObserveUri(uri)',
required: true,
},
view: {
type: String,
},
};
}
get routers () {
return this.__routeViewElement.routers;
}
attached () {
super.attached();
this.fire('route-attach');
}
detached () {
super.detached();
this.fire('route-detach');
}
__routeObserveUri (uri) {
if (Route.isStatic(uri)) {
this.type = 's';
this.pattern = null;
this.args = [];
} else {
const [pattern, args] = Route.routeRegExp(uri);
this.type = 'v';
this.pattern = pattern;
this.args = args;
}
}
__routeExtractSegmentParameters (uri) {
const result = uri.match(this.pattern);
if (!result) {
return {};
}
return this.args.reduce((args, name, index) => {
args[name] = result[index + 1];
return args;
}, {});
}
__componentInitTemplate () {
this.__routeTemplate = this.firstElementChild;
if (this.__routeTemplate) {
this.removeChild(this.__routeTemplate);
}
this.__templateInitialize(undefined, this.props);
}
test (uri) {
return (this.type === 's' && this.uri === uri) || (this.type === 'v' && uri.match(this.pattern));
}
async enter (ctx) {
if (!this.__routeViewElement) {
if (this.view) {
await Router.prepare(this.view);
}
const viewEl = document.createElement(this.view || 'xin-view');
if (!this.view) {
viewEl.template = this.__routeTemplate;
}
this.__routeViewElement = viewEl;
}
ctx = ctx.for(this);
await this.__routeViewElement.__viewEnter(this, ctx);
}
async leave () {
if (!this.__routeViewElement) {
return;
}
await this.__routeViewElement.__viewLeave(this);
this.__routeViewElement = undefined;
}
}
define('xin-route', Route);