Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80684 views
1
"use strict";
2
3
var URL = require('url');
4
5
function StateEntry(data, title, url) {
6
this.data = data;
7
this.title = title;
8
this.url = url;
9
}
10
11
module.exports = History;
12
13
function History(window) {
14
this._states = [];
15
this._index = -1;
16
this._window = window;
17
this._location = window.location;
18
}
19
20
History.prototype = {
21
constructor: History,
22
23
get length() {
24
return this._states.length;
25
},
26
27
get state() {
28
var state = this._states[this._index];
29
return state ? state.data : null;
30
},
31
32
back: function () {
33
this.go(-1);
34
},
35
36
forward: function () {
37
this.go(1);
38
},
39
40
go: function (delta) {
41
if (typeof delta === "undefined" || delta === 0) {
42
this._location.reload();
43
return;
44
}
45
46
var newIndex = this._index + delta;
47
48
if (newIndex < 0 || newIndex >= this.length) {
49
return;
50
}
51
52
this._index = newIndex;
53
this._applyState(this._states[this._index]);
54
},
55
56
pushState: function (data, title, url) {
57
var state = new StateEntry(data, title, url);
58
if (this._index + 1 !== this._states.length) {
59
this._states = this._states.slice(0, this._index + 1);
60
}
61
this._states.push(state);
62
this._applyState(state);
63
this._index++;
64
},
65
66
replaceState: function (data, title, url) {
67
var state = new StateEntry(data, title, url);
68
this._states[this._index] = state;
69
this._applyState(state);
70
},
71
72
_applyState: function(state) {
73
this._location._url = URL.parse(URL.resolve(this._location._url.href, state.url));
74
75
this._signalPopstate(state);
76
},
77
78
_signalPopstate: function(state) {
79
if (this._window.document) {
80
var ev = this._window.document.createEvent("HTMLEvents");
81
ev.initEvent("popstate", false, false);
82
ev.state = state.data;
83
process.nextTick(function () {
84
this._window.dispatchEvent(ev);
85
}.bind(this));
86
}
87
},
88
89
toString: function () {
90
return "[object History]";
91
}
92
};
93
94