-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.tsx
333 lines (298 loc) · 10.2 KB
/
index.tsx
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import { useRouter } from "next/router";
import React, {
PropsWithChildren,
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from "react";
/** Configuration for how a value will be encoded and decoded into the URL. */
export enum QueryParamKind {
/** Immediately flushed single string value. */
STRING = 1,
/** String value that uses local state updates and defers updating the URL. */
STRING_DEFERRED,
/** Value is set multiple times in the URL, decoded as a list. */
STRING_LIST,
/** Value is set multiple times in the URL, decoded as a set. */
STRING_SET,
/** Value is undefined when not present, a list when it is. */
STRING_LIST_DEFAULT_UNDEFINED,
/** String value that will throw an error if not found. */
STRING_REQUIRED,
/** Parsed and serialized as a number. */
NUMBER,
/** Number value that uses local state updates and defers updating the URL. */
NUMBER_DEFERRED,
}
type DecodedQueryParamKind<Kind extends QueryParamKind> = Kind extends
| QueryParamKind.STRING
| QueryParamKind.STRING_DEFERRED
? string | undefined
: Kind extends QueryParamKind.NUMBER | QueryParamKind.NUMBER_DEFERRED
? number | undefined
: Kind extends QueryParamKind.STRING_LIST
? string[]
: Kind extends QueryParamKind.STRING_LIST_DEFAULT_UNDEFINED
? string[] | undefined
: Kind extends QueryParamKind.STRING_REQUIRED
? string
: Set<string>;
interface AnyParamMapping {
[param: string]: QueryParamKind;
}
export type DecodedParamMapping<ParamMapping extends AnyParamMapping> = {
[Param in keyof ParamMapping]: DecodedQueryParamKind<ParamMapping[Param]>;
};
export type DecodedParamUpdate<ParamMapping extends AnyParamMapping> = {
[Param in keyof ParamMapping]?:
| DecodedQueryParamKind<ParamMapping[Param]>
| null
| undefined;
};
function defaultNaNToUndefined(n: number): number | undefined {
return Number.isNaN(n) ? undefined : n;
}
type DeferredQueryParamUpdates = Record<
string,
string | string[] | Set<string> | number | null | undefined
>;
interface QueryParamsContextValue {
deferredUpdates: DeferredQueryParamUpdates;
setDeferredUpdates: (update: DeferredQueryParamUpdates) => void;
}
const QueryParamsContext = createContext<QueryParamsContextValue>({
deferredUpdates: {},
// eslint-disable-next-line @typescript-eslint/no-empty-function
setDeferredUpdates: () => {},
});
export function QueryParamsProvider({ children }: PropsWithChildren<{}>) {
const [deferredUpdates, setDeferredUpdates] =
useState<DeferredQueryParamUpdates>({});
const contextValue = useMemo(
(): QueryParamsContextValue => ({
deferredUpdates,
setDeferredUpdates,
}),
[deferredUpdates, setDeferredUpdates]
);
return (
<QueryParamsContext.Provider value={contextValue}>
{children}
</QueryParamsContext.Provider>
);
}
export function parseQuery<ParamMapping extends AnyParamMapping>(
query: Record<string, any>,
params: ParamMapping
): DecodedParamMapping<ParamMapping> {
const valueMapping = {} as DecodedParamMapping<ParamMapping>;
for (const [name, kind] of Object.entries(params)) {
const queryParamValue = query[name];
switch (kind) {
case QueryParamKind.STRING:
case QueryParamKind.STRING_DEFERRED:
case QueryParamKind.STRING_REQUIRED:
valueMapping[name as keyof ParamMapping] = (
Array.isArray(queryParamValue) ? queryParamValue[0] : queryParamValue
) as DecodedQueryParamKind<ParamMapping[keyof ParamMapping]>;
break;
case QueryParamKind.NUMBER:
case QueryParamKind.NUMBER_DEFERRED:
valueMapping[name as keyof ParamMapping] = (
Array.isArray(queryParamValue)
? defaultNaNToUndefined(Number(queryParamValue[0]))
: defaultNaNToUndefined(Number(queryParamValue))
) as DecodedQueryParamKind<ParamMapping[keyof ParamMapping]>;
break;
case QueryParamKind.STRING_LIST:
valueMapping[name as keyof ParamMapping] = (
queryParamValue == null
? []
: Array.isArray(queryParamValue)
? queryParamValue
: [queryParamValue]
) as DecodedQueryParamKind<ParamMapping[keyof ParamMapping]>;
break;
case QueryParamKind.STRING_SET:
valueMapping[name as keyof ParamMapping] = (
queryParamValue == null
? new Set()
: Array.isArray(queryParamValue)
? new Set(queryParamValue)
: new Set([queryParamValue])
) as DecodedQueryParamKind<ParamMapping[keyof ParamMapping]>;
break;
case QueryParamKind.STRING_LIST_DEFAULT_UNDEFINED:
valueMapping[name as keyof ParamMapping] = (
queryParamValue == null
? undefined
: Array.isArray(queryParamValue)
? queryParamValue
: [queryParamValue]
) as DecodedQueryParamKind<ParamMapping[keyof ParamMapping]>;
break;
default:
break;
}
if (
kind === QueryParamKind.STRING_REQUIRED &&
typeof valueMapping[name] !== "string"
) {
throw new Error(`Expected to find required string: ${name}`);
}
}
return valueMapping;
}
export function useQueryParams<ParamMapping extends AnyParamMapping>(
params: ParamMapping
): readonly [
DecodedParamMapping<ParamMapping>,
(nextValues: DecodedParamUpdate<ParamMapping>) => void,
() => void
] {
const router = useRouter();
const { deferredUpdates, setDeferredUpdates } =
useContext(QueryParamsContext);
const values = useMemo(() => {
const valueMapping = parseQuery(router.query, params);
Object.assign(valueMapping, deferredUpdates);
return valueMapping;
}, [deferredUpdates, params, router.query]);
const updateValues = useCallback(
(
nextValues: {
[Param in keyof ParamMapping]?:
| DecodedQueryParamKind<ParamMapping[Param]>
| null
| undefined;
},
opts: { immediate: boolean } = { immediate: false }
) => {
const nextDeferredValues = {} as DecodedParamUpdate<ParamMapping>;
const url = new URL(window.location.href);
for (const [name, nextValue] of Object.entries(nextValues)) {
const isImmediateUpdate =
opts.immediate ||
(params[name] !== QueryParamKind.NUMBER_DEFERRED &&
params[name] !== QueryParamKind.STRING_DEFERRED);
if (nextValue === undefined) continue;
if (nextValue === null) {
if (isImmediateUpdate) {
url.searchParams.delete(name);
} else {
nextDeferredValues[name as keyof ParamMapping] = null;
}
continue;
}
const kind = params[name];
if (kind == null) continue;
switch (kind) {
case QueryParamKind.STRING:
case QueryParamKind.STRING_DEFERRED:
case QueryParamKind.NUMBER:
case QueryParamKind.NUMBER_DEFERRED:
case QueryParamKind.STRING_REQUIRED: {
const stringValue =
`${nextValue}` as DecodedQueryParamKind<QueryParamKind.STRING>;
if (!stringValue) {
if (isImmediateUpdate) {
url.searchParams.delete(name);
} else {
nextDeferredValues[name as keyof ParamMapping] = null;
}
} else {
if (isImmediateUpdate) {
url.searchParams.set(name, stringValue);
} else {
nextDeferredValues[name as keyof ParamMapping] = nextValue;
}
}
break;
}
case QueryParamKind.STRING_LIST: {
const listValue =
nextValue as DecodedQueryParamKind<QueryParamKind.STRING_LIST>;
if (listValue.length === 0) {
url.searchParams.delete(name);
} else {
url.searchParams.set(name, listValue[0]!);
for (const nextListValue of listValue.slice(1)) {
url.searchParams.append(name, nextListValue);
}
}
break;
}
case QueryParamKind.STRING_LIST_DEFAULT_UNDEFINED: {
const listValue =
nextValue as DecodedQueryParamKind<QueryParamKind.STRING_LIST_DEFAULT_UNDEFINED>;
if (listValue != null) {
if (listValue.length === 0) {
url.searchParams.delete(name);
} else {
url.searchParams.set(name, listValue[0]!);
for (const nextListValue of listValue.slice(1)) {
url.searchParams.append(name, nextListValue);
}
}
}
break;
}
case QueryParamKind.STRING_SET: {
const setValue =
nextValue as DecodedQueryParamKind<QueryParamKind.STRING_SET>;
if (setValue.size === 0) {
url.searchParams.delete(name);
} else {
const asList = Array.from(setValue);
url.searchParams.set(name, asList[0]!);
for (const nextListValue of asList.slice(1)) {
url.searchParams.append(name, nextListValue);
}
}
break;
}
default:
break;
}
}
if (Object.keys(nextDeferredValues).length > 0) {
setDeferredUpdates(nextDeferredValues);
}
if (window.location.href !== url.href) {
void router.replace(url, undefined, {
shallow: true,
scroll: false,
});
}
},
[params, router, setDeferredUpdates]
);
const resetFields = useCallback(() => {
const url = new URL(window.location.href);
for (const param of Array.from(url.searchParams.keys())) {
url.searchParams.delete(param);
}
setDeferredUpdates({});
void router.replace(url, undefined, {
shallow: true,
scroll: false,
});
}, [router, setDeferredUpdates]);
useEffect(() => {
const timeoutId = setTimeout(() => {
if (Object.keys(deferredUpdates).length > 0) {
updateValues(
deferredUpdates as unknown as DecodedParamUpdate<ParamMapping>,
{ immediate: true }
);
}
}, 600);
return () => {
clearTimeout(timeoutId);
};
}, [deferredUpdates, updateValues]);
return [values, updateValues, resetFields] as const;
}