-
Notifications
You must be signed in to change notification settings - Fork 961
/
useQueries.js
98 lines (78 loc) · 2.5 KB
/
useQueries.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
86
87
88
89
90
91
92
93
94
95
96
97
98
import qs from 'qs'
import runTransitionHook from './runTransitionHook'
import parsePath from './parsePath'
function defaultStringifyQuery(query) {
return qs.stringify(query, { arrayFormat: 'brackets' }).replace(/%20/g, '+')
}
function defaultParseQueryString(queryString) {
return qs.parse(queryString.replace(/\+/g, '%20'))
}
/**
* Returns a new createHistory function that may be used to create
* history objects that know how to handle URL queries.
*/
function useQueries(createHistory) {
return function (options={}) {
let { stringifyQuery, parseQueryString, ...historyOptions } = options
let history = createHistory(historyOptions)
if (typeof stringifyQuery !== 'function')
stringifyQuery = defaultStringifyQuery
if (typeof parseQueryString !== 'function')
parseQueryString = defaultParseQueryString
function addQuery(location) {
if (location.query == null)
location.query = parseQueryString(location.search.substring(1))
return location
}
function appendQuery(path, query) {
let queryString
if (!query || (queryString = stringifyQuery(query)) === '')
return path
if (typeof path === 'string')
path = parsePath(path)
const search = path.search + (path.search ? '&' : '?') + queryString
return {
...path,
search
}
}
// Override all read methods with query-aware versions.
function listenBefore(hook) {
return history.listenBefore(function (location, callback) {
runTransitionHook(hook, addQuery(location), callback)
})
}
function listen(listener) {
return history.listen(function (location) {
listener(addQuery(location))
})
}
// Override all write methods with query-aware versions.
function pushState(state, path, query) {
return history.pushState(state, appendQuery(path, query))
}
function replaceState(state, path, query) {
return history.replaceState(state, appendQuery(path, query))
}
function createPath(path, query) {
return history.createPath(appendQuery(path, query))
}
function createHref(path, query) {
return history.createHref(appendQuery(path, query))
}
function createLocation() {
return addQuery(history.createLocation.apply(history, arguments))
}
return {
...history,
listenBefore,
listen,
pushState,
replaceState,
createPath,
createHref,
createLocation
}
}
}
export default useQueries