Skip to content

Commit abde9e6

Browse files
ryansolidclaudecursoragent
committed
feat(solid-router): declare the route the document arrived on to Solid's observe tier
The Solid adapter declared every navigation's match publish to the observe tier, but the first page has no publish to wrap, so the route the page loaded as was never declared, and on the server the request's "render" record had a URL and no route. solid-js / @solidjs/web 2.0.0-rc.12 added NavigationRef.initial and RenderEvent.route for exactly this; Solid Router adopted them in solidjs/solid-router#623. RouterContextProvider now wraps the work that establishes its initial match (the ready memo, which on the server starts the load) in the same call, with initial: true on the ref: - Client: the engine opens the frame at the time origin and settles it as the provider returns: the first "navigation" record, initial: true, writes: 0, at: 0, no from; kept out of feedback().navigations. - Server: there is no engine; the server entry's withOrigin files the ref on the render, and the "render" record carries RenderEvent.route ({ name, to, params }), read at settle, after a provider-run load. describeInitial shares describeRoute with describeNavigation; its fields are getters over router.latestLocation. The Transitioner's post-mount commit of the canonical arrival location (search defaults, trailing slash) is the arrival's, not a navigation, the TanStack form of #623's "an empty arrival normalized onto the base". With the router loaded before mount, resolvedLocation was already set and that commit was declared as a navigation from the arrival to itself; without it, the arrival's history change left requestedAt set and the next real navigation was dated from the mount. The commit is now marked, and every non-pending publish answers the pending request, declared or not. Co-authored-by: Claude <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent d4284cb commit abde9e6

6 files changed

