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

useBlocker.tsx

309 lines7.6 KB

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