-
Notifications
You must be signed in to change notification settings - Fork 3
/
Route.js
88 lines (72 loc) · 1.61 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
import pathToRegexp from 'path-to-regexp';
import URL from 'url-parse';
import {EventEmitter} from './EventEmitter';
export class Route extends EventEmitter {
/**
* @param {string} path
* @param {string} name?
* @param {Function} onBeforeEnter?
* @param {Function} onEnter?
* @param {Function} onLeave?
* @param {Object} options?
*/
constructor({path, name, onBeforeEnter, onEnter, onLeave, options} = {}) {
super();
this.path = path;
this.name = name;
this.paramsInfo = [];
this.regexp = pathToRegexp(path, this.paramsInfo, options);
this.compiled = pathToRegexp.compile(path);
this.handlers = {
beforeEnter: [],
enter: [],
leave: [],
};
if (onBeforeEnter) {
this.on('beforeEnter', onBeforeEnter);
}
if (onEnter) {
this.on('enter', onEnter);
}
if (onLeave) {
this.on('leave', onLeave);
}
}
/**
* @param {string} path
* @returns {Object|boolean}
*/
execPath(path) {
let match = this.regexp.exec(path);
if (!match) {
return false;
}
let params = {};
this.paramsInfo.forEach((paramInfo, index) => {
params[paramInfo.name] = match[index + 1];
});
return params;
}
/**
* @param {Object} params?
* @param {Object} query?
* @param {string} hash?
* @returns {string}
*/
generatePath({params, query, hash} = {}) {
let path = this.compiled(params);
let url = new URL(path, true);
if (query) {
Object.keys(query).forEach((key) => {
url.query[key] = query[key];
});
}
if (hash) {
if (!hash.startsWith('#')) {
hash = `#${hash}`;
}
url.hash = hash;
}
return url.toString().replace(url.origin, '');
}
}