forked from vueuse/vueuse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
154 lines (132 loc) · 3.8 KB
/
index.ts
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import { reactive } from 'vue-demi'
import { pausableWatch } from '@vueuse/shared'
import { useEventListener } from '../useEventListener'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
export type UrlParams = Record<string, string[] | string>
export interface UseUrlSearchParamsOptions<T> extends ConfigurableWindow {
/**
* @default true
*/
removeNullishValues?: boolean
/**
* @default false
*/
removeFalsyValues?: boolean
/**
* @default {}
*/
initialValue?: T
/**
* Write back to `window.history` automatically
*
* @default true
*/
autoWrite?: boolean
}
/**
* Reactive URLSearchParams
*
* @see https://vueuse.org/useUrlSearchParams
* @param mode
* @param options
*/
export function useUrlSearchParams<T extends Record<string, any> = UrlParams>(
mode: 'history' | 'hash' | 'hash-params' = 'history',
options: UseUrlSearchParamsOptions<T> = {},
): T {
const {
initialValue = {},
removeNullishValues = true,
removeFalsyValues = false,
autoWrite = true,
window = defaultWindow!,
} = options
if (!window)
return reactive(initialValue) as T
const state: Record<string, any> = reactive({})
function getRawParams() {
if (mode === 'history') {
return window.location.search || ''
}
else if (mode === 'hash') {
const hash = window.location.hash || ''
const index = hash.indexOf('?')
return index > 0 ? hash.slice(index) : ''
}
else {
return (window.location.hash || '').replace(/^#/, '')
}
}
function constructQuery(params: URLSearchParams) {
const stringified = params.toString()
if (mode === 'history')
return `${stringified ? `?${stringified}` : ''}${window.location.hash || ''}`
if (mode === 'hash-params')
return `${window.location.search || ''}${stringified ? `#${stringified}` : ''}`
const hash = window.location.hash || '#'
const index = hash.indexOf('?')
if (index > 0)
return `${hash.slice(0, index)}${stringified ? `?${stringified}` : ''}`
return `${hash}${stringified ? `?${stringified}` : ''}`
}
function read() {
return new URLSearchParams(getRawParams())
}
function updateState(params: URLSearchParams) {
const unusedKeys = new Set(Object.keys(state))
for (const key of params.keys()) {
const paramsForKey = params.getAll(key)
state[key] = paramsForKey.length > 1
? paramsForKey
: (params.get(key) || '')
unusedKeys.delete(key)
}
Array.from(unusedKeys).forEach(key => delete state[key])
}
const { pause, resume } = pausableWatch(
state,
() => {
const params = new URLSearchParams('')
Object.keys(state).forEach((key) => {
const mapEntry = state[key]
if (Array.isArray(mapEntry))
mapEntry.forEach(value => params.append(key, value))
else if (removeNullishValues && mapEntry == null)
params.delete(key)
else if (removeFalsyValues && !mapEntry)
params.delete(key)
else
params.set(key, mapEntry)
})
write(params)
},
{ deep: true },
)
function write(params: URLSearchParams, shouldUpdate?: boolean) {
pause()
if (shouldUpdate)
updateState(params)
window.history.replaceState(
window.history.state,
window.document.title,
window.location.pathname + constructQuery(params),
)
resume()
}
function onChanged() {
if (!autoWrite) {
return
}
write(read(), true)
}
useEventListener(window, 'popstate', onChanged, false)
if (mode !== 'history')
useEventListener(window, 'hashchange', onChanged, false)
const initial = read()
if (initial.keys().next().value)
updateState(initial)
else
Object.assign(state, initialValue)
return state as T
}