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

searchMiddleware.ts

141 lines4.6 KB

1import { deepEqual, hasOwn } from './utils'
2import type { NoInfer, PickOptional } from './utils'
3import type {
4 SearchMiddleware,
5 SearchMiddlewareContext,
6 SearchMiddlewareMeta,
7} from './route'
8import type { IsRequiredParams } from './link'
9​
10type SearchMiddlewareNextWithMeta<TSearchSchema> = (
11 newSearch: TSearchSchema,
12 collectMeta: true,
13) => { search: TSearchSchema; meta: SearchMiddlewareMeta }
14​
15/**
16 * Retain specified search params across navigations.
17 *
18 * If `keys` is `true`, retain all current params. Otherwise, copy only the
19 * listed keys from the current search into the next search.
20 *
21 * @param keys `true` to retain all, or a list of keys to retain.
22 * @returns A search middleware suitable for route `search.middlewares`.
23 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/retainSearchParamsFunction
24 */
25export function retainSearchParams<TSearchSchema extends object>(
26 keys: Array<keyof TSearchSchema> | true,
27): SearchMiddleware<TSearchSchema> {
28 return ({ search, next }) => {
29 const { search: resultSearch, meta } = (
30 next as unknown as SearchMiddlewareNextWithMeta<TSearchSchema>
31 )(search, true)
32​
33 if (keys === true) {
34 const copy = { ...search, ...resultSearch }
35 const removed = meta.removed
36 const explicit = meta.explicit
37 for (const key of removed?.keys() || []) {
38 if (
39 (explicit && hasOwn.call(explicit, key)) ||
40 deepEqual(search[key as keyof TSearchSchema], removed!.get(key))
41 ) {
42 delete copy[key as keyof TSearchSchema]
43 }
44 }
45 for (const key of meta.removedAny || []) {
46 delete copy[key as keyof TSearchSchema]
47 }
48 for (const key of meta.defaulted?.keys() || []) {
49 if (
50 key in search &&
51 !meta.removedAny?.has(key) &&
52 !(
53 meta.removed?.has(key) &&
54 ((explicit && hasOwn.call(explicit, key)) ||
55 deepEqual(
56 search[key as keyof TSearchSchema],
57 meta.removed.get(key),
58 ))
59 )
60 ) {
61 copy[key as keyof TSearchSchema] = search[key as keyof TSearchSchema]
62 }
63 }
64 return copy
65 }
66​
67 const copy = { ...resultSearch }
68 const explicit = meta.explicit
69 // add missing keys from search to copy
70 for (const key of keys) {
71 const stringKey = key as string
72 const removed =
73 meta.removedAny?.has(stringKey) ||
74 (meta.removed?.has(stringKey) &&
75 ((explicit && hasOwn.call(explicit, stringKey)) ||
76 deepEqual(search[key], meta.removed.get(stringKey))))
77 if (
78 !removed &&
79 (!(key in copy) ||
80 (key in search &&
81 meta.defaulted?.has(stringKey) &&
82 deepEqual(copy[key], meta.defaulted.get(stringKey))))
83 ) {
84 copy[key] = search[key]
85 }
86 }
87 return copy
88 }
90​
91/**
92 * Remove optional or default-valued search params from navigations.
93 *
94 * - Pass `true` (only if there are no required search params) to strip all.
95 * - Pass an array to always remove those optional keys.
96 * - Pass an object of default values; keys equal (deeply) to the defaults are removed.
97 *
98 * @returns A search middleware suitable for route `search.middlewares`.
99 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/stripSearchParamsFunction
100 */
101export function stripSearchParams<
102 TSearchSchema,
103 TOptionalProps = PickOptional<NoInfer<TSearchSchema>>,
104 const TValues = Partial<NoInfer<TSearchSchema>> | Array<keyof TOptionalProps>,
105 const TInput = IsRequiredParams<TSearchSchema> extends never
106 ? TValues | true
107 : TValues,
108>(input: NoInfer<TInput>): SearchMiddleware<TSearchSchema> {
109 return (({ search, next, meta }: SearchMiddlewareContext<TSearchSchema>) => {
110 if (input === true) {
111 Object.keys(search as object).forEach((key) => {
112 if (meta) {
113 ;(meta.removedAny ||= new Set()).add(key)
114 }
115 })
116 return {}
117 }
118 const nextResult = next(search)
119 const result = { ...nextResult } as Record<string, unknown>
120 if (Array.isArray(input)) {
121 input.forEach((key) => {
122 delete result[key as string]
123 if (meta) {
124 ;(meta.removedAny ||= new Set()).add(key as string)
125 }
126 })
127 } else {
128 Object.entries(input as Record<string, unknown>).forEach(
129 ([key, value]) => {
130 if (deepEqual(result[key], value)) {
131 delete result[key]
132 if (meta) {
133 ;(meta.removed ||= new Map()).set(key, value)
134 }
135 }
136 },
137 )
138 }
139 return result as any
140 }) as SearchMiddleware<TSearchSchema>