@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,65 @@
1
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import { createLoader, type CreateLoaderOptions } from './loader';
3
+ import type { ParserMap, inferParserType } from './parsers';
4
+ import { createSerializer } from './serializer';
5
+
6
+ export type CreateStandardSchemaV1Options<
7
+ Parsers extends ParserMap,
8
+ PartialOutput extends boolean = false,
9
+ > = CreateLoaderOptions<Parsers> & {
10
+ /**
11
+ * Marks the output type as Partial, and removes any keys
12
+ * from the output that are not present in the input.
13
+ *
14
+ * This is useful for TanStack Router, to avoid reflecting default values
15
+ * (or null) in the URL, and to make search params optional in Links,
16
+ * as default values are handled by nuqs.
17
+ *
18
+ * @default false
19
+ */
20
+ partialOutput?: PartialOutput;
21
+ };
22
+
23
+ type MaybePartial<Condition, Type> = Condition extends true ? Partial<Type> : Type;
24
+
25
+ export function createStandardSchemaV1<
26
+ Parsers extends ParserMap,
27
+ PartialOutput extends boolean = false,
28
+ >(
29
+ parsers: Parsers,
30
+ {
31
+ urlKeys,
32
+ partialOutput = false as PartialOutput,
33
+ }: CreateStandardSchemaV1Options<Parsers, PartialOutput> = {},
34
+ ): StandardSchemaV1<MaybePartial<PartialOutput, inferParserType<Parsers>>> {
35
+ const serialize = createSerializer(parsers, { urlKeys });
36
+ const load = createLoader(parsers, { urlKeys });
37
+ return {
38
+ '~standard': {
39
+ version: 1,
40
+ vendor: 'nuqs',
41
+ validate(input) {
42
+ try {
43
+ const url = serialize(input as any);
44
+ const value = load(url, { strict: true });
45
+ if (partialOutput) {
46
+ for (const key in value) {
47
+ if (!(key in (input as any))) {
48
+ delete value[key];
49
+ }
50
+ }
51
+ }
52
+ return { value };
53
+ } catch (error) {
54
+ return {
55
+ issues: [
56
+ {
57
+ message: error instanceof Error ? error.message : String(error),
58
+ },
59
+ ],
60
+ };
61
+ }
62
+ },
63
+ },
64
+ };
65
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,167 @@
1
+ import { compareQuery } from './lib/compare';
2
+ import type { GenericParserBuilder, MultiParserBuilder, SingleParserBuilder } from './parsers';
3
+
4
+ export function isParserBijective<T>(
5
+ parser: SingleParserBuilder<T>,
6
+ serialized: string,
7
+ input: T,
8
+ ): boolean;
9
+ export function isParserBijective<T>(
10
+ parser: MultiParserBuilder<T>,
11
+ serialized: Array<string>,
12
+ input: T,
13
+ ): boolean;
14
+
15
+ /**
16
+ * Test that a parser is bijective (serialize then parse gives back the same value).
17
+ *
18
+ * It will throw if the parser does not serialize the input to the expected serialized value,
19
+ * or if the parser does not parse the serialized value to the expected input value.
20
+ * The parser's `eq` function (if provided, otherwise `===`) is used to compare the values.
21
+ *
22
+ * Usage:
23
+ * ```ts
24
+ * // Expect it to pass (no error thrown)
25
+ * expect(isParserBijective(parseAsInteger, '42', 42)).toBe(true)
26
+ * // Expect it to fail
27
+ * expect(() => isParserBijective(parseAsInteger, '42', 47)).toThrow()
28
+ * ```
29
+ *
30
+ * @param parser The parser to test
31
+ * @param serialized The serialized representation of the input to test against
32
+ * @param input An input value to test against
33
+ * @returns `true` if the test passes, otherwise it will throw.
34
+ */
35
+ export function isParserBijective<T>(
36
+ parser: GenericParserBuilder<T>,
37
+ serialized: string | Array<string>,
38
+ input: T,
39
+ ): boolean {
40
+ if (parser.type === 'multi' && Array.isArray(serialized)) {
41
+ // Test either sides of the bijectivitiy
42
+ testSerializeThenParse(parser, input);
43
+ testParseThenSerialize(parser, serialized);
44
+ } else if (parser.type !== 'multi' && typeof serialized === 'string') {
45
+ // Test either sides of the bijectivitiy
46
+ testSerializeThenParse(parser, input);
47
+ testParseThenSerialize(parser, serialized);
48
+ } else {
49
+ // Shouldn't happen with correct overload types, but better be safe and fail the test.
50
+ throw new Error(`[nuqs] isParserBijective: mismatched parser type and serialized value type`);
51
+ }
52
+ // Test value equality
53
+ if (!compareQuery(parser.serialize(input), serialized)) {
54
+ throw new Error(
55
+ `[nuqs] parser.serialize does not match expected serialized value
56
+ Expected: '${serialized}'
57
+ Received: '${parser.serialize(input)}'
58
+ `,
59
+ );
60
+ }
61
+ // @ts-expect-error - might return null
62
+ const parsed: T = parser.parse(serialized);
63
+ if (!parser.eq(parsed, input)) {
64
+ throw new Error(
65
+ `[nuqs] parser.parse does not match expected input value
66
+ Expected: ${input}
67
+ Received: ${parsed}
68
+ `,
69
+ );
70
+ }
71
+ return true;
72
+ }
73
+
74
+ export function testSerializeThenParse<T>(parser: SingleParserBuilder<T>, input: T): boolean;
75
+ export function testSerializeThenParse<T>(parser: MultiParserBuilder<T>, input: T): boolean;
76
+
77
+ /**
78
+ * Test that a parser is bijective (serialize then parse gives back the same value).
79
+ *
80
+ * It will throw if the parser is not bijective (if the parsed value is not equal to the input value).
81
+ * The parser's `eq` function is used to compare the values.
82
+ *
83
+ * Usage:
84
+ * ```ts
85
+ * // Expect it to pass (no error thrown)
86
+ * expect(testSerializeThenParse(myParser, 'foo')).toBe(true)
87
+ * // Expect it to fail
88
+ * expect(() => testSerializeThenParse(myParser, 'bar')).toThrow()
89
+ * ```
90
+ *
91
+ * @param parser The parser to test
92
+ * @param input An input value to test against
93
+ * @returns `true` if the test passes, otherwise it will throw.
94
+ */
95
+ export function testSerializeThenParse<T>(parser: GenericParserBuilder<T>, input: T): boolean {
96
+ const serialized = parser.serialize(input);
97
+ const parsed =
98
+ parser.type == 'multi' && Array.isArray(serialized)
99
+ ? parser.parse(serialized)
100
+ : parser.type !== 'multi' && typeof serialized === 'string'
101
+ ? parser.parse(serialized)
102
+ : null;
103
+ if (parsed === null) {
104
+ throw new Error(
105
+ `[nuqs] testSerializeThenParse: parsed value is null (when parsing ${serialized} serialized from ${input})`,
106
+ );
107
+ }
108
+ if (!parser.eq(input, parsed)) {
109
+ throw new Error(
110
+ `[nuqs] parser is not bijective (in testSerializeThenParse)
111
+ Expected value: ${typeof input === 'object' ? JSON.stringify(input) : input}
112
+ Received parsed value: ${typeof parsed === 'object' ? JSON.stringify(parsed) : parsed}
113
+ Serialized as: '${serialized}'
114
+ `,
115
+ );
116
+ }
117
+ return true;
118
+ }
119
+
120
+ export function testParseThenSerialize<T>(parser: SingleParserBuilder<T>, input: string): boolean;
121
+ export function testParseThenSerialize<T>(
122
+ parser: MultiParserBuilder<T>,
123
+ input: Array<string>,
124
+ ): boolean;
125
+
126
+ /**
127
+ * Tests that a parser is bijective (parse then serialize gives back the same query string).
128
+ *
129
+ * It will throw if the parser is not bijective (if the serialized value is not equal to the input query).
130
+ *
131
+ * Usage:
132
+ * ```ts
133
+ * // Expect it to pass (no error thrown)
134
+ * expect(testParseThenSerialize(myParser, 'foo')).toBe(true)
135
+ * // Expect it to fail
136
+ * expect(() => testParseThenSerialize(myParser, 'bar')).toThrow()
137
+ * ```
138
+ *
139
+ * @param parser The parser to test
140
+ * @param input A query string to test against
141
+ * @returns `true` if the test passes, otherwise it will throw.
142
+ */
143
+ export function testParseThenSerialize<T>(
144
+ parser: GenericParserBuilder<T>,
145
+ input: string | Array<string>,
146
+ ): boolean {
147
+ const parsed =
148
+ parser.type === 'multi' && Array.isArray(input)
149
+ ? parser.parse(input)
150
+ : parser.type !== 'multi' && typeof input === 'string'
151
+ ? parser.parse(input)
152
+ : null;
153
+ if (parsed === null) {
154
+ throw new Error(`[nuqs] testParseThenSerialize: parsed value is null (when parsing ${input})`);
155
+ }
156
+ const serialized = parser.serialize(parsed);
157
+ if (!compareQuery(serialized, input)) {
158
+ throw new Error(
159
+ `[nuqs] parser is not bijective (in testParseThenSerialize)
160
+ Expected query: '${input}'
161
+ Received query: '${serialized}'
162
+ Parsed value: ${parsed}
163
+ `,
164
+ );
165
+ }
166
+ return true;
167
+ }
@@ -0,0 +1,225 @@
1
+ import { useCallback } from 'octane';
2
+ import type { Options } from './defs';
3
+
4
+ // Ported from react's `SetStateAction<T>`: a new value or an updater function.
5
+ type SetStateAction<T> = T | ((prev: T) => T);
6
+ import type { GenericParser } from './parsers';
7
+ import { useQueryStates } from './useQueryStates';
8
+
9
+ export type UseQueryStateOptions<T> = GenericParser<T> & Options;
10
+
11
+ export type UseQueryStateReturn<Parsed, Default> = [
12
+ Default extends undefined
13
+ ? Parsed | null // value can't be null if default is specified
14
+ : Parsed,
15
+ (
16
+ value:
17
+ | null
18
+ | Parsed
19
+ | ((old: Default extends Parsed ? Parsed : Parsed | null) => Parsed | null),
20
+ options?: Options,
21
+ ) => Promise<URLSearchParams>,
22
+ ];
23
+
24
+ // Overload type signatures ----------------------------------------------------
25
+ // Note: the order of declaration matters (from the most specific to the least).
26
+
27
+ /**
28
+ * React state hook synchronized with a URL query string in Next.js
29
+ *
30
+ * This variant is used when providing a default value. This will make
31
+ * the returned state non-nullable when the query is not present in the URL.
32
+ * (the default value will be returned instead).
33
+ *
34
+ * _Note: the URL will **not** be updated with the default value if the query
35
+ * is missing._
36
+ *
37
+ * Setting the value to `null` will clear the query in the URL, and return
38
+ * the default value as state.
39
+ *
40
+ * Example usage:
41
+ * ```ts
42
+ * const [count, setCount] = useQueryState(
43
+ * 'count',
44
+ * parseAsInteger.defaultValue(0)
45
+ * )
46
+ *
47
+ * const increment = () => setCount(oldCount => oldCount + 1)
48
+ * const decrement = () => setCount(oldCount => oldCount - 1)
49
+ * // Clears the query key from the URL and `count` equals 0
50
+ * const clearCountQuery = () => setCount(null)
51
+ * ```
52
+ * @param key The URL query string key to bind to
53
+ * @param options - Parser (defines the state data type), default value and optional history mode.
54
+ */
55
+ export function useQueryState<T>(
56
+ key: string,
57
+ options: UseQueryStateOptions<T> & { defaultValue: T },
58
+ ): UseQueryStateReturn<NonNullable<ReturnType<typeof options.parse>>, typeof options.defaultValue>;
59
+
60
+ /**
61
+ * React state hook synchronized with a URL query string in Next.js
62
+ *
63
+ * If the query is missing in the URL, the state will be `null`.
64
+ *
65
+ * Example usage:
66
+ * ```ts
67
+ * // Blog posts filtering by tag
68
+ * const [tag, selectTag] = useQueryState('tag')
69
+ * const filteredPosts = posts.filter(post => tag ? post.tag === tag : true)
70
+ * const clearTag = () => selectTag(null)
71
+ * ```
72
+ * @param key The URL query string key to bind to
73
+ * @param options - Parser (defines the state data type), and optional history mode.
74
+ */
75
+ export function useQueryState<T>(
76
+ key: string,
77
+ options: UseQueryStateOptions<T>,
78
+ ): UseQueryStateReturn<NonNullable<ReturnType<typeof options.parse>>, undefined>;
79
+
80
+ /**
81
+ * Default type string, limited options & default value
82
+ */
83
+ export function useQueryState(
84
+ key: string,
85
+ options: Options & {
86
+ defaultValue: string;
87
+ } & {
88
+ // Note: Ensure this overload isn't picked when specifying a default
89
+ // value and spreading a parser for which the default would be invalid.
90
+ // See https://github.com/47ng/nuqs/pull/1057
91
+ [K in keyof GenericParser<unknown>]?: never;
92
+ },
93
+ ): UseQueryStateReturn<string, typeof options.defaultValue>;
94
+
95
+ /**
96
+ * React state hook synchronized with a URL query string in Next.js
97
+ *
98
+ * If the query is missing in the URL, the state will be `null`.
99
+ *
100
+ * Note: by default the state type is a `string`. To use different types,
101
+ * check out the `parseAsXYZ` helpers:
102
+ * ```ts
103
+ * const [date, setDate] = useQueryState(
104
+ * 'date',
105
+ * parseAsIsoDateTime.withDefault(new Date('2021-01-01'))
106
+ * )
107
+ *
108
+ * const setToNow = () => setDate(new Date())
109
+ * const addOneHour = () => {
110
+ * setDate(oldDate => new Date(oldDate.valueOf() + 3600_000))
111
+ * }
112
+ * ```
113
+ * @param key The URL query string key to bind to
114
+ * @param options - Parser (defines the state data type), and optional history mode.
115
+ */
116
+ export function useQueryState(
117
+ key: string,
118
+ options: Pick<UseQueryStateOptions<string>, keyof Options>,
119
+ ): UseQueryStateReturn<string, undefined>;
120
+
121
+ /**
122
+ * React state hook synchronized with a URL query string in Next.js
123
+ *
124
+ * If the query is missing in the URL, the state will be `null`.
125
+ *
126
+ * Note: by default the state type is a `string`. To use different types,
127
+ * check out the `parseAsXYZ` helpers:
128
+ * ```ts
129
+ * const [date, setDate] = useQueryState(
130
+ * 'date',
131
+ * parseAsIsoDateTime.withDefault(new Date('2021-01-01'))
132
+ * )
133
+ *
134
+ * const setToNow = () => setDate(new Date())
135
+ * const addOneHour = () => {
136
+ * setDate(oldDate => new Date(oldDate.valueOf() + 3600_000))
137
+ * }
138
+ * ```
139
+ * @param key The URL query string key to bind to
140
+ */
141
+ export function useQueryState(key: string): UseQueryStateReturn<string, undefined>;
142
+
143
+ /**
144
+ * React state hook synchronized with a URL query string in Next.js
145
+ *
146
+ * If used without a `defaultValue` supplied in the options, and the query is
147
+ * missing in the URL, the state will be `null`.
148
+ *
149
+ * ### Behaviour with default values:
150
+ *
151
+ * _Note: the URL will **not** be updated with the default value if the query
152
+ * is missing._
153
+ *
154
+ * Setting the value to `null` will clear the query in the URL, and return
155
+ * the default value as state.
156
+ *
157
+ * Example usage:
158
+ * ```ts
159
+ * // Blog posts filtering by tag
160
+ * const [tag, selectTag] = useQueryState('tag')
161
+ * const filteredPosts = posts.filter(post => tag ? post.tag === tag : true)
162
+ * const clearTag = () => selectTag(null)
163
+ *
164
+ * // With default values
165
+ *
166
+ * const [count, setCount] = useQueryState(
167
+ * 'count',
168
+ * parseAsInteger.defaultValue(0)
169
+ * )
170
+ *
171
+ * const increment = () => setCount(oldCount => oldCount + 1)
172
+ * const decrement = () => setCount(oldCount => oldCount - 1)
173
+ * const clearCountQuery = () => setCount(null)
174
+ *
175
+ * // --
176
+ *
177
+ * const [date, setDate] = useQueryState(
178
+ * 'date',
179
+ * parseAsIsoDateTime.withDefault(new Date('2021-01-01'))
180
+ * )
181
+ *
182
+ * const setToNow = () => setDate(new Date())
183
+ * const addOneHour = () => {
184
+ * setDate(oldDate => new Date(oldDate.valueOf() + 3600_000))
185
+ * }
186
+ * ```
187
+ * @param key The URL query string key to bind to
188
+ * @param options - Parser (defines the state data type), optional default value and history mode.
189
+ */
190
+ export function useQueryState<T = string>(
191
+ key: string,
192
+ options: Partial<UseQueryStateOptions<T>> & {
193
+ defaultValue?: T;
194
+ } = {},
195
+ ) {
196
+ const { parse, type, serialize, eq, defaultValue, ...hookOptions } = options;
197
+ const [{ [key]: state }, setState] = useQueryStates(
198
+ {
199
+ [key]: {
200
+ parse: parse ?? ((x: any) => x as unknown as T),
201
+ type,
202
+ serialize,
203
+ eq,
204
+ defaultValue,
205
+ } as GenericParser<T>,
206
+ },
207
+ hookOptions,
208
+ );
209
+ const update = useCallback(
210
+ (stateUpdater: SetStateAction<T | null>, callOptions: Options = {}) =>
211
+ setState(
212
+ (old) => ({
213
+ [key]:
214
+ typeof stateUpdater === 'function'
215
+ ? // @ts-expect-error somehow stateUpdater is not narrowed correctly
216
+ // and useQueryStates' key type is not inferred
217
+ stateUpdater(old[key])
218
+ : stateUpdater,
219
+ }),
220
+ callOptions,
221
+ ),
222
+ [key, setState],
223
+ );
224
+ return [state, update];
225
+ }