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

useBlocker.tsx

324 lines7.9 KB

1'use client'
2​
3import * as React from 'react'
4import { useRouter } from './useRouter'
5import type {
6 BlockerFnArgs,
7 HistoryAction,
8 HistoryLocation,
9} from '@tanstack/history'
10import type {
11 AnyRoute,
12 AnyRouter,
13 ParseRoute,
14 RegisteredRouter,
15} from '@tanstack/router-core'
16​
17type ShouldBlockFnLocation<
18 out TRouteId,
19 out TFullPath,
20 out TAllParams,
21 out TFullSearchSchema,
22> = {
23 routeId: TRouteId
24 fullPath: TFullPath
25 pathname: string
26 params: TAllParams
27 search: TFullSearchSchema
29​
30type AnyShouldBlockFnLocation = ShouldBlockFnLocation<any, any, any, any>
31type MakeShouldBlockFnLocationUnion<
32 TRouter extends AnyRouter = RegisteredRouter,
33 TRoute extends AnyRoute = ParseRoute<TRouter['routeTree']>,
34> = TRoute extends any
35 ? ShouldBlockFnLocation<
36 TRoute['id'],
37 TRoute['fullPath'],
38 TRoute['types']['allParams'],
39 TRoute['types']['fullSearchSchema']
40 >
41 : never
42​
43type BlockerResolver<TRouter extends AnyRouter = RegisteredRouter> =
44 | {
45 status: 'blocked'
46 current: MakeShouldBlockFnLocationUnion<TRouter>
47 next: MakeShouldBlockFnLocationUnion<TRouter>
48 action: HistoryAction
49 proceed: () => void
50 reset: () => void
51 }
52 | {
53 status: 'idle'
54 current: undefined
55 next: undefined
56 action: undefined
57 proceed: undefined
58 reset: undefined
59 }
60​
61type ShouldBlockFnArgs<TRouter extends AnyRouter = RegisteredRouter> = {
62 current: MakeShouldBlockFnLocationUnion<TRouter>
63 next: MakeShouldBlockFnLocationUnion<TRouter>
64 action: HistoryAction
66​
67export type ShouldBlockFn<TRouter extends AnyRouter = RegisteredRouter> = (
68 args: ShouldBlockFnArgs<TRouter>,
69) => boolean | Promise<boolean>
70export type UseBlockerOpts<
71 TRouter extends AnyRouter = RegisteredRouter,
72 TWithResolver extends boolean = boolean,
73> = {
74 shouldBlockFn: ShouldBlockFn<TRouter>
75 enableBeforeUnload?: boolean | (() => boolean)
76 disabled?: boolean
77 withResolver?: TWithResolver
79​
80type LegacyBlockerFn = () => Promise<any> | any
81type LegacyBlockerOpts = {
82 blockerFn?: LegacyBlockerFn
83 condition?: boolean | any
85​
86function _resolveBlockerOpts(
87 opts?: UseBlockerOpts | LegacyBlockerOpts | LegacyBlockerFn,
88 condition?: boolean | any,
89): UseBlockerOpts {
90 if (opts === undefined) {
91 return {
92 shouldBlockFn: () => true,
93 withResolver: false,
94 }
95 }
96​
97 if ('shouldBlockFn' in opts) {
98 return opts
99 }
100​
101 if (typeof opts === 'function') {
102 const shouldBlock = Boolean(condition ?? true)
103​
104 const _customBlockerFn = async () => {
105 if (shouldBlock) return await opts()
106 return false
107 }
108​
109 return {
110 shouldBlockFn: _customBlockerFn,
111 enableBeforeUnload: shouldBlock,
112 withResolver: false,
113 }
114 }
115​
116 const shouldBlock = Boolean(opts.condition ?? true)
117 const fn = opts.blockerFn
118​
119 const _customBlockerFn = async () => {
120 if (shouldBlock && fn !== undefined) {
121 return await fn()
122 }
123 return shouldBlock
124 }
125​
126 return {
127 shouldBlockFn: _customBlockerFn,
128 enableBeforeUnload: shouldBlock,
129 withResolver: fn === undefined,
130 }
132​
133export function useBlocker<
134 TRouter extends AnyRouter = RegisteredRouter,
135 TWithResolver extends boolean = false,
136>(
137 opts: UseBlockerOpts<TRouter, TWithResolver>,
138): TWithResolver extends true ? BlockerResolver<TRouter> : void
139​
140/**
141 * @deprecated Use the shouldBlockFn property instead
142 */
143export function useBlocker(blockerFnOrOpts?: LegacyBlockerOpts): BlockerResolver
144​
145/**
146 * @deprecated Use the UseBlockerOpts object syntax instead
147 */
148export function useBlocker(
149 blockerFn?: LegacyBlockerFn,
150 condition?: boolean | any,
151): BlockerResolver
152​
153export function useBlocker(
154 opts?: UseBlockerOpts | LegacyBlockerOpts | LegacyBlockerFn,
155 condition?: boolean | any,
156): BlockerResolver | void {
157 const {
158 shouldBlockFn,
159 enableBeforeUnload = true,
160 disabled = false,
161 withResolver = false,
162 } = _resolveBlockerOpts(opts, condition)
163​
164 const router = useRouter()
165 const { history } = router
166​
167 const [resolver, setResolver] = React.useState<BlockerResolver>({
168 status: 'idle',
169 current: undefined,
170 next: undefined,
171 action: undefined,
172 proceed: undefined,
173 reset: undefined,
174 })
175​
176 React.useEffect(() => {
177 const blockerFnComposed = async (blockerFnArgs: BlockerFnArgs) => {
178 function getLocation(
179 location: HistoryLocation,
180 ): AnyShouldBlockFnLocation {
181 const parsedLocation = router.parseLocation(location)
182 const [, rawParams, foundRoute] = router.getMatchedRoutes(
183 parsedLocation.pathname,
184 )
185 if (foundRoute === undefined) {
186 return {
187 routeId: '__notFound__',
188 fullPath: parsedLocation.pathname,
189 pathname: parsedLocation.pathname,
190 params: rawParams,
191 search: router.options.parseSearch(location.search),
192 }
193 }
194​
195 return {
196 routeId: foundRoute.id,
197 fullPath: foundRoute.fullPath,
198 pathname: parsedLocation.pathname,
199 params: rawParams,
200 search: router.options.parseSearch(location.search),
201 }
202 }
203​
204 const current = getLocation(blockerFnArgs.currentLocation)
205 const next = getLocation(blockerFnArgs.nextLocation)
206​
207 if (
208 current.routeId === '__notFound__' &&
209 next.routeId !== '__notFound__'
210 ) {
211 return false
212 }
213​
214 const shouldBlock = await shouldBlockFn({
215 action: blockerFnArgs.action,
216 current,
217 next,
218 })
219 if (!withResolver) {
220 return shouldBlock
221 }
222​
223 if (!shouldBlock) {
224 return false
225 }
226​
227 const promise = new Promise<boolean>((resolve) => {
228 setResolver({
229 status: 'blocked',
230 current,
231 next,
232 action: blockerFnArgs.action,
233 proceed: () => resolve(false),
234 reset: () => resolve(true),
235 })
236 })
237​
238 const canNavigateAsync = await promise
239 setResolver({
240 status: 'idle',
241 current: undefined,
242 next: undefined,
243 action: undefined,
244 proceed: undefined,
245 reset: undefined,
246 })
247​
248 return canNavigateAsync
249 }
250​
251 return disabled
252 ? undefined
253 : history.block({ blockerFn: blockerFnComposed, enableBeforeUnload })
254 }, [
255 shouldBlockFn,
256 enableBeforeUnload,
257 disabled,
258 withResolver,
259 history,
260 router,
261 ])
262​
263 return resolver
265​
266const _resolvePromptBlockerArgs = (
267 props: PromptProps | LegacyPromptProps,
268): UseBlockerOpts => {
269 if ('shouldBlockFn' in props) {
270 return { ...props }
271 }
272​
273 const shouldBlock = Boolean(props.condition ?? true)
274 const fn = props.blockerFn
275​
276 const _customBlockerFn = async () => {
277 if (shouldBlock && fn !== undefined) {
278 return await fn()
279 }
280 return shouldBlock
281 }
282​
283 return {
284 shouldBlockFn: _customBlockerFn,
285 enableBeforeUnload: shouldBlock,
286 withResolver: fn === undefined,
287 }
289​
290export function Block<
291 TRouter extends AnyRouter = RegisteredRouter,
292 TWithResolver extends boolean = boolean,
293>(opts: PromptProps<TRouter, TWithResolver>): React.ReactNode
294​
295/**
296 * @deprecated Use the UseBlockerOpts property instead
297 */
298export function Block(opts: LegacyPromptProps): React.ReactNode
299​
300export function Block(opts: PromptProps | LegacyPromptProps): React.ReactNode {
301 const { children, ...rest } = opts
302 const args = _resolvePromptBlockerArgs(rest)
303​
304 const resolver = useBlocker(args)
305 return children
306 ? typeof children === 'function'
307 ? children(resolver as any)
308 : children
309 : null
311​
312type LegacyPromptProps = {
313 blockerFn?: LegacyBlockerFn
314 condition?: boolean | any
315 children?: React.ReactNode | ((params: BlockerResolver) => React.ReactNode)
317​
318type PromptProps<
319 TRouter extends AnyRouter = RegisteredRouter,
320 TWithResolver extends boolean = boolean,
321 TParams = TWithResolver extends true ? BlockerResolver<TRouter> : void,
322> = UseBlockerOpts<TRouter, TWithResolver> & {
323 children?: React.ReactNode | ((params: TParams) => React.ReactNode)