-
Notifications
You must be signed in to change notification settings - Fork 960
/
useQueries.js
99 lines (76 loc) · 2.66 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
99
import { parse, stringify } from 'query-string'
import runTransitionHook from './runTransitionHook'
import { createQuery } from './LocationUtils'
import { parsePath } from './PathUtils'
const defaultStringifyQuery = (query) =>
stringify(query).replace(/%20/g, '+')
const defaultParseQueryString = parse
/**
* Returns a new createHistory function that may be used to create
* history objects that know how to handle URL queries.
*/
const useQueries = (createHistory) =>
(options = {}) => {
const history = createHistory(options)
let { stringifyQuery, parseQueryString } = options
if (typeof stringifyQuery !== 'function')
stringifyQuery = defaultStringifyQuery
if (typeof parseQueryString !== 'function')
parseQueryString = defaultParseQueryString
const decodeQuery = (location) => {
if (!location)
return location
if (location.query == null)
location.query = parseQueryString(location.search.substring(1))
return location
}
const encodeQuery = (location, query) => {
if (query == null)
return location
const object = typeof location === 'string' ? parsePath(location) : location
const queryString = stringifyQuery(query)
const search = queryString ? `?${queryString}` : ''
return {
...object,
search
}
}
// Override all read methods with query-aware versions.
const getCurrentLocation = () =>
decodeQuery(history.getCurrentLocation())
const listenBefore = (hook) =>
history.listenBefore(
(location, callback) =>
runTransitionHook(hook, decodeQuery(location), callback)
)
const listen = (listener) =>
history.listen(location => listener(decodeQuery(location)))
// Override all write methods with query-aware versions.
const push = (location) =>
history.push(encodeQuery(location, location.query))
const replace = (location) =>
history.replace(encodeQuery(location, location.query))
const createPath = (location) =>
history.createPath(encodeQuery(location, location.query))
const createHref = (location) =>
history.createHref(encodeQuery(location, location.query))
const createLocation = (location, ...args) => {
const newLocation =
history.createLocation(encodeQuery(location, location.query), ...args)
if (location.query)
newLocation.query = createQuery(location.query)
return decodeQuery(newLocation)
}
return {
...history,
getCurrentLocation,
listenBefore,
listen,
push,
replace,
createPath,
createHref,
createLocation
}
}
export default useQueries