Skip to content

Commit d4284cb

Browse files
ryansolidclaudecursoragent
committed
fix(solid-router): name observe navigations by the route the pathname matches
The navigation declared to Solid's observe tier took its name and params from the leaf expected match. A not-found's leaf is the route above it, so every unmatched path was named after the root ('/') and folded into the home page's feedback row; and the params were the values params.parse returned, where NavigationRef declares the strings the path bound. Name and params now come from matching the destination pathname (router.getMatchedRoutes, the same rule matchRoutes uses for its 404 entry): the route's fullPath and its raw params, or the pathname itself when no route matches it. The description moves to observe.ts so the initial-route declaration can share it. Co-authored-by: Claude <[email protected]> Co-authored-by: Cursor <[email protected]>
1 parent 070647f commit d4284cb

4 files changed

Lines changed: 127 additions & 43 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's record names a not-found by its pathname instead of the route above it, so `/nope` no longer files under `/` beside the home page, and its `params` are the strings the path bound rather than the values `params.parse` returned, as Solid's `NavigationRef` declares them. Nothing changes in production, where `OBSERVE` is undefined.

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

Lines changed: 14 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,44 +2,9 @@ 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'
5+
import { describeNavigation } from './observe'
66
import type { AnyRouteMatch } from '@tanstack/router-core'
77

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-
438
function getResolvedLocation(router: ReturnType<typeof useRouter>) {
449
const resolvedLocation = router.stores.resolvedLocation.get()
4510
if (
@@ -66,8 +31,12 @@ export function Transitioner() {
6631
committed.length === expected.length &&
6732
expected.every((match, index) => committed![index] === match)
6833

69-
// When the history changed since the last declared publish: the moment
70-
// the user asked, which is where the navigation's wait starts.
34+
// Solid's observe tier attributes what the user waited on to the
35+
// navigation that caused it: wrap the write whose landing is the
36+
// destination showing — here the match publish, after router-core awaited
37+
// 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.
7140
let requestedAt: number | undefined
7241

7342
// Ack when the commit's transition settles (the atomic swap), not when the
@@ -81,8 +50,13 @@ export function Transitioner() {
8150
const ack: Ack = [expectedMatches, resolve]
8251
acks.push(ack)
8352
let publish = fn
84-
if (Solid.OBSERVE !== undefined) {
85-
const ref = describeNavigation(router, expectedMatches, requestedAt)
53+
// The pending offer (`offerPending`, a match with `status: 'pending'`)
54+
// is not the destination: published undeclared.
55+
if (
56+
Solid.OBSERVE !== undefined &&
57+
!expectedMatches.some((match) => match.status === 'pending')
58+
) {
59+
const ref = describeNavigation(router, requestedAt)
8660
if (ref !== undefined) {
8761
requestedAt = undefined
8862
const observe = Solid.OBSERVE
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import type { NavigationRef } from 'solid-js'
2+
import type { AnyRouter } from '@tanstack/router-core'
3+
4+
/**
5+
* What the router says about its navigations to Solid's observe tier
6+
* (`OBSERVE.attribution.withOrigin`; `OBSERVE` is defined on the dev and
7+
* observe builds, undefined in production). A navigation is named by the
8+
* route pattern its pathname matches, so occurrences fold together.
9+
*/
10+
11+
/**
12+
* The route `pathname` matches — its `fullPath` (`/users/$id`) and the raw
13+
* params it bound — or, when no route matches it (a not-found, by the rule
14+
* `matchRoutes` applies), the pathname itself and no params.
15+
*/
16+
function describeRoute(
17+
router: AnyRouter,
18+
pathname: string,
19+
): Pick<NavigationRef, 'name' | 'params'> {
20+
const [, rawParams, route] = router.getMatchedRoutes(pathname)
21+
if (!route || (route.path !== '/' && rawParams['**']))
22+
return { name: pathname }
23+
const { '**': _, ...params } = rawParams
24+
return Object.keys(params).length
25+
? { name: route.fullPath, params }
26+
: { name: route.fullPath }
27+
}
28+
29+
/**
30+
* 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.
34+
*/
35+
export function describeNavigation(
36+
router: AnyRouter,
37+
at: number | undefined,
38+
): NavigationRef | undefined {
39+
const to = router.latestLocation
40+
const from = router.stores.resolvedLocation.get()
41+
if (!from || from.href === to.href) return
42+
const ref: NavigationRef = {
43+
kind: 'navigation',
44+
...describeRoute(router, to.pathname),
45+
to: to.pathname,
46+
from: from.pathname,
47+
}
48+
if (at !== undefined) ref.at = at
49+
return ref
50+
}

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

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import { cleanup, render, screen, waitFor } from '@solidjs/testing-library'
88
import { afterEach, beforeEach, expect, test } from 'vitest'
99
import { attribution } from 'solid-js/attribution'
10+
import { z } from 'zod'
1011
import {
1112
Outlet,
1213
RouterProvider,
@@ -24,13 +25,19 @@ afterEach(() => {
2425

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

27-
function makeRouter(loaderMs: number) {
28+
function makeRouter(loaderMs: number, initialEntry = '/') {
2829
const rootRoute = createRootRoute({ component: () => <Outlet /> })
2930
const indexRoute = createRoute({
3031
getParentRoute: () => rootRoute,
3132
path: '/',
3233
component: () => <div data-testid="home">Home</div>,
3334
})
35+
const aboutRoute = createRoute({
36+
getParentRoute: () => rootRoute,
37+
path: '/about',
38+
validateSearch: z.object({ tab: z.string().default('info') }),
39+
component: () => <div data-testid="about">About</div>,
40+
})
3441
const userRoute = createRoute({
3542
getParentRoute: () => rootRoute,
3643
path: '/users/$id',
@@ -43,10 +50,24 @@ function makeRouter(loaderMs: number) {
4350
return <div data-testid="user">{data().name}</div>
4451
},
4552
})
46-
const routeTree = rootRoute.addChildren([indexRoute, userRoute])
53+
const postRoute = createRoute({
54+
getParentRoute: () => rootRoute,
55+
path: '/posts/$postId',
56+
params: {
57+
parse: ({ postId }) => ({ postId: Number(postId) }),
58+
stringify: ({ postId }) => ({ postId: String(postId) }),
59+
},
60+
component: () => <div data-testid="post">Post</div>,
61+
})
62+
const routeTree = rootRoute.addChildren([
63+
indexRoute,
64+
aboutRoute,
65+
userRoute,
66+
postRoute,
67+
])
4768
return createRouter({
4869
routeTree,
49-
history: createMemoryHistory({ initialEntries: ['/'] }),
70+
history: createMemoryHistory({ initialEntries: [initialEntry] }),
5071
})
5172
}
5273

@@ -100,3 +121,37 @@ test('a navigation superseded before it published leaves one record for the dest
100121
// Dated from the first request: that is when the user started waiting.
101122
expect(navs[0]!.at).toBeLessThan(requested + 5)
102123
})
124+
125+
test('a not-found is named by its pathname, not by the route above it', async () => {
126+
const router = makeRouter(0)
127+
render(() => <RouterProvider router={router} />)
128+
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
129+
130+
// Nothing matches; and a path that runs past `/about`, which only matches
131+
// fuzzily (the not-found renders under it).
132+
await router.navigate({ to: '/nope/deeper' as any })
133+
await sleep(10)
134+
await router.navigate({ to: '/about/nope' as any })
135+
await sleep(10)
136+
137+
const navs = attribution.history('navigation')
138+
expect(navs.map((nav) => [nav.name, nav.params])).toEqual([
139+
['/nope/deeper', undefined],
140+
['/about/nope', undefined],
141+
])
142+
})
143+
144+
test('params are the strings the path bound, before `params.parse`', async () => {
145+
const router = makeRouter(0)
146+
render(() => <RouterProvider router={router} />)
147+
await waitFor(() => expect(screen.getByTestId('home')).toBeTruthy())
148+
149+
await router.navigate({ to: '/posts/$postId', params: { postId: 5 } })
150+
await waitFor(() => expect(screen.getByTestId('post')).toBeTruthy())
151+
await sleep(0)
152+
153+
expect(attribution.history('navigation')[0]!.name).toBe('/posts/$postId')
154+
expect(attribution.history('navigation')[0]!.params).toEqual({
155+
postId: '5',
156+
})
157+
})

0 commit comments

Comments
 (0)