diff --git a/benchmarks/client-nav/react/app.tsx b/benchmarks/client-nav/react/app.tsx index cad766e26c..5889ce0c46 100644 --- a/benchmarks/client-nav/react/app.tsx +++ b/benchmarks/client-nav/react/app.tsx @@ -34,6 +34,7 @@ const noop = () => {} const rootSelectors = Array.from({ length: 10 }, (_, index) => index) const routeSelectors = Array.from({ length: 6 }, (_, index) => index) const linkGroups = Array.from({ length: 4 }, (_, index) => index) +const staticContextLinkIds = Array.from({ length: 8 }, (_, index) => index) function RootParamsSubscriber() { const params = useParams({ @@ -99,7 +100,10 @@ function LinkPanel() { data-testid={groupIndex === 0 ? 'go-ctx' : undefined} to="/ctx/$id" params={{ id: ctxId }} - search={true} + search={(prev: Record) => ({ + ...prev, + noise: '0', + })} replace activeOptions={{ includeSearch: false }} > @@ -128,6 +132,43 @@ function LinkPanel() { ) } +function StaticContextLinkPanel() { + return ( + <> + {staticContextLinkIds.map((linkId) => ( +
+ + {`Context search ${linkId}`} + + + {`Context search ignore ${linkId}`} + + + {`Context search exact ${linkId}`} + +
+ ))} + + ) +} + function Root() { return ( <> @@ -138,6 +179,7 @@ function Root() { ))} + ) diff --git a/benchmarks/client-nav/react/setup.ts b/benchmarks/client-nav/react/setup.ts index c637baf570..a18daffb43 100644 --- a/benchmarks/client-nav/react/setup.ts +++ b/benchmarks/client-nav/react/setup.ts @@ -79,7 +79,8 @@ export function setup() { () => navigate({ to: '/ctx/$id', - params: { id: 2 }, + params: { id: 1 }, + search: { page: 1, filter: 'all', noise: '1' }, replace: true, }), () => click('go-items-2', cachedLinks), diff --git a/link-performance-investigation.md b/link-performance-investigation.md new file mode 100644 index 0000000000..e448986476 --- /dev/null +++ b/link-performance-investigation.md @@ -0,0 +1,280 @@ +# Link Performance Investigation + +Date: 2026-03-20 + +## Goal + +Investigate how to reduce unnecessary `Link` work when the current router location changes, especially when `location.search` changes but a link's next location does not actually depend on current search. + +The main target is React, because React `Link` rerenders are the expensive case. Solid and Vue still matter for avoiding wasted `buildLocation` calls, but rerender pressure is much lower there. + +## What I Read + +- Adapter `Link` implementations: + - `packages/react-router/src/link.tsx` + - `packages/solid-router/src/link.tsx` + - `packages/vue-router/src/link.tsx` +- Router-core location building and matching: + - `packages/router-core/src/router.ts` + - `packages/router-core/src/location.ts` + - `packages/router-core/src/path.ts` + - `packages/router-core/src/RouterProvider.ts` +- React location update lifecycle: + - `packages/react-router/src/Transitioner.tsx` +- Existing and new benchmarks: + - `benchmarks/client-nav/react/app.tsx` + - `benchmarks/client-nav/react/setup.ts` + - `benchmarks/client-nav/react/speed.bench.ts` + +## What We Know + +- `buildLocation` is expensive. +- The old `Link` behavior rebuilt `next` whenever the full current location changed. +- Many links do not need current `location.search` to compute `next`. +- Most users do not set `activeOptions={{ includeSearch: false }}`. +- For the common default `includeSearch: true` case, skipping `buildLocation` can still help even if React still rerenders to recompute `isActive`. + +## Lifecycle: History -> Router -> Link -> buildLocation + +1. Browser/history location changes. +2. React `Transitioner` subscribes history to `router.load()`. +3. `router.beforeLoad()` updates `router.stores.location` early, before all route loading finishes. +4. Every `Link` that subscribes to `router.stores.location` gets that update. +5. If a `Link` decides the new location matters, React rerenders the component. +6. During render, `Link` calls `router.buildLocation(...)` to compute `next`. +7. `buildLocation` does all of the following: + - resolves the current route context from the current location + - computes `from` / `to` + - resolves and stringifies params + - matches destination routes + - applies search middleware / legacy search filters / validateSearch + - computes hash, state, href, publicHref, and masked location +8. `Link` then computes `href` and `isActive` from the current location and the built `next` location. + +## How `location`, `buildLocation`, and `Link` Fit Together + +- `router.stores.location` is the reactive trigger. +- `Link` is the consumer that decides whether a location update matters. +- `buildLocation` is the expensive derivation step used to compute `next`. +- The key optimization problem is not only "what does a link depend on?". +- The real problem is "how do we know the dependency set without spending enough work to cancel out the win?". + +## Attempt 1: Adapter-Local Dependency Analysis in React/Solid/Vue + +### Shape + +- Split each adapter into two subscriptions: + - one for `next` / `buildLocation` + - one for `isActive` +- Add adapter-local helper logic to infer whether current pathname/search/hash/state matter. +- Duplicate route matching logic in each adapter to decide whether current search matters because of destination search middleware. + +### What Worked + +- Narrow tests passed. +- Search-only changes could skip `buildLocation` for static-search links. + +### What Failed + +- Too much duplicated code across adapters. +- Bundle size increased noticeably. +- The existing mixed client-nav benchmark did not improve. +- React became slightly slower in the broad benchmark. + +### Conclusion + +This approach was the wrong abstraction boundary. It moved expensive reasoning into adapter space and duplicated route analysis three times. + +## Attempt 2: React-Only Single Subscription + Core Dependency Metadata + +### Shape + +- Revert Solid and Vue back to the simpler baseline behavior. +- Keep React-focused optimization only. +- Add an internal `_collectLocationDeps` option to `buildLocation`. +- While `buildLocation` is already resolving the destination route branch, compute a tiny dependency bitmask for the fields that matter: + - pathname / current route context + - search + - hash + - state +- In React `Link`: + - keep a single `useStore` subscription to `router.stores.location` + - cache the previous built `next` location plus the dependency bitmask + - rebuild only when a location change intersects the cached dependency bitmask + - still rerender when active-state inputs change, but reuse cached `next` + +### Why This Is Better + +- No duplicated route matching in adapter code. +- Only one React store subscription. +- Search dependency is determined from the same work `buildLocation` already does. +- The common default case can still skip `buildLocation` even when `isActive` must be recomputed. + +## Important Correctness Fix During Investigation + +While rerunning affected unit tests, `packages/react-router/tests/link.test.tsx` surfaced a regression in the existing test: + +- `keeps a relative link active when changing inherited params (issue #5655)` + +Cause: + +- The first dependency-mask version missed the fact that omitted `params` still inherit current params when `nextTo` contains path params. + +Fix: + +- Mark pathname as a dependency when params are inherited/merged and the resolved `nextTo` path template contains `$` params. + +## What Is Currently In Code + +- React-only optimization: + - `packages/react-router/src/link.tsx` +- Core dependency metadata support: + - `packages/router-core/src/router.ts` + - `packages/router-core/src/RouterProvider.ts` +- New React benchmark scenario: + - `benchmarks/client-nav/react/app.tsx` + - `benchmarks/client-nav/react/setup.ts` + - `benchmarks/client-nav/react/speed.bench.ts` +- React tests: + - `packages/react-router/tests/link.test.tsx` + +Solid and Vue were intentionally restored to the baseline implementation for now. + +## Benchmark Design + +### Existing Benchmark + +The original `client-nav` benchmark changes pathname every navigation and changes search every other navigation. That is a broad benchmark, but it does not isolate the search-only optimization target. + +### New Benchmark + +Added a second React scenario: `client-side navigation loop with static search links (react)`. + +Shape: + +- Stable pathname: `/links` +- Current search changes every tick +- 200 rendered `Link`s +- Each `Link` has static `search={{ linkId: ... }}` + +This isolates the intended search-only invalidation case. + +## Benchmarks I Ran + +### Validation / Build Commands + +- `CI=1 NX_DAEMON=false pnpm nx run @tanstack/react-router:test:eslint --outputStyle=stream --skipRemoteCache` +- `CI=1 NX_DAEMON=false pnpm nx affected --target=test:eslint --exclude=examples/**,e2e/** --outputStyle=stream --skipRemoteCache` +- `CI=1 NX_DAEMON=false pnpm nx affected --target=test:types --exclude=examples/** --outputStyle=stream --skipRemoteCache` +- `CI=1 NX_DAEMON=false pnpm nx affected --target=test:unit --exclude=examples/**,e2e/** --outputStyle=stream --skipRemoteCache` +- `CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:react --outputStyle=stream --skipRemoteCache` +- `CI=1 NX_DAEMON=false pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache` + +### Focused React Tests + +- `CI=1 NX_DAEMON=false pnpm nx run @tanstack/react-router:test:unit --outputStyle=stream --skipRemoteCache -- tests/link.test.tsx -t "does not rebuild static next locations on unrelated search changes"` +- `CI=1 NX_DAEMON=false pnpm nx run @tanstack/react-router:test:unit --outputStyle=stream --skipRemoteCache -- tests/link.test.tsx -t "keeps a relative link active when changing inherited params \(issue #5655\)"` + +### Main Comparison Method + +- Created a temporary detached worktree at `origin/main` +- Installed deps there +- Ran the same React benchmarks on `main` +- Compared current branch vs `main` + +## Measurements + +### Mixed React client-nav benchmark + +Current implementation vs `main`: + +- `main`: `38.78 hz`, mean `25.79 ms` +- current: `36.33 hz`, mean `27.53 ms` +- Result: still slightly worse in the broad benchmark (`-6.3%` throughput in the latest run) + +Interpretation: + +- The mixed benchmark is still dominated by cases where pathname changes and links legitimately need work. +- The new optimization does not materially help this broad scenario yet. + +### Search-only benchmark, with `activeOptions={{ includeSearch: false }}` + +Current implementation vs `main`: + +- `main`: `16.42 hz`, mean `60.92 ms` +- current: `27.03 hz`, mean `37.00 ms` +- Result: `+64.7%` throughput, `-39.3%` mean time + +Interpretation: + +- This is the ideal case: current search changes do not matter to `next` or `isActive`. +- The optimization skips both `buildLocation` and React rerender work. + +### Search-only benchmark, default `includeSearch: true` + +Follow-up work narrowed active-search dependency tracking for static-search links so React no longer subscribes to the full current search object in the common partial-match case. + +The active-state dependency now distinguishes: + +- no current-search dependency +- selected current-search keys only +- selected current-search keys plus exact current-search entry count + +That means common links such as `search={{ page: 0 }}` with default `includeSearch: true` only react to current `page`, not unrelated current search keys. + +Current implementation vs `main`: + +- `main`: `14.46 hz`, mean `69.16 ms` +- current: `20.28 hz`, mean `49.31 ms` +- Result: `+40.2%` throughput, `-28.7%` mean time + +Interpretation: + +- The default `includeSearch: true` case now benefits much more because React can skip rerenders when unrelated current search keys change. +- React still rerenders when the selected search keys or exact-search key count can affect `isActive`. +- The remaining work is now much closer to the true semantic dependency of active-state matching. + +### Bundle size + +Current implementation vs `main`: + +- `react-router.minimal`: `90682 -> 91531 gzip` (`+849 B`, `+0.94%`) +- `react-router.full`: `93928 -> 94779 gzip` (`+851 B`, `+0.91%`) + +Interpretation: + +- The core-assisted React-only approach is still larger than `main`, but much better than the original three-adapter duplicated approach. +- Replacing the hidden dependency metadata property with an internal `_locationDeps` target simplified the implementation, but it did not materially reduce the emitted React bundle on its own. + +## What Worked + +- Moving dependency analysis into `buildLocation` instead of duplicating route matching in adapters. +- Returning a tiny internal dependency mask instead of a large metadata object. +- Using one React store subscription and cached built locations. +- Adding a search-only benchmark that actually measures the intended optimization target. + +## What Did Not Work + +- Per-adapter duplicated dependency analysis. +- Two subscriptions per `Link` in all adapters. +- Expecting the broad mixed client-nav benchmark to show the targeted search-only win. + +## Current Understanding + +- The optimization target is real. +- The common-case default `includeSearch: true` can benefit substantially when a static-search link only depends on a small subset of current search keys. +- The biggest win appears when search changes affect neither `next` nor `isActive`. +- The current mixed benchmark suggests there is still a larger amount of unavoidable pathname-driven work in the general case. + +## Open Questions / Next Steps + +1. Can the remaining React/client-nav regression be explained by unavoidable pathname work, or is there still avoidable `Link` overhead in the mixed benchmark? +2. Can the dependency metadata be compressed further without giving up the selected-key / key-count active-search win? +3. Should the same core-assisted pattern eventually be extended to Solid and Vue, or is React the only adapter worth optimizing at this level? + +## Practical Status + +- React-only optimization is implemented and benchmarked. +- Narrow correctness regressions are covered by tests. +- Affected eslint, affected type tests, and affected unit tests pass. +- A draft PR is appropriate because the targeted benchmark win is strong, but the broad benchmark remains flat/slightly worse and the bundle is still somewhat larger than `main`. diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index 3f0dc83a22..558a880e11 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -19,6 +19,7 @@ import type { AnyRouter, Constrain, LinkOptions, + ParsedLocation, RegisteredRouter, RoutePaths, } from '@tanstack/router-core' @@ -395,6 +396,15 @@ export function useLinkProps< ], ) + // eslint-disable-next-line react-hooks/rules-of-hooks + const buildLocationRef = React.useRef(null) + + // eslint-disable-next-line react-hooks/rules-of-hooks + const shouldReuseBuildLocation = React.useMemo( + () => canReuseBuildLocation(_options), + [_options], + ) + // eslint-disable-next-line react-hooks/rules-of-hooks const currentLocation = useStore( router.stores.location, @@ -403,10 +413,51 @@ export function useLinkProps< ) // eslint-disable-next-line react-hooks/rules-of-hooks - const next = React.useMemo(() => { - const opts = { _fromLocation: currentLocation, ..._options } - return router.buildLocation(opts as any) - }, [router, currentLocation, _options]) + const buildLocation = React.useMemo(() => { + const previousBuildLocation = buildLocationRef.current + + if ( + shouldReuseBuildLocation && + previousBuildLocation?.options === _options && + !didLocationChange( + previousBuildLocation.location, + currentLocation, + previousBuildLocation.deps, + ) + ) { + return previousBuildLocation + } + + const shouldCollectLocationDeps = + shouldReuseBuildLocation && + !( + (previousBuildLocation?.deps ?? BUILD_LOCATION_DEP_NONE) & + (BUILD_LOCATION_DEP_PATHNAME | BUILD_LOCATION_DEP_SEARCH) + ) + + const locationDeps = shouldCollectLocationDeps + ? { value: BUILD_LOCATION_DEP_ALL } + : undefined + + const next = router.buildLocation({ + ...(locationDeps ? { _locationDeps: locationDeps } : null), + _fromLocation: currentLocation, + ..._options, + } as any) + + const result = { + location: currentLocation, + next, + deps: _options._fromLocation + ? BUILD_LOCATION_DEP_NONE + : (locationDeps?.value ?? BUILD_LOCATION_DEP_ALL), + options: _options, + } + buildLocationRef.current = result + return result + }, [router, currentLocation, _options, shouldReuseBuildLocation]) + + const next = buildLocation.next // Use publicHref - it contains the correct href for display // When a rewrite changes the origin, publicHref is the full URL @@ -725,6 +776,20 @@ const intersectionObserverOptions: IntersectionObserverInit = { rootMargin: '100px', } +type BuildLocationState = { + location: ParsedLocation + next: ParsedLocation + deps: number + options: unknown +} + +const BUILD_LOCATION_DEP_NONE = 0 +const BUILD_LOCATION_DEP_PATHNAME = 1 +const BUILD_LOCATION_DEP_SEARCH = 2 +const BUILD_LOCATION_DEP_HASH = 4 +const BUILD_LOCATION_DEP_STATE = 8 +const BUILD_LOCATION_DEP_ALL = 15 + const composeHandlers = (handlers: Array>) => (e: React.SyntheticEvent) => { @@ -759,6 +824,52 @@ function isSafeInternal(to: unknown) { return zero === 46 // '.', '..', './', '../' } +function didLocationChange( + prev: ParsedLocation, + next: ParsedLocation, + deps: number, +) { + return !!( + (deps & BUILD_LOCATION_DEP_PATHNAME && prev.pathname !== next.pathname) || + (deps & BUILD_LOCATION_DEP_SEARCH && prev.search !== next.search) || + (deps & BUILD_LOCATION_DEP_HASH && prev.hash !== next.hash) || + (deps & BUILD_LOCATION_DEP_STATE && prev.state !== next.state) + ) +} + +function canReuseBuildLocation(options: { + from?: unknown + hash?: unknown + mask?: unknown + params?: unknown + search?: unknown + state?: unknown + to?: unknown +}) { + if (options.mask) { + return false + } + + if ( + isInherit(options.search) || + isInherit(options.params) || + isInherit(options.hash) || + isInherit(options.state) + ) { + return false + } + + if (typeof options.to !== 'string') { + return false + } + + return options.to.charCodeAt(0) === 47 && options.to.charCodeAt(1) !== 47 +} + +function isInherit(p: unknown) { + return p === true || typeof p === 'function' +} + type UseLinkReactProps = TComp extends keyof React.JSX.IntrinsicElements ? React.JSX.IntrinsicElements[TComp] : TComp extends React.ComponentType diff --git a/packages/react-router/tests/link.test.tsx b/packages/react-router/tests/link.test.tsx index 26cd07d988..32e098774f 100644 --- a/packages/react-router/tests/link.test.tsx +++ b/packages/react-router/tests/link.test.tsx @@ -734,6 +734,218 @@ describe('Link', () => { expect(await screen.findByText('Posts 2')).toBeInTheDocument() }) + test('does not rebuild static next locations on unrelated search changes', async () => { + const history = createMemoryHistory({ initialEntries: ['/?page=0'] }) + + const rootRoute = createRootRoute({ + component: () => ( + + Static search + + ), + }) + + const router = createRouter({ + routeTree: rootRoute, + history, + }) + + const buildLocationSpy = vi.spyOn(router, 'buildLocation') + + render() + + const staticSearch = await screen.findByTestId('static-search') + + expect(staticSearch).toHaveClass('active') + + buildLocationSpy.mockClear() + + await act(async () => { + history.push('/?page=1') + }) + + await waitFor(() => { + expect(staticSearch).toHaveClass('inactive') + }) + + expect(buildLocationSpy).not.toHaveBeenCalled() + }) + + test('does not rerender when search changes do not affect next or active state', async () => { + const history = createMemoryHistory({ initialEntries: ['/?page=0'] }) + let renderCount = 0 + + function StaticSearchLink() { + renderCount++ + + return ( + + Static search + + ) + } + + const rootRoute = createRootRoute({ + component: () => , + }) + + const router = createRouter({ + routeTree: rootRoute, + history, + }) + + const buildLocationSpy = vi.spyOn(router, 'buildLocation') + + render() + + const staticSearch = await screen.findByTestId('static-search') + const initialRenderCount = renderCount + + expect(staticSearch).toHaveClass('active') + + buildLocationSpy.mockClear() + + await act(async () => { + history.push('/?page=1') + }) + + await waitFor(() => { + expect(router.state.location.search).toEqual({ page: 1 }) + }) + + expect(staticSearch).toHaveClass('active') + expect(renderCount).toBe(initialRenderCount) + expect(buildLocationSpy).not.toHaveBeenCalled() + }) + + test('does not rerender when unrelated search keys change for partial active search', async () => { + const history = createMemoryHistory({ + initialEntries: ['/?page=0&filter=first'], + }) + let renderCount = 0 + + function StaticSearchLink() { + renderCount++ + + return ( + + Static search + + ) + } + + const rootRoute = createRootRoute({ + component: () => , + }) + + const router = createRouter({ + routeTree: rootRoute, + history, + }) + + const buildLocationSpy = vi.spyOn(router, 'buildLocation') + + render() + + const staticSearch = await screen.findByTestId('static-search') + const initialRenderCount = renderCount + + expect(staticSearch).toHaveClass('active') + + buildLocationSpy.mockClear() + + await act(async () => { + history.push('/?page=0&filter=second') + }) + + await waitFor(() => { + expect(router.state.location.search).toEqual({ + filter: 'second', + page: 0, + }) + }) + + expect(staticSearch).toHaveClass('active') + expect(renderCount).toBe(initialRenderCount) + expect(buildLocationSpy).not.toHaveBeenCalled() + }) + + test('does not rerender when exact active search keeps the same key count', async () => { + const history = createMemoryHistory({ + initialEntries: ['/?page=0&filter=first'], + }) + let renderCount = 0 + + function StaticSearchLink() { + renderCount++ + + return ( + + Static search + + ) + } + + const rootRoute = createRootRoute({ + component: () => , + }) + + const router = createRouter({ + routeTree: rootRoute, + history, + }) + + const buildLocationSpy = vi.spyOn(router, 'buildLocation') + + render() + + const staticSearch = await screen.findByTestId('static-search') + const initialRenderCount = renderCount + + expect(staticSearch).toHaveClass('inactive') + + buildLocationSpy.mockClear() + + await act(async () => { + history.push('/?page=0&filter=second') + }) + + await waitFor(() => { + expect(router.state.location.search).toEqual({ + filter: 'second', + page: 0, + }) + }) + + expect(staticSearch).toHaveClass('inactive') + expect(renderCount).toBe(initialRenderCount) + expect(buildLocationSpy).not.toHaveBeenCalled() + }) + test('updates hash-sensitive active state immediately with and without hash=true', async () => { const rootRoute = createRootRoute({ component: () => ( diff --git a/packages/router-core/src/RouterProvider.ts b/packages/router-core/src/RouterProvider.ts index 52aeaffabb..2f6723c880 100644 --- a/packages/router-core/src/RouterProvider.ts +++ b/packages/router-core/src/RouterProvider.ts @@ -42,6 +42,7 @@ export type BuildLocationFn = < opts: ToOptions & { leaveParams?: boolean _includeValidateSearch?: boolean + _locationDeps?: { value: number } _isNavigate?: boolean }, ) => ParsedLocation diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index 965fefda33..9ee884d9fb 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -564,10 +564,17 @@ export interface BuildNextOptions { from?: string href?: string _fromLocation?: ParsedLocation + _locationDeps?: { value: number } unsafeRelative?: 'path' _isNavigate?: boolean } +const BUILD_LOCATION_DEP_NONE = 0 +const BUILD_LOCATION_DEP_PATHNAME = 1 +const BUILD_LOCATION_DEP_SEARCH = 2 +const BUILD_LOCATION_DEP_HASH = 4 +const BUILD_LOCATION_DEP_STATE = 8 + type NavigationEventInfo = { fromLocation?: ParsedLocation toLocation: ParsedLocation @@ -1682,7 +1689,6 @@ export class RouterCore< private matchRoutesLightweight(location: ParsedLocation): { matchedRoutes: ReadonlyArray fullPath: string - search: Record params: Record } { const { matchedRoutes, routeParams, parsedParams } = this.getMatchedRoutes( @@ -1690,28 +1696,6 @@ export class RouterCore< ) const lastRoute = last(matchedRoutes)! - // I don't know if we should run the full search middleware chain, or just validateSearch - // // Accumulate search validation through the route chain - // const accumulatedSearch: Record = applySearchMiddleware({ - // search: { ...location.search }, - // dest: location, - // destRoutes: matchedRoutes, - // _includeValidateSearch: true, - // }) - - // Accumulate search validation through route chain - const accumulatedSearch = { ...location.search } - for (const route of matchedRoutes) { - try { - Object.assign( - accumulatedSearch, - validateSearch(route.options.validateSearch, accumulatedSearch), - ) - } catch { - // Ignore errors, we're not actually routing - } - } - // Determine params: reuse from state if possible, otherwise parse const lastStateMatchId = last(this.stores.matchesId.state) const lastStateMatch = @@ -1749,7 +1733,6 @@ export class RouterCore< return { matchedRoutes, fullPath: lastRoute.fullPath, - search: accumulatedSearch, params, } } @@ -1793,6 +1776,9 @@ export class RouterCore< * @link https://tanstack.com/router/latest/docs/framework/react/api/router/RouterType#buildlocation-method */ buildLocation: BuildLocationFn = (opts) => { + const locationDepsTarget = opts._locationDeps + let collectedLocationDeps = BUILD_LOCATION_DEP_NONE + const build = ( dest: BuildNextOptions & { unmaskOnReload?: boolean @@ -1802,6 +1788,25 @@ export class RouterCore< const currentLocation = dest._fromLocation || this.pendingBuiltLocation || this.latestLocation + let locationDeps = BUILD_LOCATION_DEP_NONE + + if (locationDepsTarget) { + const toPath = dest.to == null ? undefined : `${dest.to}` + const toIsAbsolute = + !!toPath && toPath.charCodeAt(0) === 47 && toPath.charCodeAt(1) !== 47 + if (!dest.from && (!toPath || !toIsAbsolute)) { + locationDeps |= BUILD_LOCATION_DEP_PATHNAME + } + + if (dest.hash === true || typeof dest.hash === 'function') { + locationDeps |= BUILD_LOCATION_DEP_HASH + } + + if (dest.state === true || typeof dest.state === 'function') { + locationDeps |= BUILD_LOCATION_DEP_STATE + } + } + // Use lightweight matching - only computes what buildLocation needs // (fullPath, search, params) without creating full match objects const lightweightResult = this.matchRoutesLightweight(currentLocation) @@ -1839,7 +1844,7 @@ export class RouterCore< const fromPath = this.resolvePathWithBase(defaultedFromPath, '.') // From search should always use the current location - const fromSearch = lightweightResult.search + const fromSearch = currentLocation.search // Same with params. It can't hurt to provide as many as possible const fromParams = Object.assign( Object.create(null), @@ -1852,6 +1857,13 @@ export class RouterCore< ? this.resolvePathWithBase(fromPath, `${dest.to}`) : this.resolvePathWithBase(fromPath, '.') + if ( + locationDepsTarget && + pathRequiresCurrentParams(nextTo, dest.params) + ) { + locationDeps |= BUILD_LOCATION_DEP_PATHNAME + } + // Resolve the next params const nextParams = dest.params === false || dest.params === null @@ -1879,6 +1891,20 @@ export class RouterCore< destRoutes = [...destRoutes, this.options.notFoundRoute] } + if ( + locationDepsTarget && + (dest.search === true || + typeof dest.search === 'function' || + destRoutes.some((route) => + routeNeedsCurrentSearch( + route, + opts._includeValidateSearch ?? false, + ), + )) + ) { + locationDeps |= BUILD_LOCATION_DEP_SEARCH + } + // If there are any params, we need to stringify them if (Object.keys(nextParams).length > 0) { for (const route of destRoutes) { @@ -1999,7 +2025,7 @@ export class RouterCore< publicHref = href } - return { + const nextLocation = { publicHref, href, pathname: nextPathname, @@ -2010,6 +2036,12 @@ export class RouterCore< external, unmaskOnReload: dest.unmaskOnReload, } + + if (locationDepsTarget) { + collectedLocationDeps |= locationDeps + } + + return nextLocation } const buildWithMatches = ( @@ -2063,13 +2095,23 @@ export class RouterCore< } if (opts.mask) { - return buildWithMatches(opts, { + const next = buildWithMatches(opts, { from: opts.from, ...opts.mask, }) + if (locationDepsTarget) { + locationDepsTarget.value = collectedLocationDeps + } + return next } - return buildWithMatches(opts) + const next = buildWithMatches(opts) + + if (locationDepsTarget) { + locationDepsTarget.value = collectedLocationDeps + } + + return next } commitLocationPromise: undefined | ControlledPromise @@ -3058,6 +3100,22 @@ function applySearchMiddleware({ return middleware(search, dest, _includeValidateSearch ?? false) } +function routeNeedsCurrentSearch( + route: AnyRoute, + includeValidateSearch: boolean, +) { + return !!( + route.options.search?.middlewares?.length || + route.options.preSearchFilters?.length || + route.options.postSearchFilters?.length || + (includeValidateSearch && route.options.validateSearch) + ) +} + +function pathRequiresCurrentParams(nextTo: string, params: unknown) { + return params !== false && nextTo.includes('$') +} + function buildMiddlewareChain(destRoutes: ReadonlyArray) { const context = { dest: null as unknown as BuildNextOptions,