generated from chiffre-io/template-library
-
-
Notifications
You must be signed in to change notification settings - Fork 165
/
Copy pathuseQueryStates.ts
293 lines (274 loc) · 9.1 KB
/
useQueryStates.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useAdapter } from './adapters/lib/context'
import { debug } from './debug'
import type { Nullable, Options, UrlKeys } from './defs'
import type { Parser } from './parsers'
import { emitter, type CrossHookSyncPayload } from './sync'
import {
enqueueQueryStringUpdate,
FLUSH_RATE_LIMIT_MS,
getQueuedValue,
scheduleFlushToURL
} from './update-queue'
import { safeParse } from './utils'
type KeyMapValue<Type> = Parser<Type> &
Options & {
defaultValue?: Type
}
export type UseQueryStatesKeysMap<Map = any> = {
[Key in keyof Map]: KeyMapValue<Map[Key]>
}
export type UseQueryStatesOptions<KeyMap extends UseQueryStatesKeysMap> =
Options & {
urlKeys: UrlKeys<KeyMap>
}
export type Values<T extends UseQueryStatesKeysMap> = {
[K in keyof T]: T[K]['defaultValue'] extends NonNullable<
ReturnType<T[K]['parse']>
>
? NonNullable<ReturnType<T[K]['parse']>>
: ReturnType<T[K]['parse']> | null
}
type NullableValues<T extends UseQueryStatesKeysMap> = Nullable<Values<T>>
type UpdaterFn<T extends UseQueryStatesKeysMap> = (
old: Values<T>
) => Partial<Nullable<Values<T>>>
export type SetValues<T extends UseQueryStatesKeysMap> = (
values: Partial<Nullable<Values<T>>> | UpdaterFn<T> | null,
options?: Options
) => Promise<URLSearchParams>
export type UseQueryStatesReturn<T extends UseQueryStatesKeysMap> = [
Values<T>,
SetValues<T>
]
// Ensure referential consistency for the default value of urlKeys
// by hoisting it out of the function scope.
// Otherwise useEffect loops go brrrr
const defaultUrlKeys = {}
/**
* Synchronise multiple query string arguments to React state in Next.js
*
* @param keys - An object describing the keys to synchronise and how to
* serialise and parse them.
* Use `parseAs(String|Integer|Float|...)` for quick shorthands.
* @param options - Optional history mode, shallow routing and scroll restoration options.
*/
export function useQueryStates<KeyMap extends UseQueryStatesKeysMap>(
keyMap: KeyMap,
{
history = 'replace',
scroll = false,
shallow = true,
throttleMs = FLUSH_RATE_LIMIT_MS,
clearOnDefault = true,
startTransition,
urlKeys = defaultUrlKeys
}: Partial<UseQueryStatesOptions<KeyMap>> = {}
): UseQueryStatesReturn<KeyMap> {
type V = NullableValues<KeyMap>
const stateKeys = Object.keys(keyMap).join(',')
const resolvedUrlKeys = useMemo(
() =>
Object.fromEntries(
Object.keys(keyMap).map(key => [key, urlKeys[key] ?? key])
),
[stateKeys, urlKeys]
)
const adapter = useAdapter()
const initialSearchParams = adapter.searchParams
const queryRef = useRef<Record<string, string | null>>({})
// Initialise the queryRef with the initial values
if (Object.keys(queryRef.current).length !== Object.keys(keyMap).length) {
queryRef.current = Object.fromEntries(initialSearchParams?.entries() ?? [])
}
const defaultValues = useMemo(
() =>
Object.fromEntries(
Object.keys(keyMap).map(key => [key, keyMap[key]!.defaultValue ?? null])
) as Values<KeyMap>,
[
Object.values(keyMap)
.map(({ defaultValue }) => defaultValue)
.join(',')
]
)
const [internalState, setInternalState] = useState<V>(() => {
const source = initialSearchParams ?? new URLSearchParams()
return parseMap(keyMap, urlKeys, source)
})
const stateRef = useRef(internalState)
debug(
'[nuq+ `%s`] render - state: %O, iSP: %s',
stateKeys,
internalState,
initialSearchParams
)
useEffect(() => {
const state = parseMap(
keyMap,
urlKeys,
initialSearchParams,
queryRef.current,
stateRef.current
)
stateRef.current = state
setInternalState(state)
}, [
Object.values(resolvedUrlKeys)
.map(key => initialSearchParams?.get(key))
.join('&')
])
// Sync all hooks together & with external URL changes
useEffect(() => {
function updateInternalState(state: V) {
debug('[nuq+ `%s`] updateInternalState %O', stateKeys, state)
stateRef.current = state
setInternalState(state)
}
const handlers = Object.keys(keyMap).reduce(
(handlers, stateKey) => {
handlers[stateKey as keyof KeyMap] = ({
state,
query
}: CrossHookSyncPayload) => {
const { defaultValue } = keyMap[stateKey]!
const urlKey = resolvedUrlKeys[stateKey]!
// Note: cannot mutate in-place, the object ref must change
// for the subsequent setState to pick it up.
stateRef.current = {
...stateRef.current,
[stateKey as keyof KeyMap]: state ?? defaultValue ?? null
}
queryRef.current[urlKey] = query
debug(
'[nuq+ `%s`] Cross-hook key sync %s: %O (default: %O). Resolved: %O',
stateKeys,
urlKey,
state,
defaultValue,
stateRef.current
)
updateInternalState(stateRef.current)
}
return handlers
},
{} as Record<keyof KeyMap, (payload: CrossHookSyncPayload) => void>
)
for (const stateKey of Object.keys(keyMap)) {
const urlKey = resolvedUrlKeys[stateKey]!
debug('[nuq+ `%s`] Subscribing to sync for `%s`', stateKeys, urlKey)
emitter.on(urlKey, handlers[stateKey]!)
}
return () => {
for (const stateKey of Object.keys(keyMap)) {
const urlKey = resolvedUrlKeys[stateKey]!
debug('[nuq+ `%s`] Unsubscribing to sync for `%s`', stateKeys, urlKey)
emitter.off(urlKey, handlers[stateKey])
}
}
}, [keyMap, resolvedUrlKeys])
const update = useCallback<SetValues<KeyMap>>(
(stateUpdater, callOptions = {}) => {
const newState: Partial<Nullable<KeyMap>> =
typeof stateUpdater === 'function'
? stateUpdater(applyDefaultValues(stateRef.current, defaultValues))
: stateUpdater === null
? (Object.fromEntries(
Object.keys(keyMap).map(key => [key, null])
) as Nullable<KeyMap>)
: stateUpdater
debug('[nuq+ `%s`] setState: %O', stateKeys, newState)
for (let [stateKey, value] of Object.entries(newState)) {
const parser = keyMap[stateKey]
const urlKey = resolvedUrlKeys[stateKey]!
if (!parser) {
continue
}
if (
(callOptions.clearOnDefault ??
parser.clearOnDefault ??
clearOnDefault) &&
value !== null &&
parser.defaultValue !== undefined &&
(parser.eq ?? ((a, b) => a === b))(value, parser.defaultValue)
) {
value = null
}
const query = enqueueQueryStringUpdate(
urlKey,
value,
parser.serialize ?? String,
{
// Call-level options take precedence over individual parser options
// which take precedence over global options
history: callOptions.history ?? parser.history ?? history,
shallow: callOptions.shallow ?? parser.shallow ?? shallow,
scroll: callOptions.scroll ?? parser.scroll ?? scroll,
throttleMs:
callOptions.throttleMs ?? parser.throttleMs ?? throttleMs,
startTransition:
callOptions.startTransition ??
parser.startTransition ??
startTransition
}
)
emitter.emit(urlKey, { state: value, query })
}
return scheduleFlushToURL(adapter)
},
[
stateKeys,
history,
shallow,
scroll,
throttleMs,
startTransition,
resolvedUrlKeys,
adapter.updateUrl,
adapter.getSearchParamsSnapshot,
adapter.rateLimitFactor,
defaultValues
]
)
const outputState = useMemo(
() => applyDefaultValues(internalState, defaultValues),
[internalState, defaultValues]
)
return [outputState, update]
}
// --
function parseMap<KeyMap extends UseQueryStatesKeysMap>(
keyMap: KeyMap,
urlKeys: Partial<Record<keyof KeyMap, string>>,
searchParams: URLSearchParams,
cachedQuery?: Record<string, string | null>,
cachedState?: NullableValues<KeyMap>
): NullableValues<KeyMap> {
return Object.keys(keyMap).reduce((out, stateKey) => {
const urlKey = urlKeys?.[stateKey] ?? stateKey
const { parse } = keyMap[stateKey]!
const queuedQuery = getQueuedValue(urlKey)
const query =
queuedQuery === undefined
? (searchParams?.get(urlKey) ?? null)
: queuedQuery
if (cachedQuery && cachedState && cachedQuery[urlKey] === query) {
out[stateKey as keyof KeyMap] = cachedState[stateKey] ?? null
return out
}
const value = query === null ? null : safeParse(parse, query, stateKey)
out[stateKey as keyof KeyMap] = value ?? null
if (cachedQuery) {
cachedQuery[urlKey] = query
}
return out
}, {} as NullableValues<KeyMap>)
}
function applyDefaultValues<KeyMap extends UseQueryStatesKeysMap>(
state: NullableValues<KeyMap>,
defaults: Partial<Values<KeyMap>>
) {
return Object.fromEntries(
Object.keys(state).map(key => [key, state[key] ?? defaults[key] ?? null])
) as Values<KeyMap>
}