-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstate.js
85 lines (61 loc) · 2.24 KB
/
state.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
export { State };
/*************************************************************************************************/
/* Defaults */
/*************************************************************************************************/
const DEFAULT_NAME = "";
/*************************************************************************************************/
/* Utils */
/*************************************************************************************************/
function url2state() {
let query = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
return query.state || {};
}
function state2url(state_) {
// Perform a copy of the state.
let state = { ...state_ };
// Generate the URL.
let url = new URL(window.location);
let params = url.searchParams;
// Add the state to the query string
params.set('state', encode(state));
return url.toString();
}
/*************************************************************************************************/
/* State */
/*************************************************************************************************/
class State {
constructor() {
this._toggle = true;
this.fromURL();
}
init(state) {
this.name = state.name || DEFAULT_NAME;
this.isPlaying = false; // NOTE: always start false.
}
reset() {
this.init();
}
toggleUpdate(toggle) {
this._toggle = toggle;
}
updateURL() {
if (!this._toggle) return;
console.log("update URL with current state");
let url = this.toURL();
window.history.replaceState(null, '', url.toString());
return url;
}
fromURL() {
let state = url2state();
this.init(state);
}
toURL() {
let cpy = { ...this };
delete cpy._toggle;
cpy.selected = Array.from(cpy.selected);
let url = state2url(cpy);
return url;
}
};