Open History to see the last commit
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
27}
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
64}
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
77}
78β
79type LegacyBlockerFn = () => Promise<any> | any
80type LegacyBlockerOpts = {
81 blockerFn?: LegacyBlockerFn
82 condition?: boolean | any
83}
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 }
135}
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
256}
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 }
283}
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()}</>
307}
308β
309type LegacyPromptProps = {
310 blockerFn?: LegacyBlockerFn
311 condition?: boolean | any
312 children?: SolidNode | ((params: BlockerResolver) => SolidNode)
313}
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)
321}