Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

searchMiddleware.ts

80 lines2.5 KB

1import { deepEqual } from './utils'
2import type { NoInfer, PickOptional } from './utils'
3import type { SearchMiddleware } from './route'
4import type { IsRequiredParams } from './link'
5​
6/**
7 * Retain specified search params across navigations.
8 *
9 * If `keys` is `true`, retain all current params. Otherwise, copy only the
10 * listed keys from the current search into the next search.
11 *
12 * @param keys `true` to retain all, or a list of keys to retain.
13 * @returns A search middleware suitable for route `search.middlewares`.
14 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/retainSearchParamsFunction
15 */
16/**
17 * Retain specified search params across navigations by merging prior values.
18 */
19export function retainSearchParams<TSearchSchema extends object>(
20 keys: Array<keyof TSearchSchema> | true,
21): SearchMiddleware<TSearchSchema> {
22 return ({ search, next }) => {
23 const result = next(search)
24 if (keys === true) {
25 return { ...search, ...result }
26 }
27 // add missing keys from search to result
28 keys.forEach((key) => {
29 if (!(key in result)) {
30 result[key] = search[key]
31 }
32 })
33 return result
34 }
36​
37/**
38 * Remove optional or default-valued search params from navigations.
39 *
40 * - Pass `true` (only if there are no required search params) to strip all.
41 * - Pass an array to always remove those optional keys.
42 * - Pass an object of default values; keys equal (deeply) to the defaults are removed.
43 *
44 * @returns A search middleware suitable for route `search.middlewares`.
45 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/stripSearchParamsFunction
46 */
47/**
48 * Remove optional/default-valued search params from navigations.
49 */
50export function stripSearchParams<
51 TSearchSchema,
52 TOptionalProps = PickOptional<NoInfer<TSearchSchema>>,
53 const TValues =
54 | Partial<NoInfer<TOptionalProps>>
55 | Array<keyof TOptionalProps>,
56 const TInput = IsRequiredParams<TSearchSchema> extends never
57 ? TValues | true
58 : TValues,
59>(input: NoInfer<TInput>): SearchMiddleware<TSearchSchema> {
60 return ({ search, next }) => {
61 if (input === true) {
62 return {}
63 }
64 const result = next(search) as Record<string, unknown>
65 if (Array.isArray(input)) {
66 input.forEach((key) => {
67 delete result[key]
68 })
69 } else {
70 Object.entries(input as Record<string, unknown>).forEach(
71 ([key, value]) => {
72 if (deepEqual(result[key], value)) {
73 delete result[key]
74 }
75 },
76 )
77 }
78 return result as any
79 }