@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.
- package/LICENSE +21 -0
- package/README.md +92 -0
- package/package.json +58 -0
- package/src/adapters/custom.ts +11 -0
- package/src/adapters/lib/context.ts +94 -0
- package/src/adapters/lib/defs.ts +26 -0
- package/src/adapters/lib/key-isolation.ts +39 -0
- package/src/adapters/lib/patch-history.ts +99 -0
- package/src/adapters/react.ts +123 -0
- package/src/adapters/testing.ts +167 -0
- package/src/debug.ts +42 -0
- package/src/defs.ts +129 -0
- package/src/index.server.ts +23 -0
- package/src/index.ts +14 -0
- package/src/lib/compare.ts +20 -0
- package/src/lib/compose.ts +18 -0
- package/src/lib/debug-messages.ts +92 -0
- package/src/lib/debug.ts +49 -0
- package/src/lib/emitter.ts +36 -0
- package/src/lib/errors.ts +14 -0
- package/src/lib/global-singleton.ts +37 -0
- package/src/lib/queues/debounce.ts +165 -0
- package/src/lib/queues/rate-limiting.ts +30 -0
- package/src/lib/queues/reset.ts +26 -0
- package/src/lib/queues/throttle.ts +207 -0
- package/src/lib/queues/useSyncExternalStores.ts +51 -0
- package/src/lib/safe-parse.ts +20 -0
- package/src/lib/search-params.ts +41 -0
- package/src/lib/sync.ts +16 -0
- package/src/lib/timeout.ts +15 -0
- package/src/lib/url-encoding.ts +65 -0
- package/src/lib/version.ts +3 -0
- package/src/lib/with-resolvers.ts +20 -0
- package/src/loader.ts +154 -0
- package/src/parsers.ts +581 -0
- package/src/serializer.ts +120 -0
- package/src/standard-schema.ts +65 -0
- package/src/testing.ts +167 -0
- package/src/useQueryState.ts +225 -0
- package/src/useQueryStates.ts +413 -0
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { debug } from '../debug';
|
|
2
|
+
import { createEmitter, type Emitter } from '../emitter';
|
|
3
|
+
import { globalSingleton } from '../global-singleton';
|
|
4
|
+
import type { Query } from '../search-params';
|
|
5
|
+
import { timeout } from '../timeout';
|
|
6
|
+
import { withResolvers, type Resolvers } from '../with-resolvers';
|
|
7
|
+
import {
|
|
8
|
+
getSearchParamsSnapshotFromLocation,
|
|
9
|
+
globalThrottleQueue,
|
|
10
|
+
ThrottledQueue,
|
|
11
|
+
type UpdateQueueAdapterContext,
|
|
12
|
+
type UpdateQueuePushArgs,
|
|
13
|
+
} from './throttle';
|
|
14
|
+
import { useSyncExternalStores } from './useSyncExternalStores';
|
|
15
|
+
|
|
16
|
+
export class DebouncedPromiseQueue<ValueType, OutputType> {
|
|
17
|
+
callback: (value: ValueType) => Promise<OutputType>;
|
|
18
|
+
resolvers: Resolvers<OutputType> = withResolvers<OutputType>();
|
|
19
|
+
controller: AbortController = new AbortController();
|
|
20
|
+
queuedValue: ValueType | undefined = undefined;
|
|
21
|
+
|
|
22
|
+
constructor(callback: (value: ValueType) => Promise<OutputType>) {
|
|
23
|
+
this.callback = callback;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
abort(): void {
|
|
27
|
+
this.controller.abort();
|
|
28
|
+
this.queuedValue = undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
push(value: ValueType, timeMs: number): Promise<OutputType> {
|
|
32
|
+
this.queuedValue = value;
|
|
33
|
+
this.controller.abort();
|
|
34
|
+
this.controller = new AbortController();
|
|
35
|
+
timeout(
|
|
36
|
+
() => {
|
|
37
|
+
// Keep the resolvers in a separate variable to reset the queue
|
|
38
|
+
// while the callback is pending, so that the next push can be
|
|
39
|
+
// assigned to a new Promise (and not dropped).
|
|
40
|
+
const outputResolvers = this.resolvers;
|
|
41
|
+
try {
|
|
42
|
+
debug(13, value);
|
|
43
|
+
const callbackPromise = this.callback(value);
|
|
44
|
+
debug(14, this.queuedValue);
|
|
45
|
+
this.queuedValue = undefined;
|
|
46
|
+
this.resolvers = withResolvers<OutputType>();
|
|
47
|
+
callbackPromise
|
|
48
|
+
.then((output) => outputResolvers.resolve(output))
|
|
49
|
+
.catch((error) => outputResolvers.reject(error));
|
|
50
|
+
} catch (error) {
|
|
51
|
+
this.queuedValue = undefined;
|
|
52
|
+
outputResolvers.reject(error);
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
timeMs,
|
|
56
|
+
this.controller.signal,
|
|
57
|
+
);
|
|
58
|
+
return this.resolvers.promise;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// --
|
|
63
|
+
|
|
64
|
+
type DebouncedUpdateQueue = DebouncedPromiseQueue<
|
|
65
|
+
Omit<UpdateQueuePushArgs, 'timeMs'>,
|
|
66
|
+
URLSearchParams
|
|
67
|
+
>;
|
|
68
|
+
|
|
69
|
+
export class DebounceController {
|
|
70
|
+
throttleQueue: ThrottledQueue;
|
|
71
|
+
queues: Map<string, DebouncedUpdateQueue> = new Map();
|
|
72
|
+
queuedQuerySync: Emitter<Record<string, undefined>> = createEmitter();
|
|
73
|
+
|
|
74
|
+
constructor(throttleQueue: ThrottledQueue = new ThrottledQueue()) {
|
|
75
|
+
this.throttleQueue = throttleQueue;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
push(
|
|
79
|
+
update: Omit<UpdateQueuePushArgs, 'timeMs'>,
|
|
80
|
+
timeMs: number,
|
|
81
|
+
adapter: UpdateQueueAdapterContext,
|
|
82
|
+
processUrlSearchParams?: (search: URLSearchParams) => URLSearchParams,
|
|
83
|
+
): Promise<URLSearchParams> {
|
|
84
|
+
if (!Number.isFinite(timeMs)) {
|
|
85
|
+
const getSnapshot = adapter.getSearchParamsSnapshot ?? getSearchParamsSnapshotFromLocation;
|
|
86
|
+
return Promise.resolve(getSnapshot());
|
|
87
|
+
}
|
|
88
|
+
const key = update.key;
|
|
89
|
+
if (!this.queues.has(key)) {
|
|
90
|
+
debug(15, key);
|
|
91
|
+
const queue = new DebouncedPromiseQueue<Omit<UpdateQueuePushArgs, 'timeMs'>, URLSearchParams>(
|
|
92
|
+
(update) => {
|
|
93
|
+
this.throttleQueue.push(update);
|
|
94
|
+
return this.throttleQueue.flush(adapter, processUrlSearchParams).finally(() => {
|
|
95
|
+
const queuedValue = this.queues.get(update.key)?.queuedValue;
|
|
96
|
+
if (queuedValue === undefined) {
|
|
97
|
+
debug(16, update.key);
|
|
98
|
+
this.queues.delete(update.key);
|
|
99
|
+
}
|
|
100
|
+
this.queuedQuerySync.emit(update.key);
|
|
101
|
+
});
|
|
102
|
+
},
|
|
103
|
+
);
|
|
104
|
+
this.queues.set(key, queue);
|
|
105
|
+
}
|
|
106
|
+
debug(17, update);
|
|
107
|
+
const promise = this.queues.get(key)!.push(update, timeMs);
|
|
108
|
+
this.queuedQuerySync.emit(key);
|
|
109
|
+
return promise;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
abort(key: string): (promise: Promise<URLSearchParams>) => Promise<URLSearchParams> {
|
|
113
|
+
const queue = this.queues.get(key);
|
|
114
|
+
if (!queue) {
|
|
115
|
+
return (passThrough) => passThrough;
|
|
116
|
+
}
|
|
117
|
+
debug(18, key, queue.queuedValue?.query);
|
|
118
|
+
this.queues.delete(key);
|
|
119
|
+
queue.abort(); // Don't run to completion
|
|
120
|
+
this.queuedQuerySync.emit(key);
|
|
121
|
+
return (promise) => {
|
|
122
|
+
promise.then(queue.resolvers.resolve, queue.resolvers.reject);
|
|
123
|
+
// Don't chain: keep reference equality
|
|
124
|
+
return promise;
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
abortAll(): void {
|
|
129
|
+
for (const [key, queue] of this.queues.entries()) {
|
|
130
|
+
debug(18, key, queue.queuedValue?.query);
|
|
131
|
+
queue.abort();
|
|
132
|
+
// todo: Better abort handling
|
|
133
|
+
queue.resolvers.resolve(new URLSearchParams()); // Don't leave the Promise pending
|
|
134
|
+
this.queuedQuerySync.emit(key);
|
|
135
|
+
}
|
|
136
|
+
this.queues.clear();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
getQueuedQuery(key: string): Query | null | undefined {
|
|
140
|
+
// The debounced queued values are more likely to be up-to-date
|
|
141
|
+
// than any updates pending in the throttle queue, which comes last
|
|
142
|
+
// in the update chain.
|
|
143
|
+
const debouncedQueued = this.queues.get(key)?.queuedValue?.query;
|
|
144
|
+
if (debouncedQueued !== undefined) {
|
|
145
|
+
return debouncedQueued;
|
|
146
|
+
}
|
|
147
|
+
return this.throttleQueue.getQueuedQuery(key);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export const debounceController: DebounceController = globalSingleton(
|
|
152
|
+
'debounce-controller',
|
|
153
|
+
() => new DebounceController(globalThrottleQueue),
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
// Module-scoped rather than a DebounceController method: the controller is
|
|
157
|
+
// shared across duplicate library copies, and each copy must compose the
|
|
158
|
+
// shared data with hooks from its own React instance.
|
|
159
|
+
export function useQueuedQueries(keys: string[]): Record<string, Query | null | undefined> {
|
|
160
|
+
return useSyncExternalStores(
|
|
161
|
+
keys,
|
|
162
|
+
(key, callback) => debounceController.queuedQuerySync.on(key, callback),
|
|
163
|
+
(key: string) => debounceController.getQueuedQuery(key),
|
|
164
|
+
);
|
|
165
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { LimitUrlUpdates } from '../../defs';
|
|
2
|
+
|
|
3
|
+
// 50ms between calls to the history API seems to satisfy Chrome and Firefox.
|
|
4
|
+
// Safari remains annoying with at most 100 calls in 30 seconds.
|
|
5
|
+
// edit: Safari 17 now allows 100 calls per 10 seconds, a bit better.
|
|
6
|
+
function getDefaultThrottle() {
|
|
7
|
+
if (typeof window === 'undefined') return 50;
|
|
8
|
+
// https://stackoverflow.com/questions/7944460/detect-safari-browser
|
|
9
|
+
// @ts-expect-error
|
|
10
|
+
const isSafari = Boolean(window.GestureEvent);
|
|
11
|
+
if (!isSafari) {
|
|
12
|
+
return 50;
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
const match = navigator.userAgent?.match(/version\/([\d\.]+) safari/i);
|
|
16
|
+
return parseFloat(match![1]!) >= 17 ? 120 : 320;
|
|
17
|
+
} catch {
|
|
18
|
+
return 320;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function throttle(timeMs: number): LimitUrlUpdates {
|
|
23
|
+
return { method: 'throttle', timeMs };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function debounce(timeMs: number): LimitUrlUpdates {
|
|
27
|
+
return { method: 'debounce', timeMs };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const defaultRateLimit: LimitUrlUpdates = throttle(getDefaultThrottle());
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { debug } from '../debug';
|
|
2
|
+
import { globalSingleton } from '../global-singleton';
|
|
3
|
+
import { debounceController } from './debounce';
|
|
4
|
+
import { globalThrottleQueue } from './throttle';
|
|
5
|
+
|
|
6
|
+
const state = globalSingleton('queue-reset', () => ({ mutex: 0 }));
|
|
7
|
+
|
|
8
|
+
export function setQueueResetMutex(value = 1): void {
|
|
9
|
+
state.mutex = value;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function spinQueueResetMutex(onReset: () => void = resetQueues): void {
|
|
13
|
+
// Don't let values become too negatively large and wrap around
|
|
14
|
+
state.mutex = Math.max(0, state.mutex - 1);
|
|
15
|
+
if (state.mutex > 0) {
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
onReset();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function resetQueues(): void {
|
|
22
|
+
debug(19);
|
|
23
|
+
debounceController.abortAll();
|
|
24
|
+
const abortedKeys = globalThrottleQueue.abort();
|
|
25
|
+
abortedKeys.forEach((key) => debounceController.queuedQuerySync.emit(key));
|
|
26
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import type { AdapterInterface, AdapterOptions } from '../../adapters/lib/defs';
|
|
2
|
+
import type { Options, TransitionStartFunction } from '../../defs';
|
|
3
|
+
import { compose } from '../compose';
|
|
4
|
+
import { debug } from '../debug';
|
|
5
|
+
import { error } from '../errors';
|
|
6
|
+
import { globalSingleton } from '../global-singleton';
|
|
7
|
+
import { write, type Query } from '../search-params';
|
|
8
|
+
import { timeout } from '../timeout';
|
|
9
|
+
import { withResolvers, type Resolvers } from '../with-resolvers';
|
|
10
|
+
import { defaultRateLimit } from './rate-limiting';
|
|
11
|
+
|
|
12
|
+
type UpdateMap = Map<string, Query | null>;
|
|
13
|
+
type TransitionSet = Set<TransitionStartFunction>;
|
|
14
|
+
export type UpdateQueueAdapterContext = Pick<
|
|
15
|
+
AdapterInterface,
|
|
16
|
+
'updateUrl' | 'getSearchParamsSnapshot' | 'rateLimitFactor' | 'autoResetQueueOnUpdate'
|
|
17
|
+
>;
|
|
18
|
+
|
|
19
|
+
export type UpdateQueuePushArgs = {
|
|
20
|
+
key: string;
|
|
21
|
+
query: Query | null;
|
|
22
|
+
options: AdapterOptions & Pick<Options, 'startTransition'>;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export function getSearchParamsSnapshotFromLocation(): URLSearchParams {
|
|
26
|
+
return new URLSearchParams(location.search);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class ThrottledQueue {
|
|
30
|
+
updateMap: UpdateMap = new Map();
|
|
31
|
+
options: Required<AdapterOptions> = {
|
|
32
|
+
history: 'replace',
|
|
33
|
+
scroll: false,
|
|
34
|
+
shallow: true,
|
|
35
|
+
};
|
|
36
|
+
timeMs: number = defaultRateLimit.timeMs;
|
|
37
|
+
transitions: TransitionSet = new Set();
|
|
38
|
+
resolvers: Resolvers<URLSearchParams> | null = null;
|
|
39
|
+
controller: AbortController | null = null;
|
|
40
|
+
lastFlushedAt = 0;
|
|
41
|
+
resetQueueOnNextPush = false;
|
|
42
|
+
|
|
43
|
+
push(
|
|
44
|
+
{ key, query, options }: UpdateQueuePushArgs,
|
|
45
|
+
timeMs: number = defaultRateLimit.timeMs,
|
|
46
|
+
): void {
|
|
47
|
+
if (this.resetQueueOnNextPush) {
|
|
48
|
+
this.reset();
|
|
49
|
+
this.resetQueueOnNextPush = false;
|
|
50
|
+
}
|
|
51
|
+
debug(7, key, query, options);
|
|
52
|
+
// Enqueue update
|
|
53
|
+
this.updateMap.set(key, query);
|
|
54
|
+
if (options.history === 'push') {
|
|
55
|
+
this.options.history = 'push';
|
|
56
|
+
}
|
|
57
|
+
if (options.scroll) {
|
|
58
|
+
this.options.scroll = true;
|
|
59
|
+
}
|
|
60
|
+
if (options.shallow === false) {
|
|
61
|
+
this.options.shallow = false;
|
|
62
|
+
}
|
|
63
|
+
if (options.startTransition) {
|
|
64
|
+
this.transitions.add(options.startTransition);
|
|
65
|
+
}
|
|
66
|
+
// Keep the maximum finite throttle value (or set if previous was Infinity)
|
|
67
|
+
if (!Number.isFinite(this.timeMs) || timeMs > this.timeMs) {
|
|
68
|
+
this.timeMs = timeMs;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
getQueuedQuery(key: string): Query | null | undefined {
|
|
73
|
+
return this.updateMap.get(key);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
getPendingPromise({
|
|
77
|
+
getSearchParamsSnapshot = getSearchParamsSnapshotFromLocation,
|
|
78
|
+
}: UpdateQueueAdapterContext): Promise<URLSearchParams> {
|
|
79
|
+
return this.resolvers?.promise ?? Promise.resolve(getSearchParamsSnapshot());
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
flush(
|
|
83
|
+
{
|
|
84
|
+
getSearchParamsSnapshot = getSearchParamsSnapshotFromLocation,
|
|
85
|
+
rateLimitFactor = 1,
|
|
86
|
+
...adapter
|
|
87
|
+
}: UpdateQueueAdapterContext,
|
|
88
|
+
processUrlSearchParams?: (search: URLSearchParams) => URLSearchParams,
|
|
89
|
+
): Promise<URLSearchParams> {
|
|
90
|
+
this.controller ??= new AbortController();
|
|
91
|
+
if (!Number.isFinite(this.timeMs)) {
|
|
92
|
+
debug(8);
|
|
93
|
+
return Promise.resolve(getSearchParamsSnapshot());
|
|
94
|
+
}
|
|
95
|
+
if (this.resolvers) {
|
|
96
|
+
// Flush already scheduled
|
|
97
|
+
return this.resolvers.promise;
|
|
98
|
+
}
|
|
99
|
+
this.resolvers = withResolvers<URLSearchParams>();
|
|
100
|
+
const flushNow = () => {
|
|
101
|
+
this.lastFlushedAt = performance.now();
|
|
102
|
+
const [search, error] = this.applyPendingUpdates(
|
|
103
|
+
{
|
|
104
|
+
...adapter,
|
|
105
|
+
autoResetQueueOnUpdate: adapter.autoResetQueueOnUpdate ?? true,
|
|
106
|
+
getSearchParamsSnapshot,
|
|
107
|
+
},
|
|
108
|
+
processUrlSearchParams,
|
|
109
|
+
);
|
|
110
|
+
if (error === null) {
|
|
111
|
+
this.resolvers!.resolve(search);
|
|
112
|
+
this.resetQueueOnNextPush = true;
|
|
113
|
+
} else {
|
|
114
|
+
this.resolvers!.reject(search);
|
|
115
|
+
}
|
|
116
|
+
this.resolvers = null;
|
|
117
|
+
};
|
|
118
|
+
// We run the logic on the next event loop tick to allow
|
|
119
|
+
// multiple query updates to batch in the same event loop tick
|
|
120
|
+
// and possibly set their own throttleMs value.
|
|
121
|
+
const runOnNextTick = () => {
|
|
122
|
+
const now = performance.now();
|
|
123
|
+
const timeSinceLastFlush = now - this.lastFlushedAt;
|
|
124
|
+
const timeMs = this.timeMs;
|
|
125
|
+
const flushInMs = rateLimitFactor * Math.max(0, timeMs - timeSinceLastFlush);
|
|
126
|
+
debug(9, flushInMs, timeMs, rateLimitFactor);
|
|
127
|
+
if (flushInMs === 0) {
|
|
128
|
+
// Since we're already in the "next tick" from queued updates,
|
|
129
|
+
// no need to do setTimeout(0) here.
|
|
130
|
+
flushNow();
|
|
131
|
+
} else {
|
|
132
|
+
timeout(flushNow, flushInMs, this.controller!.signal);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
timeout(runOnNextTick, 0, this.controller.signal);
|
|
136
|
+
return this.resolvers.promise;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
abort(): string[] {
|
|
140
|
+
this.controller?.abort();
|
|
141
|
+
this.controller = new AbortController();
|
|
142
|
+
// todo: Better abort handling
|
|
143
|
+
this.resolvers?.resolve(new URLSearchParams());
|
|
144
|
+
this.resolvers = null;
|
|
145
|
+
return this.reset();
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
reset(): string[] {
|
|
149
|
+
const queuedKeys = Array.from(this.updateMap.keys());
|
|
150
|
+
debug(10, JSON.stringify(Object.fromEntries(this.updateMap)));
|
|
151
|
+
this.updateMap.clear();
|
|
152
|
+
this.transitions.clear();
|
|
153
|
+
this.options = {
|
|
154
|
+
history: 'replace',
|
|
155
|
+
scroll: false,
|
|
156
|
+
shallow: true,
|
|
157
|
+
};
|
|
158
|
+
this.timeMs = defaultRateLimit.timeMs;
|
|
159
|
+
return queuedKeys;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
applyPendingUpdates(
|
|
163
|
+
adapter: Required<Omit<UpdateQueueAdapterContext, 'rateLimitFactor'>>,
|
|
164
|
+
processUrlSearchParams?: (search: URLSearchParams) => URLSearchParams,
|
|
165
|
+
): [URLSearchParams, null | unknown] {
|
|
166
|
+
const { updateUrl, getSearchParamsSnapshot } = adapter;
|
|
167
|
+
let search = getSearchParamsSnapshot();
|
|
168
|
+
debug(11, this.updateMap.size, search.toString());
|
|
169
|
+
if (this.updateMap.size === 0) {
|
|
170
|
+
return [search, null];
|
|
171
|
+
}
|
|
172
|
+
// Work on a copy and clear the queue immediately
|
|
173
|
+
const items = Array.from(this.updateMap.entries());
|
|
174
|
+
const options = { ...this.options };
|
|
175
|
+
const transitions = Array.from(this.transitions);
|
|
176
|
+
// Let the adapters choose whether to reset, as it depends on how they
|
|
177
|
+
// handle concurrent rendering (see the life-and-death.cy.ts e2e test).
|
|
178
|
+
if (adapter.autoResetQueueOnUpdate) {
|
|
179
|
+
this.reset();
|
|
180
|
+
}
|
|
181
|
+
debug(12, items, options);
|
|
182
|
+
for (const [key, value] of items) {
|
|
183
|
+
if (value === null) {
|
|
184
|
+
search.delete(key);
|
|
185
|
+
} else {
|
|
186
|
+
search = write(search, key, value);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (processUrlSearchParams) {
|
|
190
|
+
search = processUrlSearchParams(search);
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
compose(transitions, () => updateUrl(search, options));
|
|
194
|
+
return [search, null];
|
|
195
|
+
} catch (err) {
|
|
196
|
+
// This may fail due to rate-limiting of history methods,
|
|
197
|
+
// for example Safari only allows 100 updates in a 30s window.
|
|
198
|
+
console.error(error(429), items.map(([key]) => key).join(), err);
|
|
199
|
+
return [search, err];
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export const globalThrottleQueue: ThrottledQueue = globalSingleton(
|
|
205
|
+
'throttle-queue',
|
|
206
|
+
() => new ThrottledQueue(),
|
|
207
|
+
);
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { useCallback, useRef, useSyncExternalStore } from 'octane';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Like `useSyncExternalStore`, but for subscribing to multiple keys.
|
|
5
|
+
*
|
|
6
|
+
* Each key becomes the key of the returned object,
|
|
7
|
+
* and the value is the result of calling `getKeySnapshot` with that key.
|
|
8
|
+
*
|
|
9
|
+
* @param keys - A list of keys to subscribe to.
|
|
10
|
+
* @param subscribeKey - A function that takes a key and a callback,
|
|
11
|
+
* subscribes to an external store using that key (calling the callback when
|
|
12
|
+
* state changes occur), and returns a function to unsubscribe from that key.
|
|
13
|
+
* @param getKeySnapshot - A function that takes a key and returns the snapshot for that key.
|
|
14
|
+
* It will be called on the server and on the client, so it needs to handle both
|
|
15
|
+
* environments.
|
|
16
|
+
*/
|
|
17
|
+
export function useSyncExternalStores<T>(
|
|
18
|
+
keys: string[],
|
|
19
|
+
subscribeKey: (key: string, callback: () => void) => () => void,
|
|
20
|
+
getKeySnapshot: (key: string) => T,
|
|
21
|
+
): Record<string, T> {
|
|
22
|
+
const snapshot = useCallback((): [string, Record<string, T>] => {
|
|
23
|
+
const record = Object.fromEntries(keys.map((key) => [key, getKeySnapshot(key)]));
|
|
24
|
+
const cacheKey = JSON.stringify(record);
|
|
25
|
+
return [cacheKey, record];
|
|
26
|
+
}, [keys.join(','), getKeySnapshot]);
|
|
27
|
+
const cacheRef = useRef<null | [string, Record<string, T>]>(null);
|
|
28
|
+
// Initialize the cache with the initial snapshot
|
|
29
|
+
if (cacheRef.current === null) {
|
|
30
|
+
cacheRef.current = snapshot();
|
|
31
|
+
}
|
|
32
|
+
const subscribe = useCallback(
|
|
33
|
+
(callback: () => void) => {
|
|
34
|
+
const off = keys.map((key) => subscribeKey(key, callback));
|
|
35
|
+
return () => off.forEach((unsubscribe) => unsubscribe());
|
|
36
|
+
},
|
|
37
|
+
[keys.join(','), subscribeKey],
|
|
38
|
+
);
|
|
39
|
+
return useSyncExternalStore<Record<string, T>>(
|
|
40
|
+
subscribe,
|
|
41
|
+
() => {
|
|
42
|
+
const [cacheKey, record] = snapshot();
|
|
43
|
+
if (cacheRef.current![0] === cacheKey) {
|
|
44
|
+
return cacheRef.current![1]!;
|
|
45
|
+
}
|
|
46
|
+
cacheRef.current = [cacheKey, record];
|
|
47
|
+
return record;
|
|
48
|
+
},
|
|
49
|
+
() => cacheRef.current![1]!,
|
|
50
|
+
);
|
|
51
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { warn } from './debug';
|
|
2
|
+
|
|
3
|
+
export function safeParse<I extends { toString(): string }, R>(
|
|
4
|
+
parser: (arg: I) => R,
|
|
5
|
+
value: I,
|
|
6
|
+
key?: string,
|
|
7
|
+
): R | null {
|
|
8
|
+
try {
|
|
9
|
+
return parser(value);
|
|
10
|
+
} catch (error) {
|
|
11
|
+
// Split per code so each call matches its message's arity exactly (a single
|
|
12
|
+
// `key ? 25 : 24` would widen the argument tuple to a union).
|
|
13
|
+
if (key) {
|
|
14
|
+
warn(25, value, error, key);
|
|
15
|
+
} else {
|
|
16
|
+
warn(24, value, error);
|
|
17
|
+
}
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export type Query = string | Array<string>;
|
|
2
|
+
|
|
3
|
+
export function isAbsentFromUrl(query: Query | null): query is null | [] {
|
|
4
|
+
return query === null || (Array.isArray(query) && query.length === 0);
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function write(
|
|
8
|
+
searchParams: URLSearchParams,
|
|
9
|
+
key: string,
|
|
10
|
+
serialized: Query,
|
|
11
|
+
): URLSearchParams {
|
|
12
|
+
if (typeof serialized === 'string') {
|
|
13
|
+
searchParams.set(key, serialized);
|
|
14
|
+
} else {
|
|
15
|
+
searchParams.delete(key);
|
|
16
|
+
for (const v of serialized) {
|
|
17
|
+
searchParams.append(key, v);
|
|
18
|
+
}
|
|
19
|
+
// if we get here with an empty iterable, no values were appended
|
|
20
|
+
// however, an empty iterable here means we explicitly want to set the key
|
|
21
|
+
// because for default values, we don't call write at all
|
|
22
|
+
if (!searchParams.has(key)) {
|
|
23
|
+
searchParams.set(key, '');
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return searchParams;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function getSearchParams(url: string | URL): URLSearchParams {
|
|
30
|
+
if (url instanceof URL) {
|
|
31
|
+
return url.searchParams;
|
|
32
|
+
}
|
|
33
|
+
if (url.startsWith('?')) {
|
|
34
|
+
return new URLSearchParams(url);
|
|
35
|
+
}
|
|
36
|
+
try {
|
|
37
|
+
return new URL(url, location.origin).searchParams;
|
|
38
|
+
} catch {
|
|
39
|
+
return new URLSearchParams(url);
|
|
40
|
+
}
|
|
41
|
+
}
|
package/src/lib/sync.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createEmitter, type Emitter } from './emitter';
|
|
2
|
+
import { globalSingleton } from './global-singleton';
|
|
3
|
+
import type { Query } from './search-params';
|
|
4
|
+
|
|
5
|
+
export type CrossHookSyncPayload = {
|
|
6
|
+
state: any;
|
|
7
|
+
query: Query | null;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
type EventMap = {
|
|
11
|
+
[key: string]: CrossHookSyncPayload;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export const emitter: Emitter<EventMap> = globalSingleton('sync-emitter', () =>
|
|
15
|
+
createEmitter<EventMap>(),
|
|
16
|
+
);
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Source:
|
|
2
|
+
// https://www.bennadel.com/blog/4195-using-abortcontroller-to-debounce-settimeout-calls-in-javascript.htm
|
|
3
|
+
|
|
4
|
+
export function timeout(callback: () => void, ms: number, signal: AbortSignal): void {
|
|
5
|
+
function onTick() {
|
|
6
|
+
callback();
|
|
7
|
+
signal.removeEventListener('abort', onAbort);
|
|
8
|
+
}
|
|
9
|
+
const id = setTimeout(onTick, ms);
|
|
10
|
+
function onAbort() {
|
|
11
|
+
clearTimeout(id);
|
|
12
|
+
signal.removeEventListener('abort', onAbort);
|
|
13
|
+
}
|
|
14
|
+
signal.addEventListener('abort', onAbort);
|
|
15
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { error } from './errors';
|
|
2
|
+
|
|
3
|
+
export function renderQueryString(search: URLSearchParams): string {
|
|
4
|
+
if (search.size === 0) {
|
|
5
|
+
return '';
|
|
6
|
+
}
|
|
7
|
+
const query: string[] = [];
|
|
8
|
+
for (const [key, value] of search.entries()) {
|
|
9
|
+
// Replace disallowed characters in keys,
|
|
10
|
+
// see https://github.com/47ng/nuqs/issues/599
|
|
11
|
+
const safeKey = key
|
|
12
|
+
.replace(/#/g, '%23')
|
|
13
|
+
.replace(/&/g, '%26')
|
|
14
|
+
.replace(/\+/g, '%2B')
|
|
15
|
+
.replace(/=/g, '%3D')
|
|
16
|
+
.replace(/\?/g, '%3F');
|
|
17
|
+
query.push(`${safeKey}=${encodeQueryValue(value)}`);
|
|
18
|
+
}
|
|
19
|
+
const queryString = '?' + query.join('&');
|
|
20
|
+
warnIfURLIsTooLong(queryString);
|
|
21
|
+
return queryString;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function encodeQueryValue(input: string): string {
|
|
25
|
+
return (
|
|
26
|
+
input
|
|
27
|
+
// Encode existing % signs first to avoid appearing
|
|
28
|
+
// as an incomplete escape sequence:
|
|
29
|
+
.replace(/%/g, '%25')
|
|
30
|
+
// Note: spaces are encoded as + in RFC 3986,
|
|
31
|
+
// so we pre-encode existing + signs to avoid confusion
|
|
32
|
+
// before converting spaces to + signs.
|
|
33
|
+
.replace(/\+/g, '%2B')
|
|
34
|
+
.replace(/ /g, '+')
|
|
35
|
+
// Encode other URI-reserved characters
|
|
36
|
+
.replace(/#/g, '%23')
|
|
37
|
+
.replace(/&/g, '%26')
|
|
38
|
+
// Encode characters that break URL detection on some platforms
|
|
39
|
+
// and would drop the tail end of the querystring:
|
|
40
|
+
.replace(/"/g, '%22')
|
|
41
|
+
.replace(/'/g, '%27')
|
|
42
|
+
.replace(/`/g, '%60')
|
|
43
|
+
.replace(/</g, '%3C')
|
|
44
|
+
.replace(/>/g, '%3E')
|
|
45
|
+
// Encode invisible ASCII control characters
|
|
46
|
+
.replace(/[\x00-\x1F]/g, (char) => encodeURIComponent(char))
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Note: change error documentation (NUQS-414) when changing this value.
|
|
51
|
+
const URL_MAX_LENGTH = 2000;
|
|
52
|
+
|
|
53
|
+
function warnIfURLIsTooLong(queryString: string): void {
|
|
54
|
+
if (process.env.NODE_ENV === 'production') {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
if (typeof location === 'undefined') {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const url = new URL(location.href);
|
|
61
|
+
url.search = queryString;
|
|
62
|
+
if (url.href.length > URL_MAX_LENGTH) {
|
|
63
|
+
console.warn(error(414));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export type Resolvers<T> = {
|
|
2
|
+
promise: Promise<T>;
|
|
3
|
+
resolve: (value: T | PromiseLike<T>) => void;
|
|
4
|
+
reject: (reason?: any) => void;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
export function withResolvers<T>(): Resolvers<T> {
|
|
8
|
+
const P = Promise<T>;
|
|
9
|
+
if (Promise.hasOwnProperty('withResolvers')) {
|
|
10
|
+
return Promise.withResolvers<T>();
|
|
11
|
+
}
|
|
12
|
+
// todo: Remove this once Promise.withResolvers is Baseline GA (September 2026)
|
|
13
|
+
let resolve: (value: T | PromiseLike<T>) => void = () => {};
|
|
14
|
+
let reject: () => void = () => {};
|
|
15
|
+
const promise = new P((res, rej) => {
|
|
16
|
+
resolve = res;
|
|
17
|
+
reject = rej;
|
|
18
|
+
});
|
|
19
|
+
return { promise, resolve, reject };
|
|
20
|
+
}
|