-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.js
70 lines (60 loc) · 1.66 KB
/
context.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
import qs from 'querystring';
import { Route } from './route'; // eslint-disable-line no-unused-vars
const URL = window.URL;
export class Context {
constructor (ctx) {
if (ctx instanceof Context) {
this.originalUri = ctx.originalUri;
this.uri = ctx.uri;
this.pathname = ctx.pathname;
this.search = ctx.search;
this.queryParameters = ctx.queryParameters;
} else {
this.originalUri = ctx.originalUri || ctx.uri;
this._setUri(ctx.uri);
}
this.navParameters = { ...ctx.navParameters };
this.routeParameters = { ...ctx.routeParameters };
}
get parameters () {
return {
...this.routeParameters,
...this.queryParameters,
...this.navParameters,
};
}
_setUri (uri) {
this.uri = uri;
let { pathname, search } = new URL(uri, 'http://localhost');
if (search[0] === '?') {
search = search.substr(1);
}
this.pathname = pathname;
this.search = search;
this.queryParameters = qs.parse(search);
}
withUri (uri) {
const ctx = new Context(this);
ctx._setUri(uri);
return ctx;
}
shift (router) {
const { uri } = this;
if (!uri.startsWith(router.rootUri)) {
throw new Error(`Context not eligible for ${router.is}:${router.__id} with rootUri:${router.rootUri}`);
}
return this.withUri(router.rootUri === '/' ? uri : uri.substr(router.rootUri.length));
}
/**
* Copy context for specific route
* @param {Route} route
*/
for (route) {
const ctx = new Context(this);
ctx.routeParameters = {
...this.routeParameters,
...route.__routeExtractSegmentParameters(this.pathname),
};
return ctx;
}
}