Skip to content

Commit 8f46655

Browse files
ryansolidClaude via Cursorcursoragent
committed
feat(solid-router): declare navigations to Solid's observe tier
On Solid's dev and observe builds the match publish inside startTransition is wrapped in OBSERVE.attribution.withOrigin: the ref names the destination route (fullPath, params, to/from pathnames) and dates from the history change that started the load, so the record spans the loader wait even though the publish comes after it. The pending offer, the initial load and same-location reloads are published undeclared. Production is unchanged (OBSERVE is undefined). Co-authored-by: Claude via Cursor <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 8981eb7 commit 8f46655

3 files changed

Lines changed: 158 additions & 1 deletion

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+
Declare navigations to Solid's observe tier. On Solid's dev and observe builds (`OBSERVE` defined), the match publish inside `startTransition` is wrapped in `OBSERVE.attribution.withOrigin` with the destination route's `fullPath`, params, `to`/`from` pathnames and `at` from the history change that started the load, so the holds and re-runs a navigation causes are named after the route and the record spans the loader wait. The pending offer, the initial load and same-location reloads are published undeclared. Nothing changes in production, where `OBSERVE` is undefined.

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

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,44 @@ 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 type { NavigationRef } from 'solid-js'
56
import type { AnyRouteMatch } from '@tanstack/router-core'
67

8+
/**
9+
* Solid's observe tier (`OBSERVE` is defined on the dev and observe builds,
10+
* undefined in production) attributes what the user waited on to the
11+
* navigation that caused it. The rule for every router is the same: wrap the
12+
* write whose landing is the destination showing, and pass `at` when the
13+
* request predates that write. Here that write is the match publish inside
14+
* `startTransition` — the loaders were awaited in router-core before it —
15+
* so the ref names the destination route from the expected matches and
16+
* dates from the history change that started the load. The pending offer
17+
* (`offerPending`, a match with `status: 'pending'`) is not the destination
18+
* and is published undeclared; the initial load and a same-location reload
19+
* are not navigations.
20+
*/
21+
function describeNavigation(
22+
router: ReturnType<typeof useRouter>,
23+
expected: Array<AnyRouteMatch>,
24+
at: number | undefined,
25+
): NavigationRef | undefined {
26+
if (expected.some((match) => match.status === 'pending')) return
27+
const to = router.latestLocation
28+
const from = router.stores.resolvedLocation.get()
29+
// Nothing shown yet (the initial load), or a reload of what is shown.
30+
if (!from || from.href === to.href) return
31+
const leaf = expected[expected.length - 1]
32+
const ref: NavigationRef = {
33+
kind: 'navigation',
34+
name: leaf?.fullPath || to.pathname,
35+
to: to.pathname,
36+
from: from.pathname,
37+
}
38+
if (leaf && Object.keys(leaf.params).length) ref.params = leaf.params
39+
if (at !== undefined) ref.at = at
40+
return ref
41+
}
42+
743
function getResolvedLocation(router: ReturnType<typeof useRouter>) {
844
const resolvedLocation = router.stores.resolvedLocation.get()
945
if (
@@ -30,6 +66,10 @@ export function Transitioner() {
3066
committed.length === expected.length &&
3167
expected.every((match, index) => committed![index] === match)
3268

69+
// When the history changed since the last declared publish: the moment
70+
// the user asked, which is where the navigation's wait starts.
71+
let requestedAt: number | undefined
72+
3373
// Ack when the commit's transition settles (the atomic swap), not when the
3474
// flush parks it; superseded or rolled-back commits resolve false.
3575
router.startTransition = (fn, expectedMatches) => {
@@ -40,7 +80,16 @@ export function Transitioner() {
4080
return new Promise((resolve) => {
4181
const ack: Ack = [expectedMatches, resolve]
4282
acks.push(ack)
43-
Solid.runWithOwner(null, fn)
83+
let publish = fn
84+
if (Solid.OBSERVE !== undefined) {
85+
const ref = describeNavigation(router, expectedMatches, requestedAt)
86+
if (ref !== undefined) {
87+
requestedAt = undefined
88+
const observe = Solid.OBSERVE
89+
publish = () => observe.attribution.withOrigin(ref, fn)
90+
}
91+
}
92+
Solid.runWithOwner(null, publish)
4493
try {
4594
Solid.flush()
4695
} catch {
@@ -71,6 +120,7 @@ export function Transitioner() {
71120

72121
Solid.onSettled(() => {
73122
const unsub = router.history.subscribe(() => {
123+
requestedAt ??= performance.now()
74124
queueMicrotask(() => router.load().catch(console.error))
75125
})
76126

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// Solid's observe tier: the match publish inside `startTransition` is
2+
// declared to the attribution engine as the navigation, so the holds and
3+
// re-runs it causes are named after the route and the record spans from
4+
// the history change that started the load. `OBSERVE` is defined on the
5+
// dev build the tests resolve; in production it is undefined and the
6+
// declaration folds out.
7+
import { cleanup, render, screen, waitFor } from '@solidjs/testing-library'
8+
import { afterEach, beforeEach, expect, test } from 'vitest'
9+
import { attribution } from 'solid-js/attribution'
10+
import {
11+
Outlet,
12+
RouterProvider,
13+
createMemoryHistory,
14+
createRootRoute,
15+
createRoute,
16+
createRouter,
17+
} from '../src'
18+
19+
beforeEach(() => attribution.enable({ log: false }))
20+
afterEach(() => {
21+
attribution.disable()
22+
cleanup()
23+
})
24+
25+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
26+
27+
function makeRouter(loaderMs: number) {
28+
const rootRoute = createRootRoute({ component: () => <Outlet /> })
29+
const indexRoute = createRoute({
30+
getParentRoute: () => rootRoute,
31+
path: '/',
32+
component: () => <div data-testid="home">Home</div>,
33+
})
34+
const userRoute = createRoute({
35+
getParentRoute: () => rootRoute,
36+
path: '/users/$id',
37+
loader: async ({ params }) => {
38+
await sleep(loaderMs)
39+
return { name: `user ${params.id}` }
40+
},
41+
component: () => {
42+
const data = userRoute.useLoaderData()
43+
return <div data-testid="user">{data().name}</div>
44+
},
45+
})
46+
const routeTree = rootRoute.addChildren([indexRoute, userRoute])
47+
return createRouter({
48+
routeTree,
49+
history: createMemoryHistory({ initialEntries: ['/'] }),
50+
})
51+
}
52+
53+
test('the match publish is declared as the navigation, dated from the history change', async () => {
54+
const router = makeRouter(30)
55+
render(() => <RouterProvider router={router} />)
56+
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
57+
// The initial load publishes matches for the location already shown: not
58+
// a navigation.
59+
expect(attribution.navigations()).toHaveLength(0)
60+
61+
const requested = performance.now()
62+
await router.navigate({ to: '/users/$id', params: { id: '42' } })
63+
await waitFor(() => expect(screen.getByTestId('user')).toBeTruthy())
64+
await sleep(0)
65+
66+
// One record for the navigation — the pending offer (a match with
67+
// `status: 'pending'`) is published undeclared.
68+
const navs = attribution.navigations()
69+
expect(navs).toHaveLength(1)
70+
const nav = navs[0]!
71+
expect(nav.name).toBe('/users/$id')
72+
expect(nav.to).toBe('/users/42')
73+
expect(nav.from).toBe('/')
74+
expect(nav.params).toEqual({ id: '42' })
75+
expect(nav.outcome).toBe('committed')
76+
// `at` is the history change inside navigate(), before the loader ran:
77+
// the record spans the loader wait even though the publish came after it.
78+
expect(nav.at).toBeGreaterThanOrEqual(requested)
79+
expect(nav.at).toBeLessThan(requested + 30)
80+
expect(nav.settledMs!).toBeGreaterThanOrEqual(30)
81+
})
82+
83+
test('a navigation superseded before it published leaves one record for the destination that showed', async () => {
84+
const router = makeRouter(30)
85+
render(() => <RouterProvider router={router} />)
86+
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
87+
88+
const requested = performance.now()
89+
void router.navigate({ to: '/users/$id', params: { id: '1' } })
90+
await sleep(5)
91+
await router.navigate({ to: '/users/$id', params: { id: '2' } })
92+
await waitFor(() =>
93+
expect(screen.getByTestId('user').textContent).toBe('user 2'),
94+
)
95+
await sleep(0)
96+
97+
const navs = attribution.navigations()
98+
expect(navs).toHaveLength(1)
99+
expect(navs[0]!.to).toBe('/users/2')
100+
// Dated from the first request: that is when the user started waiting.
101+
expect(navs[0]!.at).toBeLessThan(requested + 5)
102+
})

0 commit comments

Comments
 (0)