-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbacktrack.js
117 lines (102 loc) · 3.02 KB
/
backtrack.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
/**
* Backtrack 2.0.2
* Copyright © Zaim Ramlan
*/
class Backtrack {
/**
* Initializes an instance of Backtrack.
*
* @constructor
* @author: Zaim Ramlan
* @param {string} backButtonId The `id` property of the back button.
*/
constructor(backButtonId) {
this._storageKey = 'backtracks';
this._backButtonId = backButtonId;
}
/**
* Configures the back button to execute `popPage()` on keyUp and
* sets its href property.
*
* assumptions:
* 1) Back link is a `<a href=""></a>`
* 2) Back link has the id stored in `_backButtonId`
*
* i.e.
* <a id="back_button" href="">Back</a>
*/
configureBackButton() {
var backButton = document.getElementById(this._backButtonId);
var url = this._getBackButtonURL();
var _this = this;
if (backButton !== null) {
if (url !== '') backButton.href = url;
backButton.onmouseup = function() { _this.popPage(); };
}
}
/**
* Pushes the current page into the history stack if it's not already in.
*/
pushPage() {
var currentPage = location.href;
var pages = this._getStoredPages();
var previousPageIndex = pages.length - 1;
var previousPage = pages[previousPageIndex];
if (currentPage !== previousPage) {
pages.push(currentPage);
this._setToStore(pages);
}
}
/**
* Removes the last page in the history stack.
*/
popPage() {
var pages = this._getStoredPages();
pages.pop();
this._setToStore(pages);
}
/**
* Removes all stored pages.
*/
removeAllPages() {
sessionStorage.removeItem(this._storageKey);
}
/**
* Returns the page, before the current page, as the link to go back.
*
* @return {string} The previous page URL visited by the user, or
* an empty string if there was no (or only one) stored page(s).
*/
_getBackButtonURL() {
var pages = this._getStoredPages();
if (pages.length <= 1) return '';
var secondLastIndex = pages.length - 2;
var secondLastPage = pages[secondLastIndex];
var lastIndex = pages.length - 1;
var lastPage = pages[lastIndex];
var currentPage = location.href;
var previousPage = currentPage === lastPage ? secondLastPage : lastPage;
return previousPage;
}
/**
* Get the stored pages.
*
* @return {array} An array of stored pages, or an empty array it's not present.
*/
_getStoredPages() {
var pages = sessionStorage.getItem(this._storageKey);
if (pages !== null && pages !== '') {
return pages.split(',');
}
return [];
}
/**
* Store the given pages array.
*
* param {array} pages The array of pages to be stored.
*/
_setToStore(pages) {
sessionStorage.setItem(this._storageKey, pages.toString());
}
}
module.exports = Backtrack;