forked from single-spa/single-spa
-
Notifications
You must be signed in to change notification settings - Fork 2
/
navigation-events.js
168 lines (144 loc) · 5.62 KB
/
navigation-events.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
import { reroute } from './reroute.js';
import { find } from '../utils/find.js';
/* We capture navigation event listeners so that we can make sure
* that application navigation listeners are not called until
* single-spa has ensured that the correct applications are
* unmounted and mounted.
*/
const capturedEventListeners = {
hashchange: [],
popstate: [],
};
export const routingEventsListeningTo = ['hashchange', 'popstate'];
export function navigateToUrl(obj, opts = {}) {
let url;
if (typeof obj === 'string') {
url = obj;
} else if (this && this.href) {
url = this.href;
} else if (obj && obj.currentTarget && obj.currentTarget.href && obj.preventDefault) {
url = obj.currentTarget.href;
obj.preventDefault();
} else {
throw Error(`singleSpaNavigate must be either called with a string url, with an <a> tag as its context, or with an event whose currentTarget is an <a> tag`);
}
const current = parseUri(window.location.href);
const destination = parseUri(url);
if (url.indexOf('#') === 0) {
window.location.hash = '#' + destination.anchor;
} else if (current.host !== destination.host && destination.host) {
if (opts.isTestingEnv) {
return { wouldHaveReloadedThePage: true };
} else {
window.location.href = url;
}
} else if (!isSamePath(destination.path + "?" + destination.query, current.path + "?" + current.query)) {
// different path, host, or query params
window.history.pushState(null, null, url);
} else {
window.location.hash = '#' + destination.anchor;
}
function isSamePath(destination, current) {
// if the destination has a path but no domain, it doesn't include the root '/'
return current === destination || current === '/' + destination;
}
}
export function callCapturedEventListeners(eventArguments) {
if (eventArguments) {
const eventType = eventArguments[0].type;
if (routingEventsListeningTo.indexOf(eventType) >= 0) {
capturedEventListeners[eventType].forEach(listener => {
listener.apply(this, eventArguments);
});
}
}
}
function urlReroute() {
reroute([], arguments)
}
// We will trigger an app change for any routing events.
window.addEventListener('hashchange', urlReroute);
window.addEventListener('popstate', (args) => {
urlReroute(args);
});
// Monkeypatch addEventListener so that we can ensure correct timing
const originalAddEventListener = window.addEventListener;
const originalRemoveEventListener = window.removeEventListener;
window.addEventListener = function (eventName, fn) {
if (typeof fn === 'function') {
if (routingEventsListeningTo.indexOf(eventName) >= 0 && !find(capturedEventListeners[eventName], listener => listener === fn)) {
capturedEventListeners[eventName].push(fn);
return;
}
}
return originalAddEventListener.apply(this, arguments);
}
window.removeEventListener = function (eventName, listenerFn) {
if (typeof listenerFn === 'function') {
if (routingEventsListeningTo.indexOf(eventName) >= 0) {
capturedEventListeners[eventName] = capturedEventListeners[eventName].filter(fn => fn !== listenerFn);
return;
}
}
return originalRemoveEventListener.apply(this, arguments);
}
const originalPushState = window.history.pushState;
window.history.pushState = function (state) {
const result = originalPushState.apply(this, arguments);
urlReroute(createPopStateEvent(state));
return result;
}
const originalReplaceState = window.history.replaceState;
window.history.replaceState = function (state) {
const result = originalReplaceState.apply(this, arguments);
setTimeout(() => {
urlReroute(createPopStateEvent(state));
}, 50);
return result;
}
function createPopStateEvent(state) {
// https://github.com/CanopyTax/single-spa/issues/224 and https://github.com/CanopyTax/single-spa-angular/issues/49
// We need a popstate event even though the browser doesn't do one by default when you call replaceState, so that
// all the applications can reroute.
try {
return new PopStateEvent('popstate', { state });
} catch (err) {
// IE 11 compatibility https://github.com/CanopyTax/single-spa/issues/299
// https://docs.microsoft.com/en-us/openspecs/ie_standards/ms-html5e/bd560f47-b349-4d2c-baa8-f1560fb489dd
const evt = document.createEvent('PopStateEvent');
evt.initPopStateEvent('popstate', false, false, state);
return evt;
}
}
/* For convenience in `onclick` attributes, we expose a global function for navigating to
* whatever an <a> tag's href is.
*/
window.singleSpaNavigate = navigateToUrl;
function parseUri(str) {
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
// http://blog.stevenlevithan.com/archives/parseuri
const parseOptions = {
strictMode: true,
key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};
let o = parseOptions;
let m = o.parser[o.strictMode ? "strict" : "loose"].exec(str);
let uri = {};
let i = 14;
while (i--) uri[o.key[i]] = m[i] || "";
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) uri[o.q.name][$1] = $2;
});
return uri;
}