forked from freeCodeCamp/devdocs
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpage.js
More file actions
357 lines (313 loc) · 7.85 KB
/
page.js
File metadata and controls
357 lines (313 loc) · 7.85 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*
* Based on github.com/visionmedia/page.js
* Licensed under the MIT license
* Copyright 2012 TJ Holowaychuk <tj@vision-media.ca>
*/
let running = false;
let currentState = null;
const callbacks = [];
this.page = function (value, fn) {
if (typeof value === "function") {
page("*", value);
} else if (typeof fn === "function") {
const route = new Route(value);
callbacks.push(route.middleware(fn));
} else if (typeof value === "string") {
page.show(value, fn);
} else {
page.start(value);
}
};
page.start = function (options) {
if (options == null) {
options = {};
}
if (!running) {
running = true;
addEventListener("popstate", onpopstate);
addEventListener("click", onclick);
page.replace(currentPath(), null, null, true);
}
};
page.stop = function () {
if (running) {
running = false;
removeEventListener("click", onclick);
removeEventListener("popstate", onpopstate);
}
};
page.show = function (path, state) {
if (path === currentState?.path) {
return;
}
const context = new Context(path, state);
const previousState = currentState;
currentState = context.state;
const res = page.dispatch(context);
if (res) {
currentState = previousState;
location.assign(res);
} else {
context.pushState();
updateCanonicalLink();
track();
}
return context;
};
page.replace = function (path, state, skipDispatch, init) {
let result;
let context = new Context(path, state || currentState);
context.init = init;
currentState = context.state;
if (!skipDispatch) {
result = page.dispatch(context);
}
if (result) {
context = new Context(result);
context.init = init;
currentState = context.state;
page.dispatch(context);
}
context.replaceState();
updateCanonicalLink();
if (!skipDispatch) {
track();
}
return context;
};
page.dispatch = function (context) {
let i = 0;
const next = function () {
let fn = callbacks[i++];
return fn?.(context, next);
};
return next();
};
page.canGoBack = () => !Context.isIntialState(currentState);
page.canGoForward = () => !Context.isLastState(currentState);
const currentPath = () => location.pathname + location.search + location.hash;
class Context {
/**
* A counter tracking the largest state ID used.
*/
static stateId = 0;
/**
* The session ID to apply across all contexts.
*/
static sessionId = Date.now();
static isIntialState(state) {
return state.id === 0;
}
static isLastState(state) {
return state.id === Context.stateId - 1;
}
static isInitialPopState(state) {
return state.path === this.initialPath && Context.stateId === 1;
}
static isSameSession(state) {
return state.sessionId === Context.sessionId;
}
constructor(path, state) {
this.initialPath = currentPath();
if (path == null) {
path = "/";
}
this.path = path;
if (state == null) {
state = {};
}
this.state = state;
this.pathname = this.path.replace(
/(?:\?([^#]*))?(?:#(.*))?$/,
(_, query, hash) => {
this.query = query;
this.hash = hash;
return "";
},
);
if (this.state.id == null) {
Context.stateId++;
this.state.id = Context.stateId;
}
if (this.state.sessionId == null) {
this.state.sessionId = Context.sessionId;
}
this.state.path = this.path;
}
pushState() {
history.pushState(this.state, "", this.path);
}
replaceState() {
try {
history.replaceState(this.state, "", this.path);
} catch (error) {} // NS_ERROR_FAILURE in Firefox
}
}
class Route {
constructor(path, options) {
this.path = path;
if (options == null) {
options = {};
}
this.keys = [];
this.regexp = pathToRegexp(this.path, this.keys);
}
middleware(fn) {
return (context, next) => {
let params = [];
if (this.match(context.pathname, params)) {
context.params = params;
return fn(context, next);
} else {
return next();
}
};
}
match(path, params) {
const matchData = this.regexp.exec(path);
if (!matchData) {
return;
}
const iterable = matchData.slice(1);
for (let i = 0; i < iterable.length; i++) {
var key = this.keys[i];
var value = iterable[i];
if (typeof value === "string") {
value = decodeURIComponent(value);
}
if (key) {
params[key.name] = value;
} else {
params.push(value);
}
}
return true;
}
}
var pathToRegexp = function (path, keys) {
if (path instanceof RegExp) {
return path;
}
if (path instanceof Array) {
path = `(${path.join("|")})`;
}
path = path
.replace(/\/\(/g, "(?:/")
.replace(
/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g,
(_, slash, format, key, capture, optional) => {
if (slash == null) {
slash = "";
}
if (format == null) {
format = "";
}
keys.push({ name: key, optional: !!optional });
let str = optional ? "" : slash;
str += "(?:";
if (optional) {
str += slash;
}
str += format;
str += capture || (format ? "([^/.]+?)" : "([^/]+?)");
str += ")";
if (optional) {
str += optional;
}
return str;
},
)
.replace(/([\/.])/g, "\\$1")
.replace(/\*/g, "(.*)");
return new RegExp(`^${path}$`);
};
var onpopstate = function (event) {
if (!event.state || Context.isInitialPopState(event.state)) {
return;
}
if (Context.isSameSession(event.state)) {
page.replace(event.state.path, event.state);
} else {
location.reload();
}
};
var onclick = function (event) {
try {
if (
event.which !== 1 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.defaultPrevented
) {
return;
}
} catch (error) {
return;
}
let link = $.eventTarget(event);
while (link && !(link.tagName === "A" || link.tagName === "a")) {
link = link.parentNode;
}
if (!link) return;
// If the `<a>` is in an SVG, its attributes are `SVGAnimatedString`s
// instead of strings
let href = link.href instanceof SVGAnimatedString
? new URL(link.href.baseVal, location.href).href
: link.href;
let target = link.target instanceof SVGAnimatedString
? link.target.baseVal
: link.target;
if (!target && isSameOrigin(href)) {
event.preventDefault();
let parsedHref = new URL(href);
let path = parsedHref.pathname + parsedHref.search + parsedHref.hash;
path = path.replace(/^\/\/+/, "/"); // IE11 bug
page.show(path);
}
};
var isSameOrigin = (url) =>
url.startsWith(`${location.protocol}//${location.hostname}`);
var updateCanonicalLink = function () {
if (!this.canonicalLink) {
this.canonicalLink = document.head.querySelector('link[rel="canonical"]');
}
return this.canonicalLink.setAttribute(
"href",
`https://${location.host}${location.pathname}`,
);
};
const trackers = [];
page.track = function (fn) {
trackers.push(fn);
};
var track = function () {
if (app.config.env !== "production") {
return;
}
if (navigator.doNotTrack === "1") {
return;
}
if (navigator.globalPrivacyControl) {
return;
}
const consentGiven = Cookies.get("analyticsConsent");
const consentAsked = Cookies.get("analyticsConsentAsked");
if (consentGiven === "1") {
for (var tracker of trackers) {
tracker.call();
}
} else if (consentGiven === undefined && consentAsked === undefined) {
// Only ask for consent once per browser session
Cookies.set("analyticsConsentAsked", "1");
new app.views.Notif("AnalyticsConsent", { autoHide: null });
}
};
this.resetAnalytics = function () {
for (var cookie of document.cookie.split(/;\s?/)) {
var name = cookie.split("=")[0];
if (name[0] === "_" && name[1] !== "_") {
Cookies.expire(name);
}
}
};