@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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dominic Gannaway
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# @octanejs/nuqs
|
|
2
|
+
|
|
3
|
+
[nuqs](https://nuqs.dev) for the [octane](https://github.com/octanejs/octane) UI
|
|
4
|
+
framework — type-safe search-params state as octane hooks.
|
|
5
|
+
|
|
6
|
+
nuqs cleanly separates a **framework-agnostic core** (the `parseAs*` parsers,
|
|
7
|
+
`createParser`, `createSerializer`, `createLoader`, `createStandardSchemaV1`, and
|
|
8
|
+
the throttle/debounce update queues) from a small **React binding**
|
|
9
|
+
(`useQueryState`, `useQueryStates`, and the adapter context). This package
|
|
10
|
+
vendors the core verbatim from nuqs 2.9.1 and reimplements only the binding on
|
|
11
|
+
octane's hooks — keeping upstream's implementation shape (`useSyncExternalStore`
|
|
12
|
+
over `location.search`, render-time URL reconciliation, the shared throttle
|
|
13
|
+
queue), so re-render and URL-sync behavior match nuqs on React. The public
|
|
14
|
+
surface matches nuqs 1:1 — existing nuqs code works by changing the import.
|
|
15
|
+
|
|
16
|
+
```tsx
|
|
17
|
+
// before
|
|
18
|
+
import { useQueryState, parseAsInteger } from 'nuqs';
|
|
19
|
+
// after
|
|
20
|
+
import { useQueryState, parseAsInteger } from '@octanejs/nuqs';
|
|
21
|
+
|
|
22
|
+
function Counter() @{
|
|
23
|
+
const [count, setCount] = useQueryState('count', parseAsInteger.withDefault(0));
|
|
24
|
+
<button onClick={() => setCount((c) => (c ?? 0) + 1)}>count is {count as string}</button>
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Wrap your app in an adapter once, at the root:
|
|
29
|
+
|
|
30
|
+
```tsx
|
|
31
|
+
import { NuqsAdapter } from '@octanejs/nuqs/adapters/react';
|
|
32
|
+
|
|
33
|
+
function App() @{
|
|
34
|
+
<NuqsAdapter>
|
|
35
|
+
<Counter />
|
|
36
|
+
</NuqsAdapter>
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Entry points
|
|
41
|
+
|
|
42
|
+
| import | what you get | notes |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| `@octanejs/nuqs` | `useQueryState`, `useQueryStates`, all `parseAs*` parsers, `createParser`, `createSerializer`, `createLoader`, `createStandardSchemaV1` | core vendored verbatim + the octane-bound hooks |
|
|
45
|
+
| `@octanejs/nuqs/server` | `createLoader`, `createSerializer`, parsers, `createStandardSchemaV1` | react-free, safe to import from server-only modules |
|
|
46
|
+
| `@octanejs/nuqs/adapters/react` | `NuqsAdapter`, `enableHistorySync` | the standalone (router-less) adapter, ported to octane |
|
|
47
|
+
| `@octanejs/nuqs/adapters/custom` | `unstable_createAdapterProvider`, `renderQueryString` + adapter types | build an adapter for your own router |
|
|
48
|
+
| `@octanejs/nuqs/adapters/testing` | `NuqsTestingAdapter`, `withNuqsTestingAdapter` | in-memory adapter for tests |
|
|
49
|
+
| `@octanejs/nuqs/testing` | `isParserBijective`, `testParseThenSerialize`, `testSerializeThenParse` | parser test helpers (framework-agnostic) |
|
|
50
|
+
| `@octanejs/nuqs/debug` | side-effect import | opt debug logging into the bundle (`localStorage.debug = 'nuqs'`) |
|
|
51
|
+
|
|
52
|
+
## How it works
|
|
53
|
+
|
|
54
|
+
octane keys hooks by a compiler-injected per-call-site `Symbol` and transforms
|
|
55
|
+
raw-source octane packages automatically, so the ported hooks are written as
|
|
56
|
+
ordinary `use*` calls (no manual slot bookkeeping) — `useQueryState('a')` and
|
|
57
|
+
`useQueryState('b')` in one component stay independent, exactly like distinct
|
|
58
|
+
call sites in React.
|
|
59
|
+
|
|
60
|
+
`useQueryStates` is a line-for-line port of nuqs's implementation: it reads the
|
|
61
|
+
URL through the active adapter's `useSyncExternalStore`, reconciles the parsed
|
|
62
|
+
values into `useState` both during render and from an effect backstop, and
|
|
63
|
+
writes updates through nuqs's shared throttle/debounce queue. That means the same
|
|
64
|
+
observable behavior as nuqs on React, including:
|
|
65
|
+
|
|
66
|
+
- **Read the default, write the URL.** A missing key resolves to the parser's
|
|
67
|
+
default without polluting the URL; the key is written only once the value
|
|
68
|
+
diverges.
|
|
69
|
+
- **`clearOnDefault`.** Setting a value back to its default removes the key from
|
|
70
|
+
the URL (opt out per-call, per-parser, or per-adapter).
|
|
71
|
+
- **Cross-hook sync.** Two components bound to the same key update together, and
|
|
72
|
+
external `popstate`/history changes reconcile into state.
|
|
73
|
+
- **Throttled updates.** Rapid setter calls coalesce through the shared queue and
|
|
74
|
+
return a `Promise<URLSearchParams>` that resolves once the URL has committed.
|
|
75
|
+
|
|
76
|
+
## Divergences from nuqs
|
|
77
|
+
|
|
78
|
+
- **Router adapters for other React routers are not shipped**:
|
|
79
|
+
`nuqs/adapters/next`, `/adapters/remix`, `/adapters/react-router`, and
|
|
80
|
+
`/adapters/tanstack-router` each bind a React router that would need its own
|
|
81
|
+
octane port. Use `/adapters/react`, or `/adapters/custom` to wire your router.
|
|
82
|
+
- **`createSearchParamsCache` is not ported.** It is built on React Server
|
|
83
|
+
Components' `React.cache()`, which octane does not implement (no Server
|
|
84
|
+
Components). Use `createLoader` for request-scoped parsing.
|
|
85
|
+
- `TransitionStartFunction` is declared locally, so the package carries no
|
|
86
|
+
`@types/react` dependency.
|
|
87
|
+
|
|
88
|
+
## Status
|
|
89
|
+
|
|
90
|
+
Alpha, like octane itself. See [`status.json`](./status.json) and the generated
|
|
91
|
+
[bindings status table](../../docs/bindings-status.md) for the verified surface,
|
|
92
|
+
divergences, and last evidence check.
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@octanejs/nuqs",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=22"
|
|
8
|
+
},
|
|
9
|
+
"description": "nuqs for the octane renderer — the nuqs 2.9.1 source ported onto octane's hooks: type-safe search params state (useQueryState/useQueryStates), the framework-agnostic parsers/serializer/loader reused verbatim, plus the React, custom and testing adapters.",
|
|
10
|
+
"author": {
|
|
11
|
+
"name": "Dominic Gannaway",
|
|
12
|
+
"email": "dg@domgan.com"
|
|
13
|
+
},
|
|
14
|
+
"publishConfig": {
|
|
15
|
+
"access": "public"
|
|
16
|
+
},
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/octanejs/octane.git",
|
|
20
|
+
"directory": "packages/nuqs"
|
|
21
|
+
},
|
|
22
|
+
"main": "src/index.ts",
|
|
23
|
+
"module": "src/index.ts",
|
|
24
|
+
"types": "src/index.ts",
|
|
25
|
+
"files": [
|
|
26
|
+
"src",
|
|
27
|
+
"README.md"
|
|
28
|
+
],
|
|
29
|
+
"exports": {
|
|
30
|
+
".": "./src/index.ts",
|
|
31
|
+
"./server": "./src/index.server.ts",
|
|
32
|
+
"./testing": "./src/testing.ts",
|
|
33
|
+
"./debug": "./src/debug.ts",
|
|
34
|
+
"./adapters/react": "./src/adapters/react.ts",
|
|
35
|
+
"./adapters/custom": "./src/adapters/custom.ts",
|
|
36
|
+
"./adapters/testing": "./src/adapters/testing.ts"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@standard-schema/spec": "1.1.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"octane": "0.1.11"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@testing-library/jest-dom": "^6.9.1",
|
|
46
|
+
"@tsrx/react": "^0.2.44",
|
|
47
|
+
"esbuild": "^0.28.1",
|
|
48
|
+
"nuqs": "2.9.1",
|
|
49
|
+
"react": "^19.2.0",
|
|
50
|
+
"react-dom": "^19.2.0",
|
|
51
|
+
"vitest": "^4.1.9",
|
|
52
|
+
"@octanejs/testing-library": "0.1.8",
|
|
53
|
+
"octane": "0.1.11"
|
|
54
|
+
},
|
|
55
|
+
"scripts": {
|
|
56
|
+
"test": "vitest run"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { renderQueryString } from '../lib/url-encoding';
|
|
2
|
+
export {
|
|
3
|
+
createAdapterProvider as unstable_createAdapterProvider,
|
|
4
|
+
type AdapterContext as unstable_AdapterContext,
|
|
5
|
+
} from './lib/context';
|
|
6
|
+
export type {
|
|
7
|
+
AdapterInterface as unstable_AdapterInterface,
|
|
8
|
+
AdapterOptions as unstable_AdapterOptions,
|
|
9
|
+
UpdateUrlFunction as unstable_UpdateUrlFunction,
|
|
10
|
+
UseAdapterHook as unstable_UseAdapterHook,
|
|
11
|
+
} from './lib/defs';
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createContext, createElement, useContext, type Context, type OctaneNode } from 'octane';
|
|
2
|
+
import type { Options } from '../../defs';
|
|
3
|
+
import { error } from '../../lib/errors';
|
|
4
|
+
import { globalWeakSingleton } from '../../lib/global-singleton';
|
|
5
|
+
import type { AdapterInterface, UseAdapterHook } from './defs';
|
|
6
|
+
|
|
7
|
+
export type AdapterProps = {
|
|
8
|
+
defaultOptions?: Partial<
|
|
9
|
+
Pick<Options, 'history' | 'shallow' | 'clearOnDefault' | 'scroll' | 'limitUrlUpdates'>
|
|
10
|
+
>;
|
|
11
|
+
processUrlSearchParams?: (search: URLSearchParams) => URLSearchParams;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export type AdapterContext = AdapterProps & {
|
|
15
|
+
useAdapter: UseAdapterHook;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// Keyed by createContext identity: copies sharing one octane instance share
|
|
19
|
+
// the context, while distinct octane instances keep isolated contexts. Same
|
|
20
|
+
// dedup hazard as @octanejs/jotai's store context and @octanejs/redux's
|
|
21
|
+
// Context — duplicate module instances under Vite dev would otherwise each
|
|
22
|
+
// mint their own context object, and a Provider from one would be invisible to
|
|
23
|
+
// a consumer reading the other.
|
|
24
|
+
export const context: Context<AdapterContext> = globalWeakSingleton(
|
|
25
|
+
'adapter-context',
|
|
26
|
+
createContext,
|
|
27
|
+
() => {
|
|
28
|
+
const ctx = createContext<AdapterContext>({
|
|
29
|
+
useAdapter() {
|
|
30
|
+
throw new Error(error(404));
|
|
31
|
+
},
|
|
32
|
+
});
|
|
33
|
+
// Octane's Context carries no `displayName`; assign for parity with
|
|
34
|
+
// upstream (harmless if unused by tooling).
|
|
35
|
+
(ctx as { displayName?: string }).displayName = 'NuqsAdapterContext';
|
|
36
|
+
return ctx;
|
|
37
|
+
},
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
declare global {
|
|
41
|
+
interface Window {
|
|
42
|
+
__NuqsAdapterContext?: typeof context;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Detect adapter contexts that cannot be shared across duplicate copies:
|
|
47
|
+
// nuqs version mismatch, or multiple octane instances. Same-version copies
|
|
48
|
+
// on one octane runtime share a single context via globalWeakSingleton above.
|
|
49
|
+
if (typeof window !== 'undefined') {
|
|
50
|
+
if (window.__NuqsAdapterContext && window.__NuqsAdapterContext !== context) {
|
|
51
|
+
console.error(error(303));
|
|
52
|
+
}
|
|
53
|
+
window.__NuqsAdapterContext = context;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type AdapterProvider = (
|
|
57
|
+
props: AdapterProps & {
|
|
58
|
+
children: OctaneNode;
|
|
59
|
+
},
|
|
60
|
+
) => OctaneNode;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Create a custom adapter (context provider) for nuqs to work with your framework / router.
|
|
64
|
+
*
|
|
65
|
+
* Adapters are based on octane Context.
|
|
66
|
+
*
|
|
67
|
+
* @param useAdapter
|
|
68
|
+
* @returns
|
|
69
|
+
*/
|
|
70
|
+
export function createAdapterProvider(useAdapter: UseAdapterHook): AdapterProvider {
|
|
71
|
+
return ({ children, defaultOptions, processUrlSearchParams, ...props }) =>
|
|
72
|
+
createElement(
|
|
73
|
+
context.Provider,
|
|
74
|
+
{
|
|
75
|
+
...props,
|
|
76
|
+
value: { useAdapter, defaultOptions, processUrlSearchParams },
|
|
77
|
+
},
|
|
78
|
+
children,
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function useAdapter(watchKeys: string[]): AdapterInterface {
|
|
83
|
+
const value = useContext(context);
|
|
84
|
+
if (!('useAdapter' in value)) {
|
|
85
|
+
throw new Error(error(404));
|
|
86
|
+
}
|
|
87
|
+
return value.useAdapter(watchKeys);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const useAdapterDefaultOptions = (): AdapterProps['defaultOptions'] =>
|
|
91
|
+
useContext(context).defaultOptions;
|
|
92
|
+
|
|
93
|
+
export const useAdapterProcessUrlSearchParams = (): AdapterProps['processUrlSearchParams'] =>
|
|
94
|
+
useContext(context).processUrlSearchParams;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { Options } from '../../defs';
|
|
2
|
+
|
|
3
|
+
export type AdapterOptions = Pick<Options, 'history' | 'scroll' | 'shallow'>;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Optionally return a Promise that resolves when the router has fully applied
|
|
7
|
+
* the update (eg: after navigation and route loaders settle). It is passed to
|
|
8
|
+
* the user's startTransition, keeping its isPending flag true until settlement
|
|
9
|
+
* on React 19. The Promise should not reject: rejections bypass nuqs and
|
|
10
|
+
* surface through React's transition error handling.
|
|
11
|
+
*/
|
|
12
|
+
export type UpdateUrlFunction = (
|
|
13
|
+
search: URLSearchParams,
|
|
14
|
+
options: Required<AdapterOptions>,
|
|
15
|
+
) => void | Promise<void>;
|
|
16
|
+
|
|
17
|
+
export type UseAdapterHook = (watchKeys: string[]) => AdapterInterface;
|
|
18
|
+
|
|
19
|
+
export type AdapterInterface = {
|
|
20
|
+
searchParams: URLSearchParams;
|
|
21
|
+
pathname?: string;
|
|
22
|
+
updateUrl: UpdateUrlFunction;
|
|
23
|
+
getSearchParamsSnapshot?: () => URLSearchParams;
|
|
24
|
+
rateLimitFactor?: number;
|
|
25
|
+
autoResetQueueOnUpdate?: boolean;
|
|
26
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { debug } from '../../lib/debug';
|
|
2
|
+
import { compareQuery } from '../../lib/compare';
|
|
3
|
+
|
|
4
|
+
export function applyChange(
|
|
5
|
+
newValue: URLSearchParams,
|
|
6
|
+
keys: string[],
|
|
7
|
+
copy: boolean,
|
|
8
|
+
): (oldValue: URLSearchParams) => URLSearchParams {
|
|
9
|
+
return (oldValue: URLSearchParams) => {
|
|
10
|
+
const hasChanged =
|
|
11
|
+
keys.length === 0
|
|
12
|
+
? true
|
|
13
|
+
: keys.some((key) => !compareQuery(oldValue.getAll(key), newValue.getAll(key)));
|
|
14
|
+
if (!hasChanged) {
|
|
15
|
+
debug(22, keys.join(','), oldValue);
|
|
16
|
+
return oldValue;
|
|
17
|
+
}
|
|
18
|
+
const filtered = filterSearchParams(newValue, keys, copy);
|
|
19
|
+
debug(23, keys.join(','), oldValue, filtered);
|
|
20
|
+
return filtered;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function filterSearchParams(
|
|
25
|
+
search: URLSearchParams,
|
|
26
|
+
keys: string[],
|
|
27
|
+
copy: boolean,
|
|
28
|
+
): URLSearchParams {
|
|
29
|
+
if (keys.length === 0) {
|
|
30
|
+
return search;
|
|
31
|
+
}
|
|
32
|
+
const filtered = copy ? new URLSearchParams(search) : search;
|
|
33
|
+
for (const key of Array.from(search.keys())) {
|
|
34
|
+
if (!keys.includes(key)) {
|
|
35
|
+
filtered.delete(key);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return filtered;
|
|
39
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { debug } from '../../lib/debug';
|
|
2
|
+
import { createEmitter, type Emitter } from '../../lib/emitter';
|
|
3
|
+
import { error } from '../../lib/errors';
|
|
4
|
+
import { globalSingleton } from '../../lib/global-singleton';
|
|
5
|
+
import { resetQueues, spinQueueResetMutex } from '../../lib/queues/reset';
|
|
6
|
+
import { getSearchParams } from '../../lib/search-params';
|
|
7
|
+
import { version } from '../../lib/version';
|
|
8
|
+
|
|
9
|
+
export type SearchParamsSyncEmitterEvents = { update: URLSearchParams };
|
|
10
|
+
|
|
11
|
+
export function getHistorySyncEmitter(adapter: string): Emitter<SearchParamsSyncEmitterEvents> {
|
|
12
|
+
return globalSingleton(`history-emitter.${adapter}`, () =>
|
|
13
|
+
createEmitter<SearchParamsSyncEmitterEvents>(),
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export const historyUpdateMarker = '__nuqs__';
|
|
18
|
+
|
|
19
|
+
declare global {
|
|
20
|
+
interface History {
|
|
21
|
+
nuqs?: {
|
|
22
|
+
version: string;
|
|
23
|
+
adapters: string[];
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function shouldPatchHistory(adapter: string): boolean {
|
|
29
|
+
if (typeof history === 'undefined') {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
if (history.nuqs?.version && history.nuqs.version !== version) {
|
|
33
|
+
console.error(error(409), history.nuqs.version, version, adapter);
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
if (history.nuqs?.adapters?.includes(adapter)) {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function markHistoryAsPatched(adapter: string): void {
|
|
43
|
+
history.nuqs = history.nuqs ?? {
|
|
44
|
+
version,
|
|
45
|
+
adapters: [],
|
|
46
|
+
};
|
|
47
|
+
history.nuqs.adapters.push(adapter);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function patchHistory(
|
|
51
|
+
emitter: Emitter<SearchParamsSyncEmitterEvents>,
|
|
52
|
+
adapter: string,
|
|
53
|
+
): void {
|
|
54
|
+
if (!shouldPatchHistory(adapter)) {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
let lastSearchSeen = typeof location === 'object' ? location.search : '';
|
|
58
|
+
|
|
59
|
+
emitter.on('update', (search) => {
|
|
60
|
+
const searchString = search.toString();
|
|
61
|
+
lastSearchSeen = searchString.length ? '?' + searchString : '';
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
window.addEventListener('popstate', () => {
|
|
65
|
+
lastSearchSeen = location.search;
|
|
66
|
+
resetQueues();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
debug(21, version, adapter);
|
|
70
|
+
function sync(url: URL | string) {
|
|
71
|
+
spinQueueResetMutex();
|
|
72
|
+
try {
|
|
73
|
+
const newSearch = new URL(url, location.origin).search;
|
|
74
|
+
if (newSearch === lastSearchSeen) {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
} catch {}
|
|
78
|
+
try {
|
|
79
|
+
emitter.emit('update', getSearchParams(url));
|
|
80
|
+
} catch (e) {
|
|
81
|
+
console.error(e);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const originalPushState = history.pushState;
|
|
85
|
+
const originalReplaceState = history.replaceState;
|
|
86
|
+
history.pushState = function nuqs_pushState(state, marker, url) {
|
|
87
|
+
originalPushState.call(history, state, '', url);
|
|
88
|
+
if (url && marker !== historyUpdateMarker) {
|
|
89
|
+
sync(url);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
history.replaceState = function nuqs_replaceState(state, marker, url) {
|
|
93
|
+
originalReplaceState.call(history, state, '', url);
|
|
94
|
+
if (url && marker !== historyUpdateMarker) {
|
|
95
|
+
sync(url);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
markHistoryAsPatched(adapter);
|
|
99
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createContext,
|
|
3
|
+
createElement,
|
|
4
|
+
useContext,
|
|
5
|
+
useMemo,
|
|
6
|
+
useRef,
|
|
7
|
+
useSyncExternalStore,
|
|
8
|
+
type OctaneNode,
|
|
9
|
+
} from 'octane';
|
|
10
|
+
import { debug } from '../lib/debug';
|
|
11
|
+
import { renderQueryString } from '../lib/url-encoding';
|
|
12
|
+
import { createAdapterProvider, type AdapterProps } from './lib/context';
|
|
13
|
+
import type { AdapterInterface, AdapterOptions } from './lib/defs';
|
|
14
|
+
import { filterSearchParams } from './lib/key-isolation';
|
|
15
|
+
import { getHistorySyncEmitter, historyUpdateMarker, patchHistory } from './lib/patch-history';
|
|
16
|
+
|
|
17
|
+
const emitter = getHistorySyncEmitter('react');
|
|
18
|
+
|
|
19
|
+
function generateUpdateUrlFn(fullPageNavigationOnShallowFalseUpdates: boolean) {
|
|
20
|
+
return function updateUrl(search: URLSearchParams, options: AdapterOptions) {
|
|
21
|
+
const url = new URL(location.href);
|
|
22
|
+
url.search = renderQueryString(search);
|
|
23
|
+
debug(20, 'react', url);
|
|
24
|
+
if (fullPageNavigationOnShallowFalseUpdates && options.shallow === false) {
|
|
25
|
+
const method = options.history === 'push' ? location.assign : location.replace;
|
|
26
|
+
method.call(location, url);
|
|
27
|
+
} else {
|
|
28
|
+
const method = options.history === 'push' ? history.pushState : history.replaceState;
|
|
29
|
+
method.call(history, history.state, historyUpdateMarker, url);
|
|
30
|
+
}
|
|
31
|
+
emitter.emit('update', search);
|
|
32
|
+
if (options.scroll === true) {
|
|
33
|
+
window.scrollTo({ top: 0 });
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const NuqsReactAdapterContext = createContext({
|
|
39
|
+
fullPageNavigationOnShallowFalseUpdates: false,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const emptySearchParams = new URLSearchParams();
|
|
43
|
+
|
|
44
|
+
// Note: we could expose a getServerSnapshot() function to allow server-side rendering
|
|
45
|
+
// to let consumers wire that to their backend router (eg: in Astro SSR, Fastify, Hono etc).
|
|
46
|
+
function getServerSnapshot() {
|
|
47
|
+
return emptySearchParams;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function subscribe(onStoreChange: () => void) {
|
|
51
|
+
emitter.on('update', onStoreChange);
|
|
52
|
+
window.addEventListener('popstate', onStoreChange);
|
|
53
|
+
return () => {
|
|
54
|
+
emitter.off('update', onStoreChange);
|
|
55
|
+
window.removeEventListener('popstate', onStoreChange);
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function useNuqsReactAdapter(watchKeys: string[]): AdapterInterface {
|
|
60
|
+
const { fullPageNavigationOnShallowFalseUpdates } = useContext(NuqsReactAdapterContext);
|
|
61
|
+
// Reading location.search live in getSnapshot (rather than from React state
|
|
62
|
+
// synced by an effect) keeps the value fresh even on the first render after an
|
|
63
|
+
// <Activity> subtree is revealed: its effects — and thus the emitter
|
|
64
|
+
// subscription — were detached while hidden and missed the URL update (#1444).
|
|
65
|
+
const cache = useRef<{ key: string; search: URLSearchParams } | null>(null);
|
|
66
|
+
const searchParams = useSyncExternalStore(
|
|
67
|
+
subscribe,
|
|
68
|
+
() => {
|
|
69
|
+
const filteredSearch = filterSearchParams(
|
|
70
|
+
new URLSearchParams(location.search),
|
|
71
|
+
watchKeys,
|
|
72
|
+
false,
|
|
73
|
+
);
|
|
74
|
+
// Return a referentially-stable snapshot while the watched keys are unchanged:
|
|
75
|
+
// required by useSyncExternalStore (Object.is bail-out),
|
|
76
|
+
// and it preserves key isolation (a change to an unwatched key keeps the same ref,
|
|
77
|
+
// so this hook doesn't re-render).
|
|
78
|
+
const key = filteredSearch.toString();
|
|
79
|
+
if (cache.current?.key === key) {
|
|
80
|
+
return cache.current.search;
|
|
81
|
+
}
|
|
82
|
+
cache.current = { key, search: filteredSearch };
|
|
83
|
+
return filteredSearch;
|
|
84
|
+
},
|
|
85
|
+
getServerSnapshot,
|
|
86
|
+
);
|
|
87
|
+
const updateUrl = useMemo(
|
|
88
|
+
() => generateUpdateUrlFn(fullPageNavigationOnShallowFalseUpdates),
|
|
89
|
+
[fullPageNavigationOnShallowFalseUpdates],
|
|
90
|
+
);
|
|
91
|
+
return {
|
|
92
|
+
searchParams,
|
|
93
|
+
updateUrl,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const NuqsReactAdapter = createAdapterProvider(useNuqsReactAdapter);
|
|
98
|
+
|
|
99
|
+
export function NuqsAdapter({
|
|
100
|
+
children,
|
|
101
|
+
fullPageNavigationOnShallowFalseUpdates = false,
|
|
102
|
+
...adapterProps
|
|
103
|
+
}: AdapterProps & {
|
|
104
|
+
children: OctaneNode;
|
|
105
|
+
fullPageNavigationOnShallowFalseUpdates?: boolean;
|
|
106
|
+
}): OctaneNode {
|
|
107
|
+
return createElement(
|
|
108
|
+
NuqsReactAdapterContext.Provider,
|
|
109
|
+
{ value: { fullPageNavigationOnShallowFalseUpdates } },
|
|
110
|
+
createElement(NuqsReactAdapter, { ...adapterProps, children }),
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Opt-in to syncing shallow updates of the URL with the useOptimisticSearchParams hook.
|
|
116
|
+
*
|
|
117
|
+
* By default, the useOptimisticSearchParams hook will only react to internal nuqs updates.
|
|
118
|
+
* If third party code updates the History API directly, use this function to
|
|
119
|
+
* enable useOptimisticSearchParams to react to those changes.
|
|
120
|
+
*/
|
|
121
|
+
export function enableHistorySync(): void {
|
|
122
|
+
patchHistory(emitter, 'react');
|
|
123
|
+
}
|