-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathutil.js
74 lines (67 loc) · 1.84 KB
/
util.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
//a key for the context to carry baseUrl to nested Router instances
export const CONTEXT_KEY = 'preact-router-base';
const EMPTY = {};
export function assign(obj, props) {
// eslint-disable-next-line guard-for-in
for (let i in props) {
obj[i] = props[i];
}
return obj;
}
export function exec(url, route, opts=EMPTY) {
let reg = /(?:\?([^#]*))?(#.*)?$/,
c = url.match(reg),
matches = {},
ret;
if (c && c[1]) {
let p = c[1].split('&');
for (let i=0; i<p.length; i++) {
let r = p[i].split('=');
matches[decodeURIComponent(r[0])] = decodeURIComponent(r.slice(1).join('='));
}
}
url = segmentize(url.replace(reg, ''));
route = segmentize(route || '');
let max = Math.max(url.length, route.length);
for (let i=0; i<max; i++) {
if (route[i] && route[i].charAt(0)===':') {
let param = route[i].replace(/(^\:|[+*?]+$)/g, ''),
flags = (route[i].match(/[+*?]+$/) || EMPTY)[0] || '',
plus = ~flags.indexOf('+'),
star = ~flags.indexOf('*'),
val = url[i] || '';
if (!val && !star && (flags.indexOf('?')<0 || plus)) {
ret = false;
break;
}
matches[param] = decodeURIComponent(val);
if (plus || star) {
matches[param] = url.slice(i).map(decodeURIComponent).join('/');
break;
}
}
else if (route[i]!==url[i]) {
ret = false;
break;
}
}
if (opts.default!==true && ret===false) return false;
return matches;
}
export function pathRankSort(a, b) {
let aAttr = a.attributes || EMPTY,
bAttr = b.attributes || EMPTY;
if (aAttr.default) return 1;
if (bAttr.default) return -1;
let diff = rank(aAttr.path) - rank(bAttr.path);
return diff || (aAttr.path.length - bAttr.path.length);
}
export function segmentize(url) {
return strip(url).split('/');
}
export function rank(url) {
return (strip(url).match(/\/+/g) || '').length;
}
export function strip(url) {
return url.replace(/(^\/+|\/+$)/g, '');
}