-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.js
321 lines (248 loc) · 6.87 KB
/
router.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import { define, Component, Repository, event } from '@xinix/xin'; // eslint-disable-line max-lines
import { Context } from './context';
const debug = require('debug')('xin-router:router');
let loaders = [];
export class Router extends Component {
static prepare (view) {
const repo = Repository.singleton();
if (repo.get(view)) {
return;
}
Router.init();
for (const loader of loaders) {
if (view.match(loader.test)) {
return loader.load(view);
}
}
}
static addLoader (loader) {
Router.init();
const index = loaders.indexOf(loader);
if (index === -1) {
loaders.push(loader);
}
}
static removeLoader (loader) {
Router.init();
const index = loaders.indexOf(loader);
if (index !== -1) {
loaders.splice(index, 1);
}
}
static init (reset) {
if (reset) {
loaders = [];
}
if (loaders.length === 0) {
const repo = Repository.singleton();
const repoLoaders = repo.get('view.loaders');
if (repoLoaders && repoLoaders.length) {
loaders.push(...repoLoaders);
}
}
}
get props () {
return {
...super.props,
mode: {
type: String,
value: 'hash',
},
manual: {
type: Boolean,
value: false,
},
hash: {
type: String,
value: '#!',
},
rootUri: {
type: String,
value: '/',
},
location: {
type: Object,
value: () => window.location,
},
history: {
type: Object,
value: () => window.history,
},
};
}
get hashRegexp () {
if (!this.__routerHashRegexp || this.__routerHash !== this.hash) {
this.__routerHashRegexp = new RegExp(`${this.hash}(.*)$`);
this.__routerHash = this.hash;
}
return this.__routerHashRegexp;
}
getUri (location) {
try {
let uri;
if (this.mode === 'history') {
uri = decodeURI(location.pathname + location.search);
uri = uri.replace(/\?(.*)$/, '');
uri = this.rootUri === '/' ? uri : uri.replace(this.rootUri, '');
} else {
const match = location.href.match(this.hashRegexp);
uri = match ? match[1] : '';
}
return '/' + uri.toString().replace(/\/$/, '').replace(/^\//, '');
} catch (err) {
console.error('Fragment is not match any pattern, fallback to /');
console.error(err);
return '/';
}
}
created () {
this.middlewares = [];
this.routes = [];
}
async attached () {
super.attached();
this.__routerIsRoot = Boolean(!this.parentElement.closest('xin-router'));
this.routes = [...this.querySelectorAll('xin-route')];
await Promise.all(this.routes.map(async route => {
await event(route).waitFor('route-attach');
}));
this.fire('router-attach');
if (!this.manual) {
this.start();
}
}
detached () {
super.detached();
this.stop();
this.__routerIsRoot = undefined;
}
use (middleware) {
this.middlewares.push(middleware);
}
async start () {
if (!this.__routerIsRoot) {
return;
}
if (debug.enabled) debug(`Starting ${this.is}:${this.__id} ...`);
this.__routerListen();
const uri = this.getUri(this.location);
await this.__routerDispatch(new Context({ uri }));
}
stop () {
if (!this.__routerIsRoot) {
return;
}
if (debug.enabled) debug(`Stopping ${this.is}:${this.__id} ...`);
this.__middlewareChain = undefined;
this.__routerUnlisten();
}
async push (uri, navParameters) {
if (debug.enabled) debug(`Push ${this.is}:${this.__id} %s`, uri);
if (this.currentUri === uri) {
return;
}
const url = this.mode === 'history'
? this.rootUri + uri.toString().replace(/\/$/, '').replace(/^\//, '')
: this.hash + uri;
this.history.pushState(navParameters, document.title, url);
await this.__routerDispatch(new Context({ uri, navParameters }));
}
async replace (uri, navParameters) {
if (debug.enabled) debug(`Replace ${this.is}:${this.__id} %s`, uri);
if (this.currentUri === uri) {
return;
}
const url = this.mode === 'history'
? this.rootUri + uri.toString().replace(/\/$/, '').replace(/^\//, '')
: this.hash + uri;
this.history.replaceState(navParameters, document.title, url);
await this.__routerDispatch(new Context({ uri, navParameters }));
}
async go (delta) {
if (!delta) {
return;
}
this.history.go(delta);
await this.waitFor('router-dispatch');
}
__routerListen () {
this.__routerPopstateListener = async () => {
const uri = this.getUri(this.location);
await this.__routerDispatch(new Context({ uri }));
};
this.__routerClickListener = evt => {
if (!evt.defaultPrevented && evt.target.nodeName === 'A' && evt.target.target === '') {
evt.preventDefault();
const target = evt.target;
let href = target.getAttribute('href');
if (href.startsWith(this.hash)) {
href = href.split(this.hash).pop();
}
this.push(href);
}
};
event(window).on('popstate', this.__routerPopstateListener);
event(document).on('click', this.__routerClickListener);
}
__routerUnlisten () {
if (!this.__routerPopstateListener) {
return;
}
event(window).off('popstate', this.__routerPopstateListener);
event(document).off('click', this.__routerClickListener);
}
async __routerDispatch (ctx) {
if (!this.__middlewareChain) {
this.__middlewareChain = compose(this.middlewares);
}
this.currentUri = ctx.uri;
ctx = ctx.shift(this);
if (debug.enabled) debug(`Dispatching ${this.is}:${this.__id} with ctx: %O`, ctx);
await this.__middlewareChain(ctx, async () => {
await this.__routerRoute(ctx);
});
this.fire('router-dispatch', ctx);
}
async __routerRoute (ctx) {
const routes = [];
await Promise.all(this.routes.map(async route => {
if (route.test(ctx.pathname)) {
await route.enter(ctx);
routes.push(route);
} else {
await route.leave();
}
}));
if (!routes.length) {
throw new Error(`Route not found! (uri:${ctx.originalUri})`);
}
return routes;
}
}
define('xin-router', Router);
function compose (middlewares) {
for (const fn of middlewares) {
if (typeof fn !== 'function') {
throw new TypeError('Middleware must be composed of functions!');
}
}
return (context, next) => {
// last called middlewares #
let index = -1;
function dispatch (i) {
if (i <= index) {
throw new Error('next() called multiple times');
}
index = i;
let fn = middlewares[i];
if (i === middlewares.length) {
fn = next;
}
if (!fn) {
return;
}
return fn(context, () => dispatch(i + 1));
}
return dispatch(0);
};
}