-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (42 loc) · 1.27 KB
/
index.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
const queryString = require('query-string');
const updateURL = (qs) => {
var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + qs;
window.history.pushState({ path: newUrl }, '', newUrl);
}
const stripKeys = (whitelist, obj) => {
const ret = {};
Object.keys(obj).forEach((key) => {
if (whitelist) {
if (whitelist[key]) {
ret[key] = obj[key];
}
} else {
ret[key] = obj[key];
}
})
return ret;
}
module.exports = (whitelist) => {
return (ctx) => {
ctx.onMount(() => {
if (window.location.search) {
// Merge initial state with the state from URL if it exists:
const parsed = queryString.parse(location.search);
ctx.update(parsed)
} else {
// Otherwise serialize the initial state to the URL
const data = ctx.data();
if (whitelist) {
}
const stringified = queryString.stringify(stripKeys(whitelist, data));
updateURL(stringified);
}
})
// Update the url when data changes
ctx.onUpdate((newData) => {
const stringified = queryString.stringify(
stripKeys(whitelist, Object.assign({}, queryString.parse(location.search), newData)));
updateURL(stringified);
})
}
}