Skip to content

Commit 5f1a361

Browse files
ryansolidclaudecursoragent
committed
fix(solid-router): keep the requesting interaction across a useBlocker await
The Transitioner dated a navigation and captured its interaction when the history notified. With a blocker registered, the history awaits the blocker before it pushes, so the notification ran in a later task: the interaction was gone from the stack and the record declared none, and a navigation held until `proceed()` was dated from the confirm with no interaction either. Solid Router has neither gap: its leave guard runs synchronously inside navigate(), and a blocked navigation retried from the confirm (`retry()`) navigates in the confirm's interaction. Note the request (time, `currentOrigin()`) at `commitLocation`, before the history is asked, for the history change it causes to take. A `useBlocker` consulted synchronously as the first blocker holds it past the commit; `proceed()` notes a new request in the interaction that proceeds, so the navigation joins the confirm as Solid Router's `retry()` does; a blocker that stops the navigation drops it; a commit that changed no history releases it as it returns. Only on the client, only where `OBSERVE` is defined. Co-authored-by: Claude <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent c70a2ce commit 5f1a361

6 files changed

Lines changed: 199 additions & 16 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/solid-router': patch
3+
---
4+
5+
Observe tier (Solid's dev and observe builds only): a navigation that passes a `useBlocker` keeps the interaction that requested it and is dated from the request, though the history awaits the blocker before it changes; one the blocker holds until `proceed()` joins the interaction that proceeds and is dated from it, as `@solidjs/router`'s `retry()` makes it. The router notes the request at `commitLocation` for the history change to take. A navigation the blocker stops, or a request that changes no history (the same location reloading), leaves nothing noted behind. Nothing changes in production, where `OBSERVE` is undefined.

‎packages/solid-router/src/Transitioner.tsx‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,14 @@ import * as Solid from 'solid-js'
22
import { getLocationChangeInfo, trimPathRight } from '@tanstack/router-core'
33
import { isServer } from '@tanstack/router-core/isServer'
44
import { useRouter } from './useRouter'
5-
import { describeInitial, describeNavigation } from './observe'
5+
import { describeInitial, describeNavigation, takeRequest } from './observe'
66
import type { NavigationRequest } from './observe'
7+
import type { RouterHistory } from '@tanstack/history'
78
import type { AnyRouteMatch, ParsedLocation } from '@tanstack/router-core'
89

10+
/** What the history tells its subscribers. */
11+
type HistoryChange = Parameters<Parameters<RouterHistory['subscribe']>[0]>[0]
12+
913
/** The history change was the arrival's own canonicalization, not a request. */
1014
const ARRIVAL = Symbol()
1115

@@ -123,11 +127,18 @@ export function Transitioner() {
123127
)
124128

125129
Solid.onSettled(() => {
126-
const unsub = router.history.subscribe(() => {
130+
const unsub = router.history.subscribe(({ action }: HistoryChange) => {
127131
if (Solid.OBSERVE !== undefined) {
132+
// A push or replace was requested through `commitLocation`, maybe
133+
// before an `await` on the blockers; anything else is the browser
134+
// moving, requested now.
135+
const noted =
136+
action.type === 'PUSH' || action.type === 'REPLACE'
137+
? takeRequest(router)
138+
: undefined
128139
if (canonicalizing) request ??= ARRIVAL
129140
else if (request === undefined || request === ARRIVAL) {
130-
request = {
141+
request = noted ?? {
131142
at: performance.now(),
132143
interaction: Solid.OBSERVE.attribution.currentOrigin(),
133144
}

‎packages/solid-router/src/observe.ts‎

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as Solid from 'solid-js'
12
import type { NavigationRef } from 'solid-js'
23
import type { AnyRouter, ParsedLocation } from '@tanstack/router-core'
34

@@ -18,6 +19,52 @@ export interface NavigationRequest {
1819
interaction: NavigationRef['interaction']
1920
}
2021

22+
const requests = new WeakMap<AnyRouter, NavigationRequest>()
23+
const held = new WeakSet<AnyRouter>()
24+
25+
/**
26+
* Records the navigation being requested now — a `commitLocation`, or a
27+
* blocker's `proceed` — for the history change it causes to answer. The
28+
* history may notify after awaiting its blockers, the interaction gone from
29+
* the stack by then; a later request replaces this one.
30+
*/
31+
export function noteRequest(router: AnyRouter): void {
32+
const observe = Solid.OBSERVE
33+
if (observe === undefined) return
34+
held.delete(router)
35+
requests.set(router, {
36+
at: performance.now(),
37+
interaction: observe.attribution.currentOrigin(),
38+
})
39+
}
40+
41+
/** A blocker is deciding on the noted request: keep it past the commit. */
42+
export function holdRequest(router: AnyRouter): void {
43+
if (requests.has(router)) held.add(router)
44+
}
45+
46+
/**
47+
* The commit that noted the request has returned. Without a blocker
48+
* holding it, the history has notified by then — or never will: the same
49+
* location reloads without a history change.
50+
*/
51+
export function releaseRequest(router: AnyRouter): void {
52+
if (!held.has(router)) requests.delete(router)
53+
}
54+
55+
/** Forgets the noted request: a blocker stopped the navigation it made. */
56+
export function dropRequest(router: AnyRouter): void {
57+
held.delete(router)
58+
requests.delete(router)
59+
}
60+
61+
/** The request noted for the history change being notified, if any. */
62+
export function takeRequest(router: AnyRouter): NavigationRequest | undefined {
63+
const request = requests.get(router)
64+
dropRequest(router)
65+
return request
66+
}
67+
2168
/**
2269
* The route `pathname` matches — its `fullPath` (`/users/$id`) and the raw
2370
* params it bound — or, when no route matches it (a not-found, by the rule
@@ -40,9 +87,9 @@ function describeRoute(
4087
* The navigation a match publish lands: the latest location, from `from`
4188
* (the location shown, or the arrival while the first page is still
4289
* loading). Nothing when the publish reloads the location it came from.
43-
* `request` dates it from the history change and joins it to the interaction
44-
* that asked, both gone by the time the loaders resolve and the publish
45-
* runs; the key's presence declares the interaction, `undefined` included.
90+
* `request` dates it from the request and joins it to the interaction that
91+
* asked, both gone by the time the loaders resolve and the publish runs; the
92+
* key's presence declares the interaction, `undefined` included.
4693
*/
4794
export function describeNavigation(
4895
router: AnyRouter,

‎packages/solid-router/src/router.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
import * as Solid from 'solid-js'
12
import { RouterCore } from '@tanstack/router-core'
23
import { isServer } from '@tanstack/router-core/isServer'
34
import { getStoreFactory } from './routerStores'
45
import { primeRouterFromRegistry } from './registryTransfer'
6+
import { noteRequest, releaseRequest } from './observe'
57
import type { RouterHistory } from '@tanstack/history'
68
import type {
79
AnyRoute,
@@ -112,6 +114,18 @@ export class Router<
112114
// so the first missing entry falls through to unchanged behavior.
113115
if (!(isServer ?? this.isServer)) {
114116
primeRouterFromRegistry(this)
117+
// Solid's observe tier dates a navigation from its request and joins
118+
// it to the interaction it was requested in, both gone by the time a
119+
// blocked history notifies (see `noteRequest`).
120+
if (Solid.OBSERVE !== undefined) {
121+
const commitLocation = this.commitLocation
122+
this.commitLocation = (opts) => {
123+
noteRequest(this)
124+
const committed = commitLocation(opts)
125+
releaseRequest(this)
126+
return committed
127+
}
128+
}
115129
}
116130
}
117131
}

‎packages/solid-router/src/useBlocker.tsx‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as Solid from 'solid-js'
22
import { useRouter } from './useRouter'
3+
import { dropRequest, holdRequest, noteRequest } from './observe'
34
import type {
45
BlockerFnArgs,
56
HistoryAction,
@@ -194,6 +195,11 @@ export function useBlocker(
194195
}
195196

196197
const blockerFnComposed = async (blockerFnArgs: BlockerFnArgs) => {
198+
// Called before the history's first `await` when this is the first
199+
// blocker, so the request `commitLocation` noted outlives the
200+
// commit. A later blocker finds it held by the first, or released
201+
// (the navigation is then dated when the history notifies).
202+
holdRequest(router)
197203
function getLocation(
198204
location: HistoryLocation,
199205
): AnyShouldBlockFnLocation {
@@ -235,6 +241,7 @@ export function useBlocker(
235241
next,
236242
})
237243
if (!props.withResolver) {
244+
if (shouldBlock) dropRequest(router)
238245
return shouldBlock
239246
}
240247

@@ -248,7 +255,12 @@ export function useBlocker(
248255
current,
249256
next,
250257
action: blockerFnArgs.action,
251-
proceed: () => resolve(false),
258+
// The navigation goes ahead in the interaction that proceeds, as
259+
// `@solidjs/router`'s `retry()` makes it.
260+
proceed: () => {
261+
noteRequest(router)
262+
resolve(false)
263+
},
252264
reset: () => resolve(true),
253265
})
254266
})
@@ -263,6 +275,7 @@ export function useBlocker(
263275
reset: undefined,
264276
})
265277

278+
if (canNavigateAsync) dropRequest(router)
266279
return canNavigateAsync
267280
}
268281

‎packages/solid-router/tests/observe-navigation.test.tsx‎

Lines changed: 102 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ import {
2525
createRoute,
2626
createRouter,
2727
redirect,
28+
useBlocker,
2829
} from '../src'
30+
import type { BlockerResolver } from '../src'
2931

3032
beforeEach(() => attribution.enable({ log: false }))
3133
afterEach(() => {
@@ -38,14 +40,26 @@ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
3840
const navigations = () =>
3941
attribution.history('navigation').filter((nav) => !nav.initial)
4042

43+
const click = (target: string, fn: () => void) =>
44+
OBSERVE!.attribution.withInteraction({ type: 'click', target }, fn)
45+
46+
let resolver: (() => BlockerResolver) | undefined
47+
let blocking = false
48+
49+
function Guard() {
50+
resolver = useBlocker({ shouldBlockFn: () => blocking, withResolver: true })
51+
return null
52+
}
53+
4154
function makeRouter(
4255
loaderMs: number,
4356
initialEntry = '/',
44-
options: { pendingComponent?: boolean } = {},
57+
options: { guard?: boolean; pendingComponent?: boolean } = {},
4558
) {
4659
const rootRoute = createRootRoute({
4760
component: () => (
4861
<>
62+
{options.guard ? <Guard /> : null}
4963
<Link to="/users/$id" params={{ id: '7' }} data-testid="link">
5064
User 7
5165
</Link>
@@ -208,7 +222,7 @@ test('the initial declaration is not a row in feedback().navigations', async ()
208222
expect(rows[0]!.navigations).toBe(1)
209223
})
210224

211-
test('the match publish is declared as the navigation, dated from the history change', async () => {
225+
test('the match publish is declared as the navigation, dated from the request', async () => {
212226
const router = makeRouter(30)
213227
render(() => <RouterProvider router={router} />)
214228
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
@@ -231,8 +245,8 @@ test('the match publish is declared as the navigation, dated from the history ch
231245
expect(nav.outcome).toBe('committed')
232246
// Not requested inside an interaction, and declared so.
233247
expect(nav.interaction).toBeUndefined()
234-
// `at` is the history change inside navigate(), before the loader ran:
235-
// the record spans the loader wait even though the publish came after it.
248+
// `at` is the request inside navigate(), before the loader ran: the
249+
// record spans the loader wait even though the publish came after it.
236250
expect(nav.at).toBeGreaterThanOrEqual(requested)
237251
expect(nav.at).toBeLessThan(requested + 30)
238252
expect(nav.settledMs!).toBeGreaterThanOrEqual(30)
@@ -286,20 +300,20 @@ test('a navigation requested in an interaction joins it, though the publish runs
286300
render(() => <RouterProvider router={router} />)
287301
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
288302

289-
let click: ReturnType<
303+
let origin: ReturnType<
290304
NonNullable<typeof OBSERVE>['attribution']['currentOrigin']
291305
>
292-
OBSERVE!.attribution.withInteraction({ type: 'click', target: 'a' }, () => {
293-
click = OBSERVE!.attribution.currentOrigin()
306+
click('a', () => {
307+
origin = OBSERVE!.attribution.currentOrigin()
294308
void router.navigate({ to: '/users/$id', params: { id: '42' } })
295309
})
296310
await waitFor(() => expect(screen.getByTestId('user')).toBeTruthy())
297311
await sleep(0)
298312

299313
const navs = navigations()
300314
expect(navs).toHaveLength(1)
301-
expect(click).toMatchObject({ kind: 'interaction', name: 'click' })
302-
expect(navs[0]!.interaction).toBe(click)
315+
expect(origin).toMatchObject({ kind: 'interaction', name: 'click' })
316+
expect(navs[0]!.interaction).toBe(origin)
303317
expect(navs[0]!.settledMs!).toBeGreaterThanOrEqual(30)
304318
})
305319

@@ -321,6 +335,85 @@ test('a <Link> click is the interaction its navigation joins', async () => {
321335
})
322336
})
323337

338+
test('a blocker that lets the navigation through keeps its interaction; one that holds it gives it the interaction that proceeds', async () => {
339+
blocking = false
340+
const router = makeRouter(0, '/', { guard: true })
341+
render(() => <RouterProvider router={router} />)
342+
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
343+
344+
// The blocker is consulted after an `await` even when it lets the
345+
// navigation through; the request is still the click's, as in
346+
// `@solidjs/router`, whose leave guard runs inside the navigation.
347+
click('a#allowed', () => void router.navigate({ to: '/about' }))
348+
await waitFor(() => expect(screen.getByTestId('about')).toBeTruthy())
349+
await sleep(0)
350+
351+
// Held until the user confirms: the navigation happens in the confirm,
352+
// as `@solidjs/router`'s `retry()` makes it.
353+
blocking = true
354+
click(
355+
'a#held',
356+
() => void router.navigate({ to: '/posts/$postId', params: { postId: 5 } }),
357+
)
358+
await waitFor(() => expect(resolver!().status).toBe('blocked'))
359+
await sleep(5)
360+
const proceeded = performance.now()
361+
click('button#confirm', () => resolver!().proceed!())
362+
await waitFor(() => expect(screen.getByTestId('post')).toBeTruthy())
363+
await sleep(0)
364+
365+
const navs = navigations()
366+
expect(navs.map((nav) => [nav.name, nav.interaction?.target])).toEqual([
367+
['/about', 'a#allowed'],
368+
['/posts/$postId', 'button#confirm'],
369+
])
370+
expect(navs[1]!.at).toBeGreaterThanOrEqual(proceeded)
371+
blocking = false
372+
})
373+
374+
test('a blocked navigation the user resets leaves no request behind', async () => {
375+
blocking = true
376+
const router = makeRouter(0, '/', { guard: true })
377+
render(() => <RouterProvider router={router} />)
378+
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
379+
380+
click('a#held', () => void router.navigate({ to: '/about' }))
381+
await waitFor(() => expect(resolver!().status).toBe('blocked'))
382+
resolver!().reset!()
383+
await sleep(0)
384+
blocking = false
385+
386+
const requested = performance.now()
387+
await router.navigate({ to: '/login' })
388+
await waitFor(() => expect(screen.getByTestId('login')).toBeTruthy())
389+
await sleep(0)
390+
391+
const navs = navigations()
392+
expect(navs).toHaveLength(1)
393+
expect(navs[0]!.name).toBe('/login')
394+
expect(navs[0]!.interaction).toBeUndefined()
395+
expect(navs[0]!.at).toBeGreaterThanOrEqual(requested)
396+
})
397+
398+
test('a request that changed no history leaves none behind', async () => {
399+
const router = makeRouter(0)
400+
render(() => <RouterProvider router={router} />)
401+
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
402+
403+
// The same location reloads without a history change.
404+
click('a#same', () => void router.navigate({ to: '/' }))
405+
await sleep(0)
406+
const requested = performance.now()
407+
router.history.push('/login')
408+
await waitFor(() => expect(screen.getByTestId('login')).toBeTruthy())
409+
await sleep(0)
410+
411+
const navs = navigations()
412+
expect(navs).toHaveLength(1)
413+
expect(navs[0]!.interaction).toBeUndefined()
414+
expect(navs[0]!.at).toBeGreaterThanOrEqual(requested)
415+
})
416+
324417
test('a not-found is named by its pathname, not by the route above it', async () => {
325418
const router = makeRouter(0)
326419
render(() => <RouterProvider router={router} />)

0 commit comments

Comments
 (0)