-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
58 lines (50 loc) · 1.54 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
50
51
52
53
54
55
56
57
58
const jsonURL = require('json-url')('lzw');
/**
* StatefulURL is a Vuex plugin that can read and write the state from a query string
*
* @param {Object} config = {}
* @param {String} config.key the query string value to sync the state
*
* @returns {Function<void>|void}
*/
function StatefulURL (config = {}) {
// bail if not in a browser or missing features
if (typeof window === 'undefined' || typeof window.URLSearchParams !== 'function' || typeof window.URL !== 'function') {
return;
}
const key = config.key || 'state';
const search = new window.URLSearchParams(window.location.search);
const urlState = Object.fromEntries(search.entries()).state || null;
/**
* Store plugin
*
* @param {Object} store
*/
return function (store) {
if (urlState) {
jsonURL
.decompress(urlState)
.then((json) => {
try {
Object.entries(json)
.forEach(([prop, value]) => {
store.state[prop] = value;
});
} catch (e) {}
});
}
store.subscribe((mutation, state) => {
const search = new window.URLSearchParams(window.location.search);
jsonURL
.compress(state)
.then((currentState) => {
search.set(key, currentState);
const url = new window.URL(window.location.href);
url.search = '?' + search.toString();
const path = url.toString();
window.history.replaceState({ path }, document.title, path);
});
});
};
};
module.exports = StatefulURL;