@octanejs/nuqs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,413 @@
1
+ import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'octane';
2
+ import {
3
+ useAdapter,
4
+ useAdapterDefaultOptions,
5
+ useAdapterProcessUrlSearchParams,
6
+ } from './adapters/lib/context';
7
+ import type { Nullable, Options, UrlKeys } from './defs';
8
+ import { compareQuery } from './lib/compare';
9
+ import { debug } from './lib/debug';
10
+ import { debounceController, useQueuedQueries } from './lib/queues/debounce';
11
+ import { defaultRateLimit } from './lib/queues/rate-limiting';
12
+ import { globalThrottleQueue, type UpdateQueuePushArgs } from './lib/queues/throttle';
13
+ import { safeParse } from './lib/safe-parse';
14
+ import { isAbsentFromUrl, type Query } from './lib/search-params';
15
+ import { emitter, type CrossHookSyncPayload } from './lib/sync';
16
+ import { type GenericParser } from './parsers';
17
+
18
+ type KeyMapValue<Type> = GenericParser<Type> &
19
+ Options & {
20
+ defaultValue?: Type;
21
+ };
22
+
23
+ export type UseQueryStatesKeysMap<Map = any> = {
24
+ [Key in keyof Map]: KeyMapValue<Map[Key]>;
25
+ } & {};
26
+
27
+ export type UseQueryStatesOptions<KeyMap extends UseQueryStatesKeysMap> = Options & {
28
+ urlKeys: UrlKeys<KeyMap>;
29
+ };
30
+
31
+ export type Values<T extends UseQueryStatesKeysMap> = {
32
+ [K in keyof T]: T[K]['defaultValue'] extends NonNullable<ReturnType<T[K]['parse']>>
33
+ ? NonNullable<ReturnType<T[K]['parse']>>
34
+ : ReturnType<T[K]['parse']> | null;
35
+ };
36
+ type NullableValues<T extends UseQueryStatesKeysMap> = Nullable<Values<T>>;
37
+
38
+ type UpdaterFn<T extends UseQueryStatesKeysMap> = (
39
+ old: Values<T>,
40
+ ) => Partial<Nullable<Values<T>>> | null;
41
+
42
+ export type SetValues<T extends UseQueryStatesKeysMap> = (
43
+ values: Partial<Nullable<Values<T>>> | UpdaterFn<T> | null,
44
+ options?: Options,
45
+ ) => Promise<URLSearchParams>;
46
+
47
+ export type UseQueryStatesReturn<T extends UseQueryStatesKeysMap> = [Values<T>, SetValues<T>];
48
+
49
+ // Ensure referential consistency for the default value of urlKeys
50
+ // by hoisting it out of the function scope.
51
+ // Otherwise useEffect loops go brrrr
52
+ const defaultUrlKeys = {};
53
+
54
+ /**
55
+ * Synchronise multiple query string arguments to React state in Next.js
56
+ *
57
+ * @param keys - An object describing the keys to synchronise and how to
58
+ * serialise and parse them.
59
+ * Use `parseAs(String|Integer|Float|...)` for quick shorthands.
60
+ * @param options - Optional history mode, shallow routing and scroll restoration options.
61
+ */
62
+ export function useQueryStates<KeyMap extends UseQueryStatesKeysMap>(
63
+ keyMap: KeyMap,
64
+ options: Partial<UseQueryStatesOptions<KeyMap>> = {},
65
+ ): UseQueryStatesReturn<KeyMap> {
66
+ const hookId = useId();
67
+ const defaultOptions = useAdapterDefaultOptions();
68
+ const processUrlSearchParams = useAdapterProcessUrlSearchParams();
69
+
70
+ const {
71
+ history = defaultOptions?.history ?? 'replace',
72
+ scroll = defaultOptions?.scroll ?? false,
73
+ shallow = defaultOptions?.shallow ?? true,
74
+ throttleMs = defaultRateLimit.timeMs,
75
+ limitUrlUpdates = defaultOptions?.limitUrlUpdates,
76
+ clearOnDefault = defaultOptions?.clearOnDefault ?? true,
77
+ startTransition,
78
+ urlKeys = defaultUrlKeys as UrlKeys<KeyMap>,
79
+ } = options;
80
+
81
+ type V = NullableValues<KeyMap>;
82
+ const stateKeys = Object.keys(keyMap).join(',');
83
+ const resolvedUrlKeys = useMemo(
84
+ () => Object.fromEntries(Object.keys(keyMap).map((key) => [key, urlKeys[key] ?? key])),
85
+ [stateKeys, JSON.stringify(urlKeys)],
86
+ );
87
+ const adapter = useAdapter(Object.values(resolvedUrlKeys));
88
+ const initialSearchParams = adapter.searchParams;
89
+ const queryRef = useRef<Record<string, Query | null>>({});
90
+ // Tracks the URL source (search params + queued queries) the internal state
91
+ // was last reconciled against during render. See the reconciliation block below.
92
+ const lastSyncKeyRef = useRef<string | null>(null);
93
+ // The pathname this hook last reconciled against from a committed render
94
+ // (set by the effect backstop below). The render-time reconcile is skipped when
95
+ // the current pathname no longer matches it: that means the component is
96
+ // rendering through a navigation transition for a different route (an outgoing
97
+ // or incoming page kept alive by the router, e.g. under cacheComponents),
98
+ // where adopting the in-flight URL would corrupt speculative renders (#1293).
99
+ // Both sides of the comparison use the adapter's pathname when provided
100
+ // (`usePathname()` in Next.js), which tracks the destination route from the
101
+ // start of a transition; the live `location.pathname` lags until the browser
102
+ // URL commits, which would misjudge a same-route reveal as a cross-route
103
+ // render and skip the reconcile (#1273). A genuine `<Activity>` reveal keeps
104
+ // the same pathname, so it still reconciles.
105
+ const committedPathnameRef = useRef<string | null>(null);
106
+ const defaultValues = useMemo(
107
+ () =>
108
+ Object.fromEntries(
109
+ Object.keys(keyMap).map((key) => [key, keyMap[key]!.defaultValue ?? null]),
110
+ ) as Values<KeyMap>,
111
+ [
112
+ Object.values(keyMap)
113
+ .map(({ defaultValue }) => defaultValue)
114
+ .join(','),
115
+ ],
116
+ );
117
+ const queuedQueries = useQueuedQueries(Object.values(resolvedUrlKeys));
118
+ const [internalState, setInternalState] = useState<V>(
119
+ () => parseMap(keyMap, urlKeys, initialSearchParams, queuedQueries).state,
120
+ );
121
+
122
+ const stateRef = useRef(internalState);
123
+
124
+ // Identifies the current URL source (resolved search params + queued queries).
125
+ // Mirrors the dependencies of the URL sync effect below so that render-time
126
+ // reconciliation reacts to the same external changes, and never to internal
127
+ // (optimistic) updates which don't immediately alter the URL source.
128
+ const searchParamsSyncKey =
129
+ Object.values(resolvedUrlKeys)
130
+ .map((key) => `${key}=${initialSearchParams.getAll(key)}`)
131
+ .join('&') + JSON.stringify(queuedQueries);
132
+ // Adopts the current URL value into the internal state when it has changed.
133
+ // Used both during render (below) and from the effect backstop further down.
134
+ const reconcile = () => {
135
+ const { state, hasChanged } = parseMap(
136
+ keyMap,
137
+ urlKeys,
138
+ initialSearchParams,
139
+ queuedQueries,
140
+ queryRef.current,
141
+ stateRef.current,
142
+ );
143
+ if (hasChanged) {
144
+ debug(1, hookId, stateKeys, state);
145
+ stateRef.current = state;
146
+ setInternalState(state);
147
+ }
148
+ };
149
+ // Reconcile during render, both on key-set changes (initialisation) and when
150
+ // the URL source changes. The effect below does the same, but effects are
151
+ // detached while a subtree is hidden under `<Activity>` and only re-run after
152
+ // the first commit on reveal, so without this, that first render would paint
153
+ // the value captured while hidden (#1444). Gating on `searchParamsSyncKey`
154
+ // means we only adopt the URL when its source actually changed, never
155
+ // reverting an optimistic update not yet propagated to the adapter's params.
156
+ //
157
+ // The URL-change branch is further gated to renders happening on the pathname
158
+ // the hook last committed against: during a route transition the router can
159
+ // render an outgoing/incoming page against the other route's in-flight URL,
160
+ // and adopting it there produces cross-page renders React discards (#1293).
161
+ const keysChanged =
162
+ Object.keys(queryRef.current).join('&') !== Object.values(resolvedUrlKeys).join('&');
163
+ // `committedPathnameRef` is only ever assigned from the client,
164
+ // so a null value covers both SSR and the first client render.
165
+ const onCommittedPathname =
166
+ committedPathnameRef.current === null ||
167
+ committedPathnameRef.current === (adapter.pathname ?? location.pathname);
168
+ if (keysChanged || (onCommittedPathname && lastSyncKeyRef.current !== searchParamsSyncKey)) {
169
+ lastSyncKeyRef.current = searchParamsSyncKey;
170
+ reconcile();
171
+ if (keysChanged) {
172
+ queryRef.current = Object.fromEntries(
173
+ Object.entries(resolvedUrlKeys).map(([key, urlKey]) => {
174
+ const parser = keyMap[key];
175
+ return [
176
+ urlKey,
177
+ parser?.type === 'multi'
178
+ ? initialSearchParams.getAll(urlKey)
179
+ : (initialSearchParams.get(urlKey) ?? null),
180
+ ];
181
+ }),
182
+ );
183
+ }
184
+ }
185
+
186
+ // Backstop for the render-time reconciliation above: covers external changes
187
+ // landing in renders React discards before commit (e.g. interrupted
188
+ // transitions). Shares the `searchParamsSyncKey` dependency, so they can't
189
+ // drift. Also records the pathname of this committed reconciliation, which
190
+ // gates the render-time branch above (effects don't run while detached, so
191
+ // this freezes at the pathname the hook was last attached on).
192
+ // `adapter.pathname` is a dependency too: a same-search cross-route navigation
193
+ // leaves `searchParamsSyncKey` unchanged, so without it the recorded pathname
194
+ // would stay frozen on the previous route and wrongly gate off the next
195
+ // render-time reconcile there (a stale frame until the next URL change, #1273).
196
+ useEffect(() => {
197
+ committedPathnameRef.current = adapter.pathname ?? location.pathname;
198
+ reconcile();
199
+ }, [searchParamsSyncKey, adapter.pathname]);
200
+
201
+ // Sync all hooks together & with external URL changes
202
+ useEffect(() => {
203
+ const handlers = Object.keys(keyMap).reduce(
204
+ (handlers, stateKey) => {
205
+ handlers[stateKey as keyof KeyMap] = ({ state, query }: CrossHookSyncPayload) => {
206
+ setInternalState((currentState) => {
207
+ const { defaultValue } = keyMap[stateKey]!;
208
+ const urlKey = resolvedUrlKeys[stateKey]!;
209
+ const nextValue = state ?? defaultValue ?? null;
210
+ const currentValue = currentState[stateKey] ?? defaultValue ?? null;
211
+
212
+ if (Object.is(currentValue, nextValue)) {
213
+ debug(2, hookId, stateKeys, urlKey, state, defaultValue, stateRef.current);
214
+ // bail out by returning the current state
215
+ return currentState;
216
+ }
217
+ // Note: cannot mutate in-place, the object ref must change
218
+ // for the subsequent setState to pick it up.
219
+ stateRef.current = {
220
+ ...stateRef.current,
221
+ [stateKey as keyof KeyMap]: nextValue,
222
+ };
223
+ queryRef.current[urlKey] = query;
224
+ debug(3, hookId, stateKeys, urlKey, state, defaultValue, stateRef.current);
225
+ return stateRef.current;
226
+ });
227
+ };
228
+ return handlers;
229
+ },
230
+ {} as Record<keyof KeyMap, (payload: CrossHookSyncPayload) => void>,
231
+ );
232
+
233
+ for (const stateKey of Object.keys(keyMap)) {
234
+ const urlKey = resolvedUrlKeys[stateKey]!;
235
+ debug(4, hookId, urlKey, stateKeys);
236
+ emitter.on(urlKey, handlers[stateKey]!);
237
+ }
238
+ return () => {
239
+ for (const stateKey of Object.keys(keyMap)) {
240
+ const urlKey = resolvedUrlKeys[stateKey]!;
241
+ debug(5, hookId, urlKey, stateKeys);
242
+ emitter.off(urlKey, handlers[stateKey]);
243
+ }
244
+ };
245
+ }, [stateKeys, resolvedUrlKeys]);
246
+
247
+ const update = useCallback<SetValues<KeyMap>>(
248
+ (stateUpdater, callOptions = {}) => {
249
+ const nullMap = Object.fromEntries(
250
+ Object.keys(keyMap).map((key) => [key, null]),
251
+ ) as Nullable<KeyMap>;
252
+ const newState: Partial<Nullable<KeyMap>> =
253
+ typeof stateUpdater === 'function'
254
+ ? (stateUpdater(applyDefaultValues(stateRef.current, defaultValues)) ?? nullMap)
255
+ : (stateUpdater ?? nullMap);
256
+ debug(6, hookId, stateKeys, newState);
257
+ let returnedPromise: Promise<URLSearchParams> | undefined = undefined;
258
+ let maxDebounceTime = 0;
259
+ let doFlush = false;
260
+ const debounceAborts: Array<(p: Promise<URLSearchParams>) => Promise<URLSearchParams>> = [];
261
+ for (let [stateKey, value] of Object.entries(newState)) {
262
+ const parser = keyMap[stateKey];
263
+ const urlKey = resolvedUrlKeys[stateKey]!;
264
+ if (!parser || value === undefined) {
265
+ continue;
266
+ }
267
+ if (
268
+ (callOptions.clearOnDefault ?? parser.clearOnDefault ?? clearOnDefault) &&
269
+ value !== null &&
270
+ parser.defaultValue !== undefined &&
271
+ (parser.eq ?? ((a, b) => a === b))(value, parser.defaultValue)
272
+ ) {
273
+ value = null;
274
+ }
275
+ const query = value === null ? null : (parser.serialize ?? String)(value);
276
+ emitter.emit(urlKey, { state: value, query });
277
+ const update: UpdateQueuePushArgs = {
278
+ key: urlKey,
279
+ query,
280
+ options: {
281
+ // Call-level options take precedence over individual parser options
282
+ // which take precedence over global options
283
+ history: callOptions.history ?? parser.history ?? history,
284
+ shallow: callOptions.shallow ?? parser.shallow ?? shallow,
285
+ scroll: callOptions.scroll ?? parser.scroll ?? scroll,
286
+ startTransition:
287
+ callOptions.startTransition ?? parser.startTransition ?? startTransition,
288
+ },
289
+ };
290
+ const resolvedLimitUrlUpdates =
291
+ callOptions.limitUrlUpdates ?? parser.limitUrlUpdates ?? limitUrlUpdates;
292
+ if (resolvedLimitUrlUpdates?.method === 'debounce') {
293
+ const timeMs = resolvedLimitUrlUpdates.timeMs ?? defaultRateLimit.timeMs;
294
+ const debouncedPromise = debounceController.push(
295
+ update,
296
+ timeMs,
297
+ adapter,
298
+ processUrlSearchParams,
299
+ );
300
+ if (maxDebounceTime < timeMs) {
301
+ // The largest debounce is likely to be the last URL update,
302
+ // so we keep that Promise to return it.
303
+ returnedPromise = debouncedPromise;
304
+ maxDebounceTime = timeMs;
305
+ }
306
+ } else {
307
+ const timeMs =
308
+ resolvedLimitUrlUpdates?.timeMs ??
309
+ callOptions.throttleMs ??
310
+ parser.throttleMs ??
311
+ throttleMs;
312
+ debounceAborts.push(debounceController.abort(urlKey));
313
+ globalThrottleQueue.push(update, timeMs);
314
+ doFlush = true;
315
+ }
316
+ }
317
+ // We need to flush the throttle queue, but we may have a pending
318
+ // debounced update that will resolve afterwards.
319
+ const globalPromise = debounceAborts.reduce(
320
+ (previous, fn) => fn(previous),
321
+ doFlush
322
+ ? globalThrottleQueue.flush(adapter, processUrlSearchParams)
323
+ : globalThrottleQueue.getPendingPromise(adapter),
324
+ );
325
+ return returnedPromise ?? globalPromise;
326
+ },
327
+ [
328
+ stateKeys,
329
+ history,
330
+ shallow,
331
+ scroll,
332
+ throttleMs,
333
+ limitUrlUpdates?.method,
334
+ limitUrlUpdates?.timeMs,
335
+ startTransition,
336
+ resolvedUrlKeys,
337
+ adapter.updateUrl,
338
+ adapter.getSearchParamsSnapshot,
339
+ adapter.rateLimitFactor,
340
+ processUrlSearchParams,
341
+ defaultValues,
342
+ ],
343
+ );
344
+
345
+ const outputState = useMemo(
346
+ () => applyDefaultValues(internalState, defaultValues),
347
+ [internalState, defaultValues],
348
+ );
349
+ return [outputState, update];
350
+ }
351
+
352
+ // --
353
+
354
+ function parseMap<KeyMap extends UseQueryStatesKeysMap>(
355
+ keyMap: KeyMap,
356
+ urlKeys: Partial<Record<keyof KeyMap, string>>,
357
+ searchParams: URLSearchParams,
358
+ queuedQueries: Record<string, Query | null | undefined>,
359
+ cachedQuery?: Record<string, Query | null>,
360
+ cachedState?: NullableValues<KeyMap>,
361
+ ): {
362
+ state: NullableValues<KeyMap>;
363
+ hasChanged: boolean;
364
+ } {
365
+ let hasChanged = false;
366
+ const state = Object.entries(keyMap).reduce((out, [stateKey, parser]) => {
367
+ const urlKey = urlKeys?.[stateKey] ?? stateKey;
368
+ const queuedQuery = queuedQueries[urlKey];
369
+ const fallbackValue = parser.type === 'multi' ? [] : null;
370
+ const query =
371
+ queuedQuery === undefined
372
+ ? ((parser.type === 'multi' ? searchParams.getAll(urlKey) : searchParams.get(urlKey)) ??
373
+ fallbackValue)
374
+ : queuedQuery;
375
+ if (cachedQuery && cachedState && compareQuery(cachedQuery[urlKey] ?? fallbackValue, query)) {
376
+ // Cache hit
377
+ out[stateKey as keyof KeyMap] = cachedState[stateKey] ?? null;
378
+ return out;
379
+ }
380
+ // Cache miss
381
+ hasChanged = true;
382
+ const value = isAbsentFromUrl(query)
383
+ ? null
384
+ : // we have properly narrowed `query` here, but TS doesn't keep track of that
385
+ safeParse(parser.parse, query as string & Array<string>, urlKey);
386
+
387
+ out[stateKey as keyof KeyMap] = value ?? null;
388
+ if (cachedQuery) {
389
+ cachedQuery[urlKey] = query;
390
+ }
391
+ return out;
392
+ }, {} as NullableValues<KeyMap>);
393
+
394
+ if (!hasChanged) {
395
+ // check that keyMap keys have not changed
396
+ const keyMapKeys = Object.keys(keyMap);
397
+ const cachedStateKeys = Object.keys(cachedState ?? {});
398
+ hasChanged =
399
+ keyMapKeys.length !== cachedStateKeys.length ||
400
+ keyMapKeys.some((key) => !cachedStateKeys.includes(key));
401
+ }
402
+
403
+ return { state, hasChanged };
404
+ }
405
+
406
+ function applyDefaultValues<KeyMap extends UseQueryStatesKeysMap>(
407
+ state: NullableValues<KeyMap>,
408
+ defaults: Partial<Values<KeyMap>>,
409
+ ) {
410
+ return Object.fromEntries(
411
+ Object.keys(state).map((key) => [key, state[key] ?? defaults[key] ?? null]),
412
+ ) as Values<KeyMap>;
413
+ }