Lines changed: 263 additions & 34 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@tanstack/solid-router': patch
3+
---
4+
5+
Observe tier (Solid's dev and observe builds only): the router declares the route the document arrived on, with the same `OBSERVE.attribution.withOrigin` call it makes for every navigation, around the work in `RouterProvider` that establishes its initial match (`initial: true` on the ref), on both sides. On the client this is the first `"navigation"` record (`initial: true`, `at` the document's navigation start, no write to wait for), kept out of `feedback().navigations`; on the server the same declaration names the request's `"render"` record (`RenderEvent.route`: the matched route's `fullPath`, the pathname, the params), read when the render settles, so a render whose provider ran the load names the location it resolved. A consumer naming page loads and requests by route (`/users/$id` rather than one name per user) had this for every navigation but the first; now it has the first too.
6+
7+
The Transitioner committing the canonical form of the arrival location (search defaults, trailing slash) is part of the arrival, not a navigation: a router loaded before it mounted no longer records it as one, and the next navigation is dated from its own request rather than from that commit. Nothing changes in production, where `OBSERVE` is undefined.

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

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { SafeFragment } from './SafeFragment'
55
import { Matches } from './Matches'
66
import { serializeMatchTransfer } from './registryTransfer'
77
import { setupFlightDataConsumer } from './flightData'
8+
import { describeInitial } from './observe'
89
import type {
910
AnyRouter,
1011
RegisteredRouter,
@@ -49,11 +50,18 @@ export function RouterContextProvider<
4950
// on the client it resolves immediately and the boot is handled by the
5051
// registry priming in the Router constructor plus Transitioner's
5152
// settled-time load.
52-
const ready = Solid.createMemo(() =>
53-
(isServer ?? router.isServer) && !router._serverResult
54-
? router.load().then(() => true)
55-
: true,
56-
)
53+
const establish = () =>
54+
Solid.createMemo(() =>
55+
(isServer ?? router.isServer) && !router._serverResult
56+
? router.load().then(() => true)
57+
: true,
58+
)
59+
// The route the document arrived on, declared to Solid's observe tier
60+
// around the work that establishes the initial match (see
61+
// `describeInitial`); folded out of production with `OBSERVE`.
62+
const ready = Solid.OBSERVE
63+
? Solid.OBSERVE.attribution.withOrigin(describeInitial(router), establish)
64+
: establish()
5765

5866
// Client-side, the provider is where the router meets Solid's
5967
// server-function transport: it consumes the response metadata mutations

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

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ import { useRouter } from './useRouter'
55
import { describeNavigation } from './observe'
66
import type { AnyRouteMatch } from '@tanstack/router-core'
77

8+
/** The history change was the arrival's own canonicalization, not a request. */
9+
const ARRIVAL = Symbol()
10+
811
function getResolvedLocation(router: ReturnType<typeof useRouter>) {
912
const resolvedLocation = router.stores.resolvedLocation.get()
1013
if (
@@ -35,9 +38,12 @@ export function Transitioner() {
3538
// navigation that caused it: wrap the write whose landing is the
3639
// destination showing — here the match publish, after router-core awaited
3740
// the loaders — and pass `at`, since the request predates it. The first
38-
// history change since the last declared publish is that request: the
39-
// moment the user asked, which is where the navigation's wait starts.
40-
let requestedAt: number | undefined
41+
// history change since the last publish is that request: the moment the
42+
// user asked, which is where the navigation's wait starts. `ARRIVAL` when
43+
// the change was the arrival being canonicalized (below): the initial
44+
// declaration already covers it.
45+
let requestedAt: number | typeof ARRIVAL | undefined
46+
let canonicalizing = false
4147

4248
// Ack when the commit's transition settles (the atomic swap), not when the
4349
// flush parks it; superseded or rolled-back commits resolve false.
@@ -51,14 +57,19 @@ export function Transitioner() {
5157
acks.push(ack)
5258
let publish = fn
5359
// The pending offer (`offerPending`, a match with `status: 'pending'`)
54-
// is not the destination: published undeclared.
60+
// is not the destination: published undeclared, the request kept for
61+
// the publish that lands. Every other publish answers the request.
5562
if (
5663
Solid.OBSERVE !== undefined &&
5764
!expectedMatches.some((match) => match.status === 'pending')
5865
) {
59-
const ref = describeNavigation(router, requestedAt)
66+
const answered = requestedAt
67+
requestedAt = undefined
68+
const ref =
69+
answered === ARRIVAL
70+
? undefined
71+
: describeNavigation(router, answered)
6072
if (ref !== undefined) {
61-
requestedAt = undefined
6273
const observe = Solid.OBSERVE
6374
publish = () => observe.attribution.withOrigin(ref, fn)
6475
}
@@ -94,7 +105,10 @@ export function Transitioner() {
94105

95106
Solid.onSettled(() => {
96107
const unsub = router.history.subscribe(() => {
97-
requestedAt ??= performance.now()
108+
if (canonicalizing) requestedAt ??= ARRIVAL
109+
else if (requestedAt === undefined || requestedAt === ARRIVAL) {
110+
requestedAt = performance.now()
111+
}
98112
queueMicrotask(() => router.load().catch(console.error))
99113
})
100114

@@ -113,11 +127,18 @@ export function Transitioner() {
113127
trimPathRight(router.latestLocation.publicHref) !==
114128
trimPathRight(nextLocation.publicHref)
115129
) {
116-
router.commitLocation({
117-
...nextLocation,
118-
replace: true,
119-
ignoreBlocker: true,
120-
})
130+
// The history notifies synchronously inside the commit (no blocker to
131+
// await), so the subscriber above sees the flag.
132+
canonicalizing = true
133+
try {
134+
router.commitLocation({
135+
...nextLocation,
136+
replace: true,
137+
ignoreBlocker: true,
138+
})
139+
} finally {
140+
canonicalizing = false
141+
}
121142
return unsub
122143
}
123144

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

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,9 @@ function describeRoute(
2828

2929
/**
3030
* The navigation a match publish lands: the latest location, from the one
31-
* shown. Nothing when nothing is shown yet (the initial load) or the publish
32-
* reloads what is shown. `at` dates it from the history change that started
33-
* the load.
31+
* shown. Nothing when nothing is shown yet (the initial load — declared by
32+
* `describeInitial`) or the publish reloads what is shown. `at` dates it
33+
* from the history change that started the load.
3434
*/
3535
export function describeNavigation(
3636
router: AnyRouter,
@@ -48,3 +48,30 @@ export function describeNavigation(
4848
if (at !== undefined) ref.at = at
4949
return ref
5050
}
51+
52+
/**
53+
* The route the document arrived on, declared around the work that
54+
* establishes the router's initial match, since a fresh document has no
55+
* publish to wrap. On the client the engine opens it at the time origin and
56+
* settles it as that work returns (the first `"navigation"` record,
57+
* `initial: true`); on the server the same call names the request's
58+
* `"render"` record (`RenderEvent.route`). The fields are getters read at
59+
* settle, so a server render whose provider ran the load names the location
60+
* the load resolved.
61+
*/
62+
export function describeInitial(router: AnyRouter): NavigationRef {
63+
const pathname = () => router.latestLocation.pathname
64+
return {
65+
kind: 'navigation',
66+
initial: true,
67+
get to() {
68+
return pathname()
69+
},
70+
get name() {
71+
return describeRoute(router, pathname()).name
72+
},
73+
get params() {
74+
return describeRoute(router, pathname()).params
75+
},
76+
}
77+
}

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

Lines changed: 83 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
// Solid's observe tier: the match publish inside `startTransition` is
22
// declared to the attribution engine as the navigation, so the holds and
33
// 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.
4+
// the history change that started the load; the route the document arrived
5+
// on is declared when the provider establishes its initial match. `OBSERVE`
6+
// is defined on the dev build the tests resolve; in production it is
7+
// undefined and the declarations fold out.
78
import { cleanup, render, screen, waitFor } from '@solidjs/testing-library'
89
import { afterEach, beforeEach, expect, test } from 'vitest'
9-
import { attribution } from 'solid-js/attribution'
10+
import { attribution, feedback } from 'solid-js/attribution'
1011
import { z } from 'zod'
1112
import {
1213
Outlet,
@@ -25,6 +26,9 @@ afterEach(() => {
2526

2627
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
2728

29+
const navigations = () =>
30+
attribution.history('navigation').filter((nav) => !nav.initial)
31+
2832
function makeRouter(loaderMs: number, initialEntry = '/') {
2933
const rootRoute = createRootRoute({ component: () => <Outlet /> })
3034
const indexRoute = createRoute({
@@ -71,13 +75,80 @@ function makeRouter(loaderMs: number, initialEntry = '/') {
7175
})
7276
}
7377

78+
test('mounting declares the route the document arrived on — the first record, initial', async () => {
79+
const router = makeRouter(30, '/users/42?tab=posts')
80+
render(() => <RouterProvider router={router} />)
81+
// Delivered as the provider established its initial match: nothing to
82+
// wait for, so the record settled before the loader ran.
83+
expect(attribution.history('navigation')).toHaveLength(1)
84+
const nav = attribution.history('navigation')[0]!
85+
expect(nav.initial).toBe(true)
86+
expect(nav.name).toBe('/users/$id')
87+
expect(nav.to).toBe('/users/42')
88+
expect(nav.params).toEqual({ id: '42' })
89+
expect(nav.from).toBeUndefined()
90+
expect(nav.interaction).toBeUndefined()
91+
// The document's own navigation start on the performance clock.
92+
expect(nav.at).toBe(0)
93+
expect(nav.writes).toBe(0)
94+
expect(nav.outcome).toBe('committed')
95+
96+
// The initial load publishes matches for the location already shown: not
97+
// a navigation.
98+
await waitFor(() => expect(screen.getByTestId('user')).toBeTruthy())
99+
await sleep(0)
100+
expect(attribution.history('navigation')).toHaveLength(1)
101+
})
102+
103+
test.each([false, true])(
104+
'an arrival the router canonicalizes is the one initial record, not a navigation (loaded before mount: %s)',
105+
async (preloaded) => {
106+
// `/about` validates to `/about?tab=info`; the Transitioner commits the
107+
// canonical location once mounted. That write is the arrival's.
108+
const router = makeRouter(0, '/about')
109+
if (preloaded) await router.load()
110+
render(() => <RouterProvider router={router} />)
111+
await waitFor(() => expect(screen.getByTestId('about')).toBeTruthy())
112+
await waitFor(() =>
113+
expect(router.stores.resolvedLocation.get()?.href).toBe(
114+
'/about?tab=info',
115+
),
116+
)
117+
await sleep(0)
118+
const navs = attribution.history('navigation')
119+
expect(navs).toHaveLength(1)
120+
expect(navs[0]!.initial).toBe(true)
121+
expect(navs[0]!.name).toBe('/about')
122+
123+
// The next navigation is dated from its own request, not the arrival's.
124+
const requested = performance.now()
125+
await router.navigate({ to: '/' })
126+
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
127+
await sleep(0)
128+
expect(navigations()).toHaveLength(1)
129+
expect(navigations()[0]!.name).toBe('/')
130+
expect(navigations()[0]!.at).toBeGreaterThanOrEqual(requested)
131+
},
132+
)
133+
134+
test('the initial declaration is not a row in feedback().navigations', async () => {
135+
const router = makeRouter(0)
136+
render(() => <RouterProvider router={router} />)
137+
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
138+
expect(attribution.history('navigation').at(-1)!.initial).toBe(true)
139+
await router.navigate({ to: '/users/$id', params: { id: '1' } })
140+
await waitFor(() => expect(screen.getByTestId('user')).toBeTruthy())
141+
await sleep(0)
142+
const rows = feedback().navigations
143+
expect(rows.map((row) => row.name)).toEqual(['/users/$id'])
144+
expect(rows[0]!.navigations).toBe(1)
145+
})
146+
74147
test('the match publish is declared as the navigation, dated from the history change', async () => {
75148
const router = makeRouter(30)
76149
render(() => <RouterProvider router={router} />)
77150
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
78-
// The initial load publishes matches for the location already shown: not
79-
// a navigation.
80-
expect(attribution.history('navigation')).toHaveLength(0)
151+
expect(navigations()).toHaveLength(0)
81152

82153
const requested = performance.now()
83154
await router.navigate({ to: '/users/$id', params: { id: '42' } })
@@ -86,7 +157,7 @@ test('the match publish is declared as the navigation, dated from the history ch
86157

87158
// One record for the navigation — the pending offer (a match with
88159
// `status: 'pending'`) is published undeclared.
89-
const navs = attribution.history('navigation')
160+
const navs = navigations()
90161
expect(navs).toHaveLength(1)
91162
const nav = navs[0]!
92163
expect(nav.name).toBe('/users/$id')
@@ -115,7 +186,7 @@ test('a navigation superseded before it published leaves one record for the dest
115186
)
116187
await sleep(0)
117188

118-
const navs = attribution.history('navigation')
189+
const navs = navigations()
119190
expect(navs).toHaveLength(1)
120191
expect(navs[0]!.to).toBe('/users/2')
121192
// Dated from the first request: that is when the user started waiting.
@@ -134,7 +205,7 @@ test('a not-found is named by its pathname, not by the route above it', async ()
134205
await router.navigate({ to: '/about/nope' as any })
135206
await sleep(10)
136207

137-
const navs = attribution.history('navigation')
208+
const navs = navigations()
138209
expect(navs.map((nav) => [nav.name, nav.params])).toEqual([
139210
['/nope/deeper', undefined],
140211
['/about/nope', undefined],
@@ -150,8 +221,6 @@ test('params are the strings the path bound, before `params.parse`', async () =>
150221
await waitFor(() => expect(screen.getByTestId('post')).toBeTruthy())
151222
await sleep(0)
152223

153-
expect(attribution.history('navigation')[0]!.name).toBe('/posts/$postId')
154-
expect(attribution.history('navigation')[0]!.params).toEqual({
155-
postId: '5',
156-
})
224+
expect(navigations()[0]!.name).toBe('/posts/$postId')
225+
expect(navigations()[0]!.params).toEqual({ postId: '5' })
157226
})

0 commit comments

Comments
 (0)