-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
65 lines (55 loc) · 1.66 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
59
60
61
62
63
64
65
const store = require('svelte/store');
const query = store.writable({})
const keepHistory = []
let disableHistory = false
query.setWithoutHistory = (params) => {
disableHistory = true
query.set(params)
disableHistory = false
}
query.keepHistory = function(param) {
keepHistory.push(param)
}
// TODO: figure out a way to support SSR
if (typeof window !== 'undefined') {
let initial = {}
const handlePop = () => {
const params = new URLSearchParams(window.location.search)
for (let [param, value] of params) {
try {
value = JSON.parse(value)
}
catch { /* wasnt json. dont care */ }
initial[param] = value
}
query.setWithoutHistory(initial)
}
handlePop()
window.addEventListener('popstate', handlePop)
let oldParams = initial
query.subscribe(params => {
if (disableHistory) return
if (typeof history == 'undefined') return
let search = ''
let pushHistory = false
for (const param in params) {
let value = params[param]
search += (search ? '&' : '?')
if (oldParams[param] !== value && keepHistory.indexOf(param) !== -1) {
pushHistory = true
}
if (typeof value == 'undefined') continue;
if (!!value && typeof value == 'object') value = JSON.stringify(value)
value = encodeURIComponent(value)
search += param + '=' + value
}
oldParams = JSON.parse(JSON.stringify(params))
if (pushHistory) {
history.pushState(history.state, document.title, window.location.pathname + search)
}
else {
history.replaceState(history.state, document.title, window.location.pathname + search)
}
})
}
module.exports = query