forked from HSLdevcom/digitransit-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlocalStorageHistory.js
75 lines (64 loc) · 1.7 KB
/
localStorageHistory.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
import { createMemoryHistory } from 'history';
import { setHistory, getHistory } from './store/localStorage';
function getHistoryConsideringTime() {
const history = getHistory();
if (history.time > Date.now() - 60 * 60 * 1000) {
return history;
}
return { entries: ['/'], index: 0, time: 0 };
}
// minimial serializable history state (just the paths)
const history = getHistoryConsideringTime();
let isInitialized = false;
const saveHistory = () => {
setHistory({ ...history, time: Date.now() });
};
const PUSH = entry => {
history.entries.splice(history.index + 1);
history.entries.push(entry);
history.index += 1;
saveHistory();
};
const POP = () => {
if (isInitialized && history.index > 0) {
history.index -= 1;
saveHistory();
} else if (!isInitialized) {
isInitialized = true;
}
};
const REPLACE = entry => {
history.entries.splice(history.index);
history.entries.push(entry);
saveHistory();
};
const getEntries = () => history.entries;
const getIndex = () => history.index;
const getLocationListener = () => event => {
switch (event.action) {
case 'POP':
POP(event);
break;
case 'REPLACE':
REPLACE(event);
break;
case 'PUSH':
PUSH(event);
break;
default:
// eslint-disable-next-line no-console
console.error('unhandled history event:', event);
}
if (this && this[event.action] !== undefined) {
this[event.action](event);
}
};
const createLocalStorageHistory = () => {
const hist = createMemoryHistory({
current: getIndex(),
entries: getEntries(),
});
hist.listen(getLocationListener());
return hist;
};
export { createLocalStorageHistory as default, getIndex, getLocationListener };