/
index.js
83 lines (69 loc) · 2.3 KB
/
index.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
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var randomKey = function randomKey(keyLength) {
return Math.random().toString(36).substr(2, keyLength);
};
var createDefaultMatch = function createDefaultMatch() {
return { path: '/', url: '/', isExact: true, params: {} };
};
var createDefaultLocation = function createDefaultLocation() {
return { pathname: '/', search: '', hash: '', key: randomKey(6) };
};
var createDefaultHistory = function createDefaultHistory(location) {
return {
action: 'POP',
location: location || createDefaultLocation(),
_listeners: [],
listen: function listen(fn) {
var _this = this;
this._listeners.push(fn);
return function () {
_this._listeners = _this._listeners.filter(function (func) {
return func !== fn;
});
};
},
push: function push(location) {
this._notifyListeners(location);
},
replace: function replace(location) {
this._notifyListeners(location);
},
_notifyListeners: function _notifyListeners(loc) {
this._listeners.forEach(function (fn) {
fn(loc);
});
},
createHref: function createHref(loc) {
if (typeof loc === 'string') {
return loc;
} else {
return loc.pathname + (loc.search || '') + (loc.hash || '');
}
}
};
};
var createRouterContext = function createRouterContext() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var userHistory = options.history,
userLocation = options.location,
userMatch = options.match,
staticContext = options.staticContext;
var match = _extends({}, createDefaultMatch(), userMatch);
var location = _extends({}, createDefaultLocation(), userLocation);
var history = _extends({}, createDefaultHistory(location), userHistory);
return {
router: {
history: history,
route: {
match: match,
location: location
},
staticContext: staticContext
}
};
};
exports.default = createRouterContext;