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

useBlocker.tsx

321 lines8.0 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​
16interface 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 matchedRoutes = router.getMatchedRoutes(
190 parsedLocation.pathname,
191 undefined,
192 )
193 if (matchedRoutes.foundRoute === undefined) {
194 throw new Error(`No route found for location ${location.href}`)
195 }
196 return {
197 routeId: matchedRoutes.foundRoute.id,
198 fullPath: matchedRoutes.foundRoute.fullPath,
199 pathname: parsedLocation.pathname,
200 params: matchedRoutes.routeParams,
201 search: parsedLocation.search,
202 }
203 }
204​
205 const current = getLocation(blockerFnArgs.currentLocation)
206 const next = getLocation(blockerFnArgs.nextLocation)
207​
208 const shouldBlock = await props.shouldBlockFn({
209 action: blockerFnArgs.action,
210 current,
211 next,
212 })
213 if (!props.withResolver) {
214 return shouldBlock
215 }
216​
217 if (!shouldBlock) {
218 return false
219 }
220​
221 const promise = new Promise<boolean>((resolve) => {
222 setResolver({
223 status: 'blocked',
224 current,
225 next,
226 action: blockerFnArgs.action,
227 proceed: () => resolve(false),
228 reset: () => resolve(true),
229 })
230 })
231​
232 const canNavigateAsync = await promise
233 setResolver({
234 status: 'idle',
235 current: undefined,
236 next: undefined,
237 action: undefined,
238 proceed: undefined,
239 reset: undefined,
240 })
241​
242 return canNavigateAsync
243 }
244​
245 const disposeBlock = props.disabled
246 ? undefined
247 : router.history.block({
248 blockerFn: blockerFnComposed,
249 enableBeforeUnload: props.enableBeforeUnload,
250 })
251​
252 Solid.onCleanup(() => disposeBlock?.())
253 })
254​
255 return resolver
257​
258const _resolvePromptBlockerArgs = (
259 props: PromptProps | LegacyPromptProps,
260): UseBlockerOpts => {
261 if ('shouldBlockFn' in props) {
262 return props
263 }
264​
265 const shouldBlock = Solid.createMemo(() => Boolean(props.condition ?? true))
266​
267 const _customBlockerFn = async () => {
268 if (shouldBlock() && props.blockerFn !== undefined) {
269 return await props.blockerFn()
270 }
271 return shouldBlock
272 }
273​
274 return {
275 shouldBlockFn: _customBlockerFn,
276 get enableBeforeUnload() {
277 return shouldBlock()
278 },
279 get withResolver() {
280 return props.blockerFn === undefined
281 },
282 }
284​
285export function Block<
286 TRouter extends AnyRouter = RegisteredRouter,
287 TWithResolver extends boolean = boolean,
288>(opts: PromptProps<TRouter, TWithResolver>): SolidNode
289​
290/**
291 * @deprecated Use the UseBlockerOpts property instead
292 */
293export function Block(opts: LegacyPromptProps): SolidNode
294​
295export function Block(opts: PromptProps | LegacyPromptProps): SolidNode {
296 const [propsWithChildren, rest] = Solid.splitProps(opts, ['children'])
297 const args = _resolvePromptBlockerArgs(rest)
298​
299 const resolver = useBlocker(args)
300 const children = Solid.createMemo(() => {
301 const child = propsWithChildren.children
302 if (resolver && typeof child === 'function') return child(resolver())
303 return child
304 })
305​
306 return <>{children()}</>
308​
309type LegacyPromptProps = {
310 blockerFn?: LegacyBlockerFn
311 condition?: boolean | any
312 children?: SolidNode | ((params: BlockerResolver) => SolidNode)
314​
315type PromptProps<
316 TRouter extends AnyRouter = RegisteredRouter,
317 TWithResolver extends boolean = boolean,
318 TParams = TWithResolver extends true ? BlockerResolver<TRouter> : void,
319> = UseBlockerOpts<TRouter, TWithResolver> & {
320 children?: SolidNode | ((params: TParams) => SolidNode)