-
Notifications
You must be signed in to change notification settings - Fork 184
/
utils.js
executable file
·278 lines (251 loc) · 8.02 KB
/
utils.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
/**
* Adapted from https://github.com/reach/router/blob/b60e6dd781d5d3a4bdaaf4de665649c0f6a7e78d/src/lib/utils.js
* https://github.com/reach/router/blob/master/LICENSE
*/
const PARAM = /^:(.+)/;
const SEGMENT_POINTS = 4;
const STATIC_POINTS = 3;
const DYNAMIC_POINTS = 2;
const SPLAT_PENALTY = 1;
const ROOT_POINTS = 1;
/**
* Split up the URI into segments delimited by `/`
* Strip starting/ending `/`
* @param {string} uri
* @return {string[]}
*/
const segmentize = (uri) => uri.replace(/(^\/+|\/+$)/g, "").split("/");
/**
* Strip `str` of potential start and end `/`
* @param {string} string
* @return {string}
*/
const stripSlashes = (string) => string.replace(/(^\/+|\/+$)/g, "");
/**
* Score a route depending on how its individual segments look
* @param {object} route
* @param {number} index
* @return {object}
*/
const rankRoute = (route, index) => {
const score = route.default
? 0
: segmentize(route.path).reduce((score, segment) => {
score += SEGMENT_POINTS;
if (segment === "") {
score += ROOT_POINTS;
} else if (PARAM.test(segment)) {
score += DYNAMIC_POINTS;
} else if (segment[0] === "*") {
score -= SEGMENT_POINTS + SPLAT_PENALTY;
} else {
score += STATIC_POINTS;
}
return score;
}, 0);
return { route, score, index };
};
/**
* Give a score to all routes and sort them on that
* If two routes have the exact same score, we go by index instead
* @param {object[]} routes
* @return {object[]}
*/
const rankRoutes = (routes) =>
routes
.map(rankRoute)
.sort((a, b) =>
a.score < b.score ? 1 : a.score > b.score ? -1 : a.index - b.index
);
/**
* Ranks and picks the best route to match. Each segment gets the highest
* amount of points, then the type of segment gets an additional amount of
* points where
*
* static > dynamic > splat > root
*
* This way we don't have to worry about the order of our routes, let the
* computers do it.
*
* A route looks like this
*
* { path, default, value }
*
* And a returned match looks like:
*
* { route, params, uri }
*
* @param {object[]} routes
* @param {string} uri
* @return {?object}
*/
const pick = (routes, uri) => {
let match;
let default_;
const [uriPathname] = uri.split("?");
const uriSegments = segmentize(uriPathname);
const isRootUri = uriSegments[0] === "";
const ranked = rankRoutes(routes);
for (let i = 0, l = ranked.length; i < l; i++) {
const route = ranked[i].route;
let missed = false;
if (route.default) {
default_ = {
route,
params: {},
uri,
};
continue;
}
const routeSegments = segmentize(route.path);
const params = {};
const max = Math.max(uriSegments.length, routeSegments.length);
let index = 0;
for (; index < max; index++) {
const routeSegment = routeSegments[index];
const uriSegment = uriSegments[index];
if (routeSegment && routeSegment[0] === "*") {
// Hit a splat, just grab the rest, and return a match
// uri: /files/documents/work
// route: /files/* or /files/*splatname
const splatName =
routeSegment === "*" ? "*" : routeSegment.slice(1);
params[splatName] = uriSegments
.slice(index)
.map(decodeURIComponent)
.join("/");
break;
}
if (typeof uriSegment === "undefined") {
// URI is shorter than the route, no match
// uri: /users
// route: /users/:userId
missed = true;
break;
}
const dynamicMatch = PARAM.exec(routeSegment);
if (dynamicMatch && !isRootUri) {
const value = decodeURIComponent(uriSegment);
params[dynamicMatch[1]] = value;
} else if (routeSegment !== uriSegment) {
// Current segments don't match, not dynamic, not splat, so no match
// uri: /users/123/settings
// route: /users/:id/profile
missed = true;
break;
}
}
if (!missed) {
match = {
route,
params,
uri: "/" + uriSegments.slice(0, index).join("/"),
};
break;
}
}
return match || default_ || null;
};
/**
* Add the query to the pathname if a query is given
* @param {string} pathname
* @param {string} [query]
* @return {string}
*/
const addQuery = (pathname, query) => pathname + (query ? `?${query}` : "");
/**
* Resolve URIs as though every path is a directory, no files. Relative URIs
* in the browser can feel awkward because not only can you be "in a directory",
* you can be "at a file", too. For example:
*
* browserSpecResolve('foo', '/bar/') => /bar/foo
* browserSpecResolve('foo', '/bar') => /foo
*
* But on the command line of a file system, it's not as complicated. You can't
* `cd` from a file, only directories. This way, links have to know less about
* their current path. To go deeper you can do this:
*
* <Link to="deeper"/>
* // instead of
* <Link to=`{${props.uri}/deeper}`/>
*
* Just like `cd`, if you want to go deeper from the command line, you do this:
*
* cd deeper
* # not
* cd $(pwd)/deeper
*
* By treating every path as a directory, linking to relative paths should
* require less contextual information and (fingers crossed) be more intuitive.
* @param {string} to
* @param {string} base
* @return {string}
*/
const resolve = (to, base) => {
// /foo/bar, /baz/qux => /foo/bar
if (to.startsWith("/")) return to;
const [toPathname, toQuery] = to.split("?");
const [basePathname] = base.split("?");
const toSegments = segmentize(toPathname);
const baseSegments = segmentize(basePathname);
// ?a=b, /users?b=c => /users?a=b
if (toSegments[0] === "") return addQuery(basePathname, toQuery);
// profile, /users/789 => /users/789/profile
if (!toSegments[0].startsWith(".")) {
const pathname = baseSegments.concat(toSegments).join("/");
return addQuery((basePathname === "/" ? "" : "/") + pathname, toQuery);
}
// ./ , /users/123 => /users/123
// ../ , /users/123 => /users
// ../.. , /users/123 => /
// ../../one, /a/b/c/d => /a/b/one
// .././one , /a/b/c/d => /a/b/c/one
const allSegments = baseSegments.concat(toSegments);
const segments = [];
allSegments.forEach((segment) => {
if (segment === "..") segments.pop();
else if (segment !== ".") segments.push(segment);
});
return addQuery("/" + segments.join("/"), toQuery);
};
/**
* Combines the `basepath` and the `path` into one path.
* @param {string} basepath
* @param {string} path
*/
const combinePaths = (basepath, path) =>
`${stripSlashes(
path === "/"
? basepath
: `${stripSlashes(basepath)}/${stripSlashes(path)}`
)}/`;
/**
* Decides whether a given `event` should result in a navigation or not.
* @param {object} event
*/
const shouldNavigate = (event) =>
!event.defaultPrevented &&
event.button === 0 &&
!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
// svelte seems to kill anchor.host value in ie11, so fall back to checking href
const hostMatches = (anchor) => {
const host = location.host;
return (
anchor.host === host ||
anchor.href.indexOf(`https://${host}`) === 0 ||
anchor.href.indexOf(`http://${host}`) === 0
);
};
const canUseDOM = () =>
typeof window !== "undefined" &&
"document" in window &&
"location" in window;
export {
stripSlashes,
pick,
resolve,
combinePaths,
shouldNavigate,
hostMatches,
canUseDOM,
};