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

useBlocker.tsx

338 lines8.3 KB

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