diff --git a/.changeset/open-onions-jog.md b/.changeset/open-onions-jog.md new file mode 100644 index 0000000000..15f98eb90a --- /dev/null +++ b/.changeset/open-onions-jog.md @@ -0,0 +1,6 @@ +--- +'@tanstack/router-core': patch +'@tanstack/react-router': patch +--- + +Reuse mounted React link pathnames while their resolved route template and parameter values are unchanged, including optional, inherited and splat parameters. Preserve parameter callbacks, search middleware, URL rewrites, serializers, hash and state updates. diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index a0d6968986..ed7746d733 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -20,6 +20,7 @@ import { useHydrated } from './ClientOnly' import type { ActiveOptions, AnyRouter, + BuildLocationCache, Constrain, LinkOptions, ParsedLocation, @@ -496,6 +497,8 @@ export function useLinkProps< // eslint-disable-next-line react-hooks/rules-of-hooks const stableActiveOptions = useValueStable(activeOptions) // eslint-disable-next-line react-hooks/rules-of-hooks + const buildCache = React.useMemo(() => ({}), []) + // eslint-disable-next-line react-hooks/rules-of-hooks const _options = React.useMemo( () => options, // eslint-disable-next-line react-hooks/exhaustive-deps @@ -521,6 +524,7 @@ export function useLinkProps< (location: ParsedLocation): LinkState => { const next = router.buildLocation({ _fromLocation: location, + _buildCache: buildCache, ..._options, } as any) @@ -554,7 +558,15 @@ export function useLinkProps< ), ] }, - [stableActiveOptions, disabled, isHydrated, _options, router, to], + [ + stableActiveOptions, + disabled, + isHydrated, + _options, + router, + to, + buildCache, + ], ) // eslint-disable-next-line react-hooks/rules-of-hooks diff --git a/packages/react-router/tests/link-build-cache.test.tsx b/packages/react-router/tests/link-build-cache.test.tsx new file mode 100644 index 0000000000..477431e567 --- /dev/null +++ b/packages/react-router/tests/link-build-cache.test.tsx @@ -0,0 +1,359 @@ +import React from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { + act, + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { + Link, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + retainSearchParams, +} from '../src' +import type { AnyRouter } from '../src' + +afterEach(cleanup) + +function setup(links: () => React.ReactNode) { + const root = createRootRoute({ + component: () => ( + <> + + + + ), + }) + const index = createRoute({ getParentRoute: () => root, path: '/' }) + const item = createRoute({ getParentRoute: () => root, path: '/items/$id' }) + const optional = createRoute({ + getParentRoute: () => root, + path: '/optional/{-$id}', + }) + const router = createRouter({ + routeTree: root.addChildren([index, item, optional]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + const build = router.buildLocation + let hits = 0 + vi.spyOn(router, 'buildLocation').mockImplementation((options) => { + const cache = (options as { _buildCache?: { value?: unknown } })._buildCache + const entry = cache?.value + const result = build(options) + if (entry && entry === cache?.value) { + hits++ + } + return result + }) + return { router, item, hits: () => hits } +} + +async function mount(router: AnyRouter) { + await act(async () => { + render() + await router.load() + }) +} + +function href() { + return screen.getByTestId('link').getAttribute('href') +} + +test('a cached destination keeps its href while active state follows navigation', async () => { + const { router, hits } = setup(() => ( + + item + + )) + await mount(router) + const before = hits() + expect(href()).toBe('/items/9') + expect(screen.getByTestId('link').className).not.toContain('active') + await act(() => router.navigate({ to: '/items/$id', params: { id: '9' } })) + expect(hits()).toBeGreaterThan(before) + expect(href()).toBe('/items/9') + expect(screen.getByTestId('link').className).toContain('active') + await act(() => router.navigate({ to: '/' })) + expect(screen.getByTestId('link').className).not.toContain('active') +}) + +test('changed link options discard the previous cache', async () => { + function Links() { + const [id, setId] = React.useState('1') + return ( + <> + + + item + + + ) + } + const { router, hits } = setup(() => ) + await mount(router) + await act(() => router.navigate({ to: '/items/$id', params: { id: '9' } })) + expect(hits()).toBeGreaterThan(0) + expect(href()).toBe('/items/1?tab=1#1') + fireEvent.click(screen.getByText('change')) + expect(href()).toBe('/items/2?tab=2#2') +}) + +test('cache hits still apply changed locale rewrites', async () => { + const { router, hits } = setup(() => ( + + item + + )) + let locale = 'en' + router.update({ + rewrite: { + input: ({ url }) => { + url.pathname = url.pathname.replace(/^\/(en|fr)(?=\/|$)/, '') || '/' + return url + }, + output: ({ url }) => { + url.pathname = `/${locale}${url.pathname}` + return url + }, + }, + }) + await mount(router) + expect(href()).toBe('/en/items/9') + const before = hits() + locale = 'fr' + await act(() => router.navigate({ to: '/items/$id', params: { id: '2' } })) + expect(hits()).toBeGreaterThan(before) + expect(href()).toBe('/fr/items/9') +}) + +test('an absent optional param is inherited after navigation', async () => { + const { router } = setup(() => ( + + optional + + )) + await mount(router) + expect(href()).toBe('/optional') + await act(() => router.navigate({ to: '/items/$id', params: { id: '2' } })) + expect(href()).toBe('/optional/2') +}) + +test('route.update can add middleware after the link has served cache hits', async () => { + const { router, item, hits } = setup(() => ( + + item + + )) + await mount(router) + await act(() => router.navigate({ to: '/items/$id', params: { id: '2' } })) + expect(hits()).toBeGreaterThan(0) + item.update({ search: { middlewares: [retainSearchParams(true)] } }) + await act(() => router.navigate({ to: '/', search: { tab: 'new' } } as any)) + expect(href()).toBe('/items/9?tab=new') +}) + +test('clicking a cached link still validates search during navigation', async () => { + const { router, item, hits } = setup(() => ( + + item + + )) + item.update({ + validateSearch: (search: Record) => ({ + page: Number(search.page ?? 1), + }), + } as any) + await mount(router) + await act(() => router.navigate({ to: '/items/$id', params: { id: '2' } })) + expect(hits()).toBeGreaterThan(0) + expect(href()).toBe('/items/9') + await act(async () => { + fireEvent.click(screen.getByTestId('link')) + }) + expect(router.state.location.href).toBe('/items/9?page=1') +}) + +test('intent preloading validates search after cache hits', async () => { + const { router, item, hits } = setup(() => ( + + item + + )) + const loader = vi.fn(() => null) + item.update({ + validateSearch: (search: Record) => ({ + page: Number(search.page ?? 1), + }), + loaderDeps: ({ search }: any) => ({ page: search.page }), + loader, + } as any) + const preload = vi.spyOn(router, 'preloadRoute') + await mount(router) + await act(() => router.navigate({ to: '/items/$id', params: { id: '2' } })) + expect(hits()).toBeGreaterThan(0) + loader.mockClear() + fireEvent.focus(screen.getByTestId('link')) + await waitFor(() => expect(loader).toHaveBeenCalled()) + expect(preload.mock.calls[0]![0]).not.toHaveProperty('_buildCache') + expect(loader).toHaveBeenCalledWith( + expect.objectContaining({ deps: { page: 1 }, params: { id: '9' } }), + ) +}) + +test('hash-only navigation updates href and active state on cache hits', async () => { + const { router, hits } = setup(() => ( + <> + + inherited + + + fixed + + + )) + await mount(router) + await act(() => + router.navigate({ to: '/items/$id', params: { id: '9' }, hash: 'one' }), + ) + expect(href()).toBe('/items/9#one') + expect(screen.getByTestId('fixed').className).toContain('active') + const before = hits() + await act(() => + router.navigate({ to: '/items/$id', params: { id: '9' }, hash: 'two' }), + ) + expect(hits()).toBeGreaterThan(before) + expect(href()).toBe('/items/9#two') + expect(screen.getByTestId('fixed').className).not.toContain('active') +}) + +test.each([ + ['supplied', { id: 'fixed' }, '/optional/fixed'], + ['absent', { id: undefined }, '/optional'], + ['inherited', {}, '/optional/1'], +] as const)( + 'an optional link with %s params hits on search-only changes', + async (_, params, expectedHref) => { + const { router, hits } = setup(() => ( + + optional + + )) + await router.navigate({ to: '/items/$id', params: { id: '1' } }) + await mount(router) + expect(href()).toBe(expectedHref) + const before = hits() + await act(() => + router.navigate({ + to: '/items/$id', + params: { id: '1' }, + search: { page: 2 }, + } as any), + ) + expect(href()).toBe(expectedHref) + expect(hits()).toBeGreaterThan(before) + }, +) + +test('search and hash prop changes preserve the pathname cache', async () => { + function Links() { + const [page, setPage] = React.useState(1) + return ( + <> + + + optional + + + ) + } + const { router, hits } = setup(() => ) + await mount(router) + expect(href()).toBe('/optional/fixed?page=1#section-1') + const before = hits() + fireEvent.click(screen.getByText('change search')) + expect(href()).toBe('/optional/fixed?page=2#section-2') + expect(hits()).toBeGreaterThan(before) +}) + +test('a suspended option transition cannot change the committed link pathname', async () => { + let release!: () => void + const pending = new Promise((resolve) => { + release = resolve + }) + let waiting = true + let suspended = false + function Suspend({ id }: { id: string }) { + if (id === '2' && waiting) { + suspended = true + throw pending + } + return null + } + function Links() { + const [id, setId] = React.useState('1') + return ( + <> + + loading}> + + optional + + + + + ) + } + const { router } = setup(() => ) + await mount(router) + expect(href()).toBe('/optional/1') + fireEvent.click(screen.getByText('transition')) + expect(suspended).toBe(true) + expect(href()).toBe('/optional/1') + await act(() => router.navigate({ to: '/items/$id', params: { id: '3' } })) + expect(href()).toBe('/optional/1') + await act(async () => { + waiting = false + release() + await pending + }) + expect(href()).toBe('/optional/2') +}) diff --git a/packages/router-core/src/RouterProvider.ts b/packages/router-core/src/RouterProvider.ts index 52aeaffabb..48d8c079ae 100644 --- a/packages/router-core/src/RouterProvider.ts +++ b/packages/router-core/src/RouterProvider.ts @@ -1,7 +1,11 @@ import type { NavigateOptions, ToOptions } from './link' import type { ParsedLocation } from './location' import type { RoutePaths } from './routeInfo' -import type { RegisteredRouter, ViewTransitionOptions } from './router' +import type { + BuildLocationCache, + RegisteredRouter, + ViewTransitionOptions, +} from './router' export interface MatchLocation { to?: string | number | null @@ -43,5 +47,7 @@ export type BuildLocationFn = < leaveParams?: boolean _includeValidateSearch?: boolean _isNavigate?: boolean + /** @internal */ + _buildCache?: BuildLocationCache }, ) => ParsedLocation diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index a296629ffa..003587d1e2 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -255,6 +255,7 @@ export type { RegisteredRouter, RouterState, BuildNextOptions, + BuildLocationCache, RouterListener, RouterEvent, ListenerFn, diff --git a/packages/router-core/src/path.ts b/packages/router-core/src/path.ts index d302ee13ab..1c96cda0e0 100644 --- a/packages/router-core/src/path.ts +++ b/packages/router-core/src/path.ts @@ -222,6 +222,8 @@ interface InterpolatePathOptions { * For testing only, in development mode we use the router.isServer value */ server?: boolean + /** @internal Track dependencies, including absent optionals, without aliases. */ + trackParams?: boolean } type InterPolatePathResult = { @@ -306,7 +308,9 @@ export function interpolatePath({ const splat = params._splat usedParams._splat = splat // TODO: Deprecate * - usedParams['*'] = splat + if (!rest.trackParams) { + usedParams['*'] = splat + } if (!splat) { isMissingParams = true @@ -360,7 +364,9 @@ export function interpolatePath({ const splat = params._splat usedParams._splat = splat // TODO: Deprecate * - usedParams['*'] = splat + if (!rest.trackParams) { + usedParams['*'] = splat + } const prefix = path.substring(start, segment[1]) const suffix = path.substring(segment[4], end) @@ -400,7 +406,12 @@ export function interpolatePath({ const valueRaw = params[key] // Check if optional parameter is missing or undefined - if (valueRaw == null) continue + if (valueRaw == null) { + if (rest.trackParams) { + usedParams[key] = valueRaw + } + continue + } usedParams[key] = valueRaw diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index fa4168b9ce..ea079152dc 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -576,6 +576,22 @@ export interface BuildNextOptions { _fromLocation?: ParsedLocation unsafeRelative?: 'path' _isNavigate?: boolean + /** @internal */ + _buildCache?: BuildLocationCache +} + +/** + * Caller-owned interpolation cache. Resolved parameter values, including + * absent optional ones, are dependencies. Parameter callbacks always run. + * @internal + */ +export interface BuildLocationCache { + value?: [ + template: string, + decoder: unknown, + params: Record, + pathname: string, + ] } type NavigationEventInfo = { @@ -1840,6 +1856,7 @@ export class RouterCore< dest: BuildNextOptions & { unmaskOnReload?: boolean } = {}, + cache?: BuildLocationCache, ): ParsedLocation => { if (dest.href) { const parsed = parseHref(dest.href, {} as ParsedHistoryState) @@ -1954,16 +1971,23 @@ export class RouterCore< } const nextPathname = opts.leaveParams - ? // Keep path params uninterpolated for matchRoute/template matching. - nextTo - : decodePath( - interpolatePath({ - path: nextTo, - params: nextParams, - decoder: this.pathParamsDecoder, - server: this.isServer, - }).interpolatedPath, - ).path + ? nextTo + : cache + ? getCachedPathname( + nextTo, + nextParams, + this.pathParamsDecoder, + this.isServer, + cache, + ) + : decodePath( + interpolatePath({ + path: nextTo, + params: nextParams, + decoder: this.pathParamsDecoder, + server: this.isServer, + }).interpolatedPath, + ).path if ( process.env.NODE_ENV !== 'production' && @@ -2086,7 +2110,7 @@ export class RouterCore< } } - const next = build(opts) + const next = build(opts, opts._buildCache) if (opts.mask) { next.maskedLocation = build({ @@ -2835,6 +2859,47 @@ function applySearchMiddleware( return applyNext(0, search) } +function getCachedPathname( + path: string, + params: Record, + decoder: Parameters[0]['decoder'], + server: boolean, + cache: BuildLocationCache, +) { + const entry = cache.value + if ( + entry && + entry[0 /* template */] === path && + entry[1 /* decoder */] === decoder && + equalPathParams(entry[2 /* params */], params) + ) { + return entry[3 /* pathname */] + } + const interpolated = interpolatePath({ + path, + params, + decoder, + server, + trackParams: true, + }) + const pathname = decodePath(interpolated.interpolatedPath).path + cache.value = [path, decoder, interpolated.usedParams, pathname] + return pathname +} + +// Params have already been resolved and passed through route stringifiers. +function equalPathParams( + previous: Record, + params: Record, +) { + for (const key in previous) { + if (previous[key] !== params[key]) { + return false + } + } + return true +} + function findGlobalNotFoundRouteId( notFoundMode: 'root' | 'fuzzy' | undefined, routes: ReadonlyArray, diff --git a/packages/router-core/tests/build-location-cache-regressions.test.ts b/packages/router-core/tests/build-location-cache-regressions.test.ts new file mode 100644 index 0000000000..a2460d2d37 --- /dev/null +++ b/packages/router-core/tests/build-location-cache-regressions.test.ts @@ -0,0 +1,439 @@ +import { expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, retainSearchParams } from '../src' +import { createTestRouter } from './routerTestUtils' + +function setup(stringify = false) { + const root = new BaseRootRoute({}) + const index = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const item = new BaseRoute({ getParentRoute: () => root, path: '/items/$id' }) + const optional = new BaseRoute({ + getParentRoute: () => root, + path: '/optional/{-$id}', + ...(stringify + ? { + params: { + stringify: (p: any) => ({ id: p.id ? `s${p.id}` : 'fallback' }), + }, + } + : {}), + }) + const router = createTestRouter({ + routeTree: root.addChildren([index, item, optional]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + return { router, optional, item } +} + +test('an initially absent optional param can become inherited', async () => { + const { router } = setup() + await router.load() + const cache = {} + const opts = { to: '/optional/{-$id}', params: {} } + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe( + '/optional', + ) + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const fresh = router.buildLocation(opts).href + expect(fresh).toBe('/optional/2') + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe(fresh) +}) + +test('a stringify skipped for empty params must be reconsidered', async () => { + const { router } = setup(true) + await router.load() + const cache = {} + const opts = { to: '/optional/{-$id}', params: {} } + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe( + '/optional', + ) + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const fresh = router.buildLocation(opts).href + expect(fresh).toBe('/optional/s2') + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe(fresh) +}) + +test('route.update invalidates newly installed search middleware', async () => { + const { router, item } = setup() + await router.load() + const cache = {} + const opts = { to: '/items/$id', params: { id: 'fixed' } } + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe( + '/items/fixed', + ) + item.update({ search: { middlewares: [retainSearchParams(true)] } }) + await router.navigate({ to: '/', search: { tab: 'new' } } as any) + const fresh = router.buildLocation(opts).href + expect(fresh).toBe('/items/fixed?tab=new') + expect(router.buildLocation({ ...opts, _buildCache: cache }).href).toBe(fresh) +}) + +test('output rewrites observe a changed locale with stable router options', async () => { + const { router } = setup() + let locale = 'en' + router.update({ + rewrite: { + input: ({ url }) => { + url.pathname = url.pathname.replace(/^\/(en|fr)(?=\/|$)/, '') || '/' + return url + }, + output: ({ url }) => { + url.pathname = `/${locale}${url.pathname}` + return url + }, + }, + }) + await router.load() + const cache = {} + const opts = { to: '/items/$id', params: { id: '9' } } + expect(router.buildLocation({ ...opts, _buildCache: cache }).publicHref).toBe( + '/en/items/9', + ) + locale = 'fr' + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const fresh = router.buildLocation(opts).publicHref + expect(fresh).toBe('/fr/items/9') + expect(router.buildLocation({ ...opts, _buildCache: cache }).publicHref).toBe( + fresh, + ) +}) + +test('cache hits still invoke a custom search serializer', async () => { + const { router } = setup() + let locale = 'en' + router.update({ stringifySearch: () => `?locale=${locale}` }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params: { id: '9' } } + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/9?locale=en', + ) + const entry = cache.value + expect(entry).toBeDefined() + locale = 'fr' + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/9?locale=fr', + ) + expect(cache.value).toBe(entry) +}) + +test('a newly installed params stringifier invalidates a cache hit', async () => { + const { router, item } = setup() + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params: { id: '9' } } + router.buildLocation({ ...options, _buildCache: cache }) + expect(cache.value).toBeDefined() + item.options.params = { stringify: (params) => ({ id: `x${params.id}` }) } + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/x9', + ) + const nextEntry = cache.value + expect(nextEntry).toBeDefined() + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/x9', + ) + expect(cache.value).toBe(nextEntry) +}) + +test('a link cache cannot bypass navigation validation or template matching', async () => { + const { router, item } = setup() + item.update({ + validateSearch: (search: Record) => ({ + page: search.page ?? 1, + }), + } as any) + await router.load() + const options = { to: '/items/$id', params: { id: '9' } } + const cache: import('../src').BuildLocationCache = {} + expect(router.buildLocation({ ...options, _buildCache: cache }).href).toBe( + '/items/9', + ) + expect(cache.value).toBeDefined() + expect( + router.buildLocation({ + ...options, + _buildCache: cache, + _includeValidateSearch: true, + }).href, + ).toBe('/items/9?page=1') + expect( + router.buildLocation({ ...options, _buildCache: cache, leaveParams: true }) + .pathname, + ).toBe('/items/$id') +}) + +test('cache hits build fresh state and continue applying state updaters', async () => { + const { router } = setup() + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { + to: '/items/$id', + params: { id: '9' }, + state: (previous: any): any => ({ count: (previous.count ?? 0) + 1 }), + } + const first = router.buildLocation({ ...options, _buildCache: cache }) + const entry = cache.value + expect(entry).toBeDefined() + await router.navigate({ to: '/', state: { count: 4 } } as any) + const second = router.buildLocation({ ...options, _buildCache: cache }) + expect(second).not.toBe(first) + expect(second.state).toEqual({ count: 5 }) + expect(cache.value).toBe(entry) +}) + +test('search accessors and nested accessors are evaluated on pathname cache hits', async () => { + const { router } = setup() + await router.load() + let locale = 'en' + const search = Object.freeze({ + get locale() { + return locale + }, + nested: Object.freeze({ + get locale() { + return locale + }, + }), + }) + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params: { id: '9' }, search } + router.buildLocation({ ...options, _buildCache: cache }) + const entry = cache.value + expect(entry).toBeDefined() + locale = 'fr' + const cached = router.buildLocation({ ...options, _buildCache: cache }) + expect(cached).toEqual(router.buildLocation(options)) + expect(cached.search).toEqual({ locale: 'fr', nested: { locale: 'fr' } }) + expect(cache.value).toBe(entry) +}) + +test('a mutating serializer does not accumulate mutations in a pathname cache', async () => { + const { router } = setup() + router.update({ + stringifySearch: (search) => { + search.count = (search.count ?? 0) + 1 + return `?count=${search.count}` + }, + }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params: { id: '9' } } + router.buildLocation({ ...options, _buildCache: cache }) + expect(cache.value).toBeDefined() + expect(router.buildLocation({ ...options, _buildCache: cache })).toEqual( + router.buildLocation(options), + ) +}) + +// Cache eligibility follows the effective values, including absent optionals. +test.each([ + [ + 'explicit optional', + { to: '/optional/{-$id}', params: { id: 'fixed' } }, + '/optional/fixed', + ], + [ + 'explicit undefined optional', + { to: '/optional/{-$id}', params: { id: undefined } }, + '/optional', + ], + [ + 'explicit null optional', + { to: '/optional/{-$id}', params: { id: null } }, + '/optional', + ], + ['inherited optional', { to: '/optional/{-$id}' }, '/optional/1'], + [ + 'partially inherited optional', + { to: '/optional/{-$id}', params: {} }, + '/optional/1', + ], + ['params true', { to: '/optional/{-$id}', params: true }, '/optional/1'], + ['params false', { to: '/optional/{-$id}', params: false }, '/optional'], + [ + 'params updater', + { to: '/optional/{-$id}', params: (p: any) => ({ id: p.id }) }, + '/optional/1', + ], + [ + 'relative with from', + { from: '/items/$id', to: '.', params: { id: 'fixed' } }, + '/items/fixed', + ], + ['relative inherited', { to: '.' }, '/items/1'], + ['concrete pathname', { to: '/items/1' }, '/items/1'], +])( + '%s hits across search/hash-only navigation', + async (_, options, pathname) => { + const { router } = setup() + await router.load() + await router.navigate({ to: '/items/$id', params: { id: '1' } }) + const cache: import('../src').BuildLocationCache = {} + const build = () => + router.buildLocation({ ...options, _buildCache: cache } as any) + expect(build().pathname).toBe(pathname) + const entry = cache.value + expect(entry).toBeDefined() + await router.navigate({ + to: '/items/$id', + params: { id: '1' }, + search: { page: 2 }, + hash: 'new', + } as any) + expect(build()).toEqual(router.buildLocation(options as any)) + expect(cache.value).toBe(entry) + }, +) + +test('an absent inherited optional hits until its dependency appears, then hits again', async () => { + const { router } = setup() + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/optional/{-$id}', params: {}, _buildCache: cache } + expect(router.buildLocation(options).pathname).toBe('/optional') + const absent = cache.value + await router.navigate({ to: '/', search: { page: 2 } } as any) + expect(router.buildLocation(options).pathname).toBe('/optional') + expect(cache.value).toBe(absent) + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + expect(router.buildLocation(options).pathname).toBe('/optional/2') + expect(cache.value).not.toBe(absent) + const present = cache.value + router.buildLocation(options) + expect(cache.value).toBe(present) + await router.navigate({ to: '/' }) + expect(router.buildLocation(options).pathname).toBe('/optional') + expect(cache.value).not.toBe(present) +}) + +test('a stringifier runs on cache hits and invalidates only when its output changes', async () => { + const { router, optional } = setup() + let calls = 0 + let prefix = 'a' + optional.options.params = { + stringify: (params: any) => { + calls++ + return { id: prefix + params.id } + }, + } + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { + to: '/optional/{-$id}', + params: { id: '1' }, + _buildCache: cache, + } + expect(router.buildLocation(options).pathname).toBe('/optional/a1') + const first = cache.value + expect(router.buildLocation(options).pathname).toBe('/optional/a1') + expect(cache.value).toBe(first) + expect(calls).toBe(2) + prefix = 'b' + expect(router.buildLocation(options).pathname).toBe('/optional/b1') + expect(cache.value).not.toBe(first) + expect(calls).toBe(3) +}) + +test.each(['/optional/pre{-$id}suf', '/optional/{-$id}/more/{-$other}'])( + 'optional dependency tracking preserves prefixes, suffixes and multiple params in %s', + async (path) => { + const root = new BaseRootRoute({}) + const index = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const route = new BaseRoute({ getParentRoute: () => root, path }) + const router = createTestRouter({ + routeTree: root.addChildren([index, route]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + for (const params of [ + {}, + { id: 'a', other: 'b' }, + { id: undefined, other: 'b' }, + { id: 'a', other: undefined }, + {}, + ]) { + const options = { to: path, params } + expect( + router.buildLocation({ ...options, _buildCache: cache } as any), + ).toEqual(router.buildLocation(options as any)) + const entry = cache.value + expect( + router.buildLocation({ ...options, _buildCache: cache } as any), + ).toEqual(router.buildLocation(options as any)) + expect(cache.value).toBe(entry) + } + }, +) + +test('equivalent relative parent destinations hit across sibling source routes', async () => { + const root = new BaseRootRoute({}) + const parent = new BaseRoute({ + getParentRoute: () => root, + path: '/items/$id', + }) + const a = new BaseRoute({ getParentRoute: () => parent, path: '/a' }) + const b = new BaseRoute({ getParentRoute: () => parent, path: '/b' }) + const router = createTestRouter({ + routeTree: root.addChildren([parent.addChildren([a, b])]), + history: createMemoryHistory({ initialEntries: ['/items/1/a'] }), + }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '..', _buildCache: cache } + expect(router.buildLocation(options).pathname).toBe('/items/1') + const entry = cache.value + await router.navigate({ to: '/items/$id/b', params: { id: '1' } }) + expect(router.buildLocation(options).pathname).toBe('/items/1') + expect(cache.value).toBe(entry) +}) + +test('path resolution and interpolation settings are cache dependencies', async () => { + const { router } = setup() + await router.load() + const cache: import('../src').BuildLocationCache = {} + const options = { to: '/items/$id', params: { id: 'a@b' } } + router.buildLocation({ ...options, _buildCache: cache }) + let entry = cache.value + router.update({ defaultPendingMs: 42 }) + expect(router.buildLocation({ ...options, _buildCache: cache })).toEqual( + router.buildLocation(options), + ) + expect(cache.value).toBe(entry) + router.update({ trailingSlash: 'always' } as any) + expect(router.buildLocation({ ...options, _buildCache: cache })).toEqual( + router.buildLocation(options), + ) + expect(cache.value).not.toBe(entry) + entry = cache.value + router.update({ pathParamsAllowedCharacters: ['@'] }) + expect(router.buildLocation({ ...options, _buildCache: cache })).toEqual( + router.buildLocation(options), + ) + expect(cache.value).not.toBe(entry) +}) + +test('braced splats track _splat with prefixes, suffixes and absent values', async () => { + const root = new BaseRootRoute({}) + const index = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const route = new BaseRoute({ + getParentRoute: () => root, + path: '/files/prefix{$}.txt', + }) + const router = createTestRouter({ + routeTree: root.addChildren([index, route]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + await router.load() + const cache: import('../src').BuildLocationCache = {} + for (const _splat of [undefined, 'a/b', 'space here', '', undefined]) { + const options = { to: '/files/prefix{$}.txt', params: { _splat } } + expect(router.buildLocation({ ...options, _buildCache: cache })).toEqual( + router.buildLocation(options), + ) + const entry = cache.value + router.buildLocation({ ...options, _buildCache: cache }) + expect(cache.value).toBe(entry) + } +}) diff --git a/packages/router-core/tests/build-location-cache.bench.ts b/packages/router-core/tests/build-location-cache.bench.ts new file mode 100644 index 0000000000..5ba36291b6 --- /dev/null +++ b/packages/router-core/tests/build-location-cache.bench.ts @@ -0,0 +1,240 @@ +import { bench, describe, expect } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, retainSearchParams } from '../src' +import { createTestRouter } from './routerTestUtils' + +function setup(middleware = false) { + const root = new BaseRootRoute({ + ...(middleware + ? { search: { middlewares: [retainSearchParams(true)] } } + : {}), + }) + const index = new BaseRoute({ getParentRoute: () => root, path: '/' }) + const item = new BaseRoute({ getParentRoute: () => root, path: '/items/$id' }) + const optional = new BaseRoute({ + getParentRoute: () => root, + path: '/optional/{-$id}', + }) + return createTestRouter({ + routeTree: root.addChildren([index, item, optional]), + history: createMemoryHistory({ initialEntries: ['/items/1'] }), + }) +} + +const batchSize = 100 +const plain = setup() +const middleware = setup(true) +await plain.load() +await middleware.load() +const locations = ['1', '2'].map((id) => + plain.buildLocation({ + to: '/items/$id', + params: { id }, + search: { tab: id }, + }), +) +const literal = { + to: '/items/$id', + params: { id: '9' }, + search: { tab: 'specs', page: 2 }, +} +const inherited = { to: '/items/$id', params: {} } +const optional = { to: '/optional/{-$id}', params: {} } + +// These inputs intentionally work on the parent commit, where the private slot +// is ignored, so the same fixture measures the ordinary build and its cache. +for (const [name, router, options, useCache] of [ + ['uncached literal', plain, literal, false], + ['cached literal', plain, literal, true], + ['uncached inherited', plain, inherited, false], + ['changing inherited params', plain, inherited, true], + ['uncached optional', plain, optional, false], + ['changing optional params', plain, optional, true], + ['uncached middleware', middleware, literal, false], + ['cached middleware', middleware, literal, true], +] as const) { + const cache = {} + const inputs = locations.map((location) => ({ + ...options, + _fromLocation: location, + ...(useCache ? { _buildCache: cache } : {}), + })) + for (const input of inputs) { + const { _buildCache: _, ...fresh } = input as any + expect(router.buildLocation(input as any)).toEqual( + router.buildLocation(fresh), + ) + } + describe(name, () => { + bench( + '100 alternating builds', + () => { + for (let i = 0; i < batchSize; i++) { + router.buildLocation(inputs[i % 2]! as any) + } + }, + { time: 1_000, warmupTime: 300 }, + ) + }) +} + +const mixed = [literal, literal, inherited, optional].map((options) => ({ + ...options, + _buildCache: {}, +})) +for (const [name, cold] of [ + ['stable mixed slots', false], + ['cold literal slots', true], +] as const) { + for (const options of mixed) { + const { _buildCache: _, ...fresh } = options + expect(plain.buildLocation(options as any)).toEqual( + plain.buildLocation(fresh as any), + ) + } + describe(name, () => { + bench( + '100 alternating builds', + () => { + for (let i = 0; i < batchSize; i++) { + const options = cold + ? { ...literal, _buildCache: {} } + : mixed[i % mixed.length]! + plain.buildLocation({ + ...options, + _fromLocation: locations[i % 2], + } as any) + } + }, + { time: 1_000, warmupTime: 300 }, + ) + }) +} + +// Isolate hit rates for destinations the first implementation excluded. These +// locations change search/hash while retaining the path parameter dependency. +const stableLocations = [1, 2].map((page) => + plain.buildLocation({ + to: '/items/$id', + params: { id: '1' }, + search: { page }, + hash: String(page), + }), +) +const withStringify = setup() +withStringify.routesByPath['/items/$id']!.options.params = { + stringify: (params: any) => ({ id: String(params.id) }), +} +await withStringify.load() +for (const [name, router, options] of [ + ['optional supplied', plain, { to: '/optional/{-$id}', params: { id: '9' } }], + [ + 'optional absent', + plain, + { to: '/optional/{-$id}', params: { id: undefined } }, + ], + ['optional inherited unchanged', plain, optional], + ['inherited unchanged', plain, inherited], + ['relative unchanged', plain, { to: '.' }], + [ + 'updater unchanged', + plain, + { to: '/items/$id', params: (params: any) => ({ id: params.id }) }, + ], + ['stringifier unchanged', withStringify, literal], + [ + 'explicit mask', + plain, + { ...literal, mask: { to: '/optional/{-$id}', params: true } }, + ], +] as const) { + for (const useCache of [false, true]) { + const cache: { value?: unknown } = {} + const inputs = stableLocations.map((location) => ({ + ...options, + _fromLocation: location, + ...(useCache ? { _buildCache: cache } : {}), + })) + // One Link keeps its slot while the current location changes. + for (const input of inputs) { + const { _buildCache: _, ...fresh } = input as any + expect(router.buildLocation(input as any)).toEqual( + router.buildLocation(fresh), + ) + } + // The parent implementation ignores the slot. On implementations that + // populate it, require real hits across both locations before timing. + if (cache.value) { + const entry = cache.value + for (const input of inputs) { + router.buildLocation(input as any) + expect(cache.value).toBe(entry) + } + } + describe(`${name} ${useCache ? 'cached' : 'uncached'}`, () => { + bench( + '100 alternating builds', + () => { + for (let i = 0; i < batchSize; i++) { + router.buildLocation(inputs[i % 2]! as any) + } + }, + { time: 1_000, warmupTime: 300 }, + ) + }) + } +} + +describe('mixed hits and changing inherited params', () => { + bench( + '100 alternating builds', + () => { + for (let i = 0; i < batchSize; i++) { + plain.buildLocation({ + ...mixed[i % mixed.length]!, + _fromLocation: locations[Math.floor(i / mixed.length) % 2], + } as any) + } + }, + { time: 1_000, warmupTime: 300 }, + ) +}) + +const splatRoot = new BaseRootRoute({}) +const splatRouter = createTestRouter({ + routeTree: splatRoot.addChildren([ + new BaseRoute({ getParentRoute: () => splatRoot, path: '/files/$' }), + ]), + history: createMemoryHistory({ initialEntries: ['/files/a'] }), +}) +await splatRouter.load() +for (const [name, router, options] of [ + ['static pathname', plain, { to: '/' }], + ['inherited params true', plain, { to: '/items/$id', params: true }], + [ + 'long Unicode splat', + splatRouter, + { to: '/files/$', params: { _splat: 'café/a b/@item/'.repeat(16) } }, + ], +] as const) { + for (const useCache of [false, true]) { + const optionsWithCache = { + ...options, + ...(useCache ? { _buildCache: {} } : {}), + } + expect(router.buildLocation(optionsWithCache as any)).toEqual( + router.buildLocation(options as any), + ) + describe(`${name} ${useCache ? 'cached' : 'uncached'}`, () => { + bench( + '100 repeated builds', + () => { + for (let i = 0; i < batchSize; i++) { + router.buildLocation(optionsWithCache as any) + } + }, + { time: 1_000, warmupTime: 300 }, + ) + }) + } +} diff --git a/packages/router-core/tests/build-location-cache.test.ts b/packages/router-core/tests/build-location-cache.test.ts new file mode 100644 index 0000000000..4639c09727 --- /dev/null +++ b/packages/router-core/tests/build-location-cache.test.ts @@ -0,0 +1,541 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, retainSearchParams } from '../src' +import { createTestRouter } from './routerTestUtils' +import type { AnyRouter, BuildLocationCache, ParsedLocation } from '../src' + +function makeRouter(initialEntry = '/items/1') { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const itemsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + }) + const itemsDetailRoute = new BaseRoute({ + getParentRoute: () => itemsRoute, + path: '/detail', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const routeTree = rootRoute.addChildren([ + indexRoute, + itemsRoute.addChildren([itemsDetailRoute]), + aboutRoute, + ]) + + return createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [initialEntry] }), + }) +} + +/** + * Build `opts` with and without a memo slot and assert the memo did not change + * the answer. Returns whether the pathname cache reused its previous entry, + * which happens while the template and effective params are unchanged, so both + * the fast path and the correctness of the classification are pinned. + */ +function buildBoth( + router: AnyRouter, + cache: BuildLocationCache, + opts: Record, +) { + const previous = cache.value + const cached: ParsedLocation = router.buildLocation({ + ...opts, + _buildCache: cache, + } as any) + const fresh: ParsedLocation = router.buildLocation({ ...opts } as any) + + expect(cached.href).toBe(fresh.href) + expect(cached.publicHref).toBe(fresh.publicHref) + expect(cached.pathname).toBe(fresh.pathname) + expect(cached.searchStr).toBe(fresh.searchStr) + expect(cached.hash).toBe(fresh.hash) + expect(cached.search).toEqual(fresh.search) + expect(cached.state).toEqual(fresh.state) + expect(cached.maskedLocation?.href).toBe(fresh.maskedLocation?.href) + + return { + location: cached, + hit: previous !== undefined && cache.value === previous, + } +} + +describe('buildLocation memo (_buildCache)', () => { + test('a location-independent destination is served from the memo across navigations', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id', params: { id: '9' } } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/9') + + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.href).toBe('/items/9') + + await router.navigate({ to: '/about' }) + const third = buildBoth(router, cache, opts) + expect(third.hit).toBe(true) + expect(third.location.href).toBe('/items/9') + }) + + test('a literal search and hash stay location-independent', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { + to: '/items/$id', + params: { id: '9' }, + search: { tab: 'specs' }, + hash: 'section-9', + } + + expect(buildBoth(router, cache, opts).location.href).toBe( + '/items/9?tab=specs#section-9', + ) + + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + search: { q: 'x' }, + }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.href).toBe('/items/9?tab=specs#section-9') + }) + + // A plain `params` object does not have to be complete: `resolveNextParams` + // merges it over the current location's params, so anything it leaves out is + // inherited. Skipping the `usedParams` check and treating every plain object + // as self-sufficient would memoize these links and freeze their href. + test('a plain `params` object that omits a needed param still follows the current location', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const postRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/posts/$postId', + }) + const editRoute = new BaseRoute({ + getParentRoute: () => postRoute, + path: '/edit', + }) + const tabRoute = new BaseRoute({ + getParentRoute: () => postRoute, + path: '/tab/$tab', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + indexRoute, + postRoute.addChildren([editRoute, tabRoute]), + ]), + history: createMemoryHistory({ initialEntries: ['/posts/1'] }), + }) + await router.load() + + const empty: BuildLocationCache = {} + const partial: BuildLocationCache = {} + const emptyOpts = { to: '/posts/$postId/edit', params: {} } + const partialOpts = { + to: '/posts/$postId/tab/$tab', + params: { tab: 'stats' }, + } + + expect(buildBoth(router, empty, emptyOpts).location.href).toBe( + '/posts/1/edit', + ) + expect(buildBoth(router, partial, partialOpts).location.href).toBe( + '/posts/1/tab/stats', + ) + + await router.navigate({ to: '/posts/$postId', params: { postId: '2' } }) + + const emptyAfter = buildBoth(router, empty, emptyOpts) + expect(emptyAfter.hit).toBe(false) + expect(emptyAfter.location.href).toBe('/posts/2/edit') + + const partialAfter = buildBoth(router, partial, partialOpts) + expect(partialAfter.hit).toBe(false) + expect(partialAfter.location.href).toBe('/posts/2/tab/stats') + }) + + test('inherited params (`params` omitted) follow the current location', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id/detail' } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/1/detail') + + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.href).toBe('/items/2/detail') + }) + + test('`params: true` follows the current location', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id/detail', params: true } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/1/detail') + await router.navigate({ to: '/items/$id', params: { id: '7' } }) + expect(buildBoth(router, cache, opts).location.href).toBe('/items/7/detail') + }) + + test('a params updater function follows the current location', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { + to: '/items/$id/detail', + params: (prev: any) => ({ id: `${prev.id}-x` }), + } + + expect(buildBoth(router, cache, opts).location.href).toBe( + '/items/1-x/detail', + ) + await router.navigate({ to: '/items/$id', params: { id: '7' } }) + expect(buildBoth(router, cache, opts).location.href).toBe( + '/items/7-x/detail', + ) + }) + + test('a relative `to` follows the current location', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: 'detail' } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/1/detail') + await router.navigate({ to: '/about' }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.href).toBe('/about/detail') + }) + + test('`unsafeRelative: path` follows the current pathname', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: 'detail', unsafeRelative: 'path' as const } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/1/detail') + await router.navigate({ to: '/items/$id', params: { id: '5' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.href).toBe('/items/5/detail') + }) + + test('`search: true` follows the current search', async () => { + const router = makeRouter('/items/1?tab=a') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/about', search: true } + + expect(buildBoth(router, cache, opts).location.href).toBe('/about?tab=a') + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + search: { tab: 'b' }, + }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.href).toBe('/about?tab=b') + }) + + test('a search updater function follows the current search', async () => { + const router = makeRouter('/items/1?tab=a') + await router.load() + const cache: BuildLocationCache = {} + const opts = { + to: '/about', + search: (prev: any) => ({ tab: prev.tab, extra: 1 }), + } + + expect(buildBoth(router, cache, opts).location.href).toBe( + '/about?tab=a&extra=1', + ) + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + search: { tab: 'b' }, + }) + expect(buildBoth(router, cache, opts).location.href).toBe( + '/about?tab=b&extra=1', + ) + }) + + test('retainSearchParams middleware follows the current search', async () => { + const rootRoute = new BaseRootRoute({ + validateSearch: (search: { tab?: string }) => search, + search: { middlewares: [retainSearchParams(['tab'])] }, + }) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + const itemsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, aboutRoute, itemsRoute]), + history: createMemoryHistory({ initialEntries: ['/items/1?tab=a'] }), + }) + await router.load() + + const cache: BuildLocationCache = {} + const opts = { to: '/about' } + + expect(buildBoth(router, cache, opts).location.href).toBe('/about?tab=a') + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + search: { tab: 'b' }, + }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.href).toBe('/about?tab=b') + }) + + test('`hash: true` and hash updaters follow the current hash', async () => { + const router = makeRouter('/items/1#one') + await router.load() + const inherit: BuildLocationCache = {} + const updater: BuildLocationCache = {} + + expect( + buildBoth(router, inherit, { to: '/about', hash: true }).location.href, + ).toBe('/about#one') + expect( + buildBoth(router, updater, { + to: '/about', + hash: (prev: string) => `${prev}-x`, + }).location.href, + ).toBe('/about#one-x') + + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + hash: 'two', + }) + + expect( + buildBoth(router, inherit, { to: '/about', hash: true }).location.href, + ).toBe('/about#two') + expect( + buildBoth(router, updater, { + to: '/about', + hash: (prev: string) => `${prev}-x`, + }).location.href, + ).toBe('/about#two-x') + }) + + test('`state: true` follows the current state', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/about', state: true } + + buildBoth(router, cache, opts) + await router.navigate({ + to: '/items/$id', + params: { id: '2' }, + state: { a: 1 } as any, + }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect((second.location.state as any).a).toBe(1) + }) + + test('a route with params.stringify keeps following the current params', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const itemsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + params: { + // `stringify` reads a param the destination does not supply, so the + // built location depends on the current location's params after all. + stringify: (p: any) => ({ id: `${p.id}${p.suffix ?? ''}` }), + }, + }) + const suffixRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/s/$suffix', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, itemsRoute, suffixRoute]), + history: createMemoryHistory({ initialEntries: ['/s/a'] }), + }) + await router.load() + + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id', params: { id: '9' } } + expect(buildBoth(router, cache, opts).location.href).toBe('/items/9a') + + await router.navigate({ to: '/s/$suffix', params: { suffix: 'b' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(false) + expect(second.location.href).toBe('/items/9b') + }) + + test('an explicit mask keeps resolving while the main pathname hits', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { + to: '/items/$id', + params: { id: '9' }, + mask: { to: '/items/$id/detail', params: true }, + } + + const first = buildBoth(router, cache, opts) + expect(first.location.href).toBe('/items/9') + expect(first.location.maskedLocation?.href).toBe('/items/1/detail') + + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.maskedLocation?.href).toBe('/items/2/detail') + }) + + test('routeMasks keep resolving on main pathname cache hits', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const itemsRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/items/$id', + }) + const detailRoute = new BaseRoute({ + getParentRoute: () => itemsRoute, + path: '/detail', + }) + const routeTree = rootRoute.addChildren([ + indexRoute, + itemsRoute.addChildren([detailRoute]), + ]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/items/1'] }), + routeMasks: [ + { + routeTree, + from: '/items/$id/detail', + to: '/items/$id', + } as any, + ], + }) + await router.load() + + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id/detail', params: { id: '9' } } + const first = buildBoth(router, cache, opts) + expect(first.hit).toBe(false) + expect(first.location.maskedLocation?.href).toBe('/items/9') + + await router.navigate({ to: '/items/$id', params: { id: '2' } }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.maskedLocation?.href).toBe('/items/9') + + // Clearing only the option can leave the processed mask tree in place. + router.update({ routeMasks: [] }) + const cleared = buildBoth(router, cache, opts) + expect(cleared.hit).toBe(true) + expect(cleared.location.maskedLocation?.href).toBe('/items/9') + }) + + test('unrelated router options preserve the pathname and apply the new basepath', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id', params: { id: '9' } } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/9') + router.update({ ...router.options, basepath: '/app' }) + const second = buildBoth(router, cache, opts) + expect(second.hit).toBe(true) + expect(second.location.href).toBe('/app/items/9') + }) + + test('HMR refreshes route middleware while reusing an unchanged pathname', async () => { + const router = makeRouter('/items/1') + await router.load() + const cache: BuildLocationCache = {} + const opts = { to: '/items/$id', params: { id: '9' } } + + expect(buildBoth(router, cache, opts).location.href).toBe('/items/9') + // `handleRouteUpdate` in router-plugin swaps route options in place and + // rebuilds the tree without touching `router.options`. + router.routesByPath['/items/$id']!.options.search = { + middlewares: [({ search, next }) => next({ ...search, rebuilt: true })], + } + router.setRoutes(router.buildRouteTree()) + const rebuilt = buildBoth(router, cache, opts) + expect(rebuilt.hit).toBe(true) + expect(rebuilt.location.search).toEqual({ rebuilt: true }) + }) + + test('a splat destination that supplies _splat is location-independent', async () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const filesRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/files/$', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute, filesRoute]), + history: createMemoryHistory({ initialEntries: ['/files/a/b'] }), + }) + await router.load() + + const supplied: BuildLocationCache = {} + const inherited: BuildLocationCache = {} + expect( + buildBoth(router, supplied, { to: '/files/$', params: { _splat: 'x/y' } }) + .location.href, + ).toBe('/files/x/y') + expect(buildBoth(router, inherited, { to: '/files/$' }).location.href).toBe( + '/files/a/b', + ) + + await router.navigate({ to: '/files/$', params: { _splat: 'c/d' } }) + + const suppliedAfter = buildBoth(router, supplied, { + to: '/files/$', + params: { _splat: 'x/y' }, + }) + expect(suppliedAfter.hit).toBe(true) + expect(suppliedAfter.location.href).toBe('/files/x/y') + + const inheritedAfter = buildBoth(router, inherited, { to: '/files/$' }) + expect(inheritedAfter.hit).toBe(false) + expect(inheritedAfter.location.href).toBe('/files/c/d') + }) +}) diff --git a/packages/router-core/tests/path.test.ts b/packages/router-core/tests/path.test.ts index 8e4f5ed1db..5425af7e42 100644 --- a/packages/router-core/tests/path.test.ts +++ b/packages/router-core/tests/path.test.ts @@ -295,6 +295,28 @@ describe('resolvePath', () => { describe.each([{ server: true }, { server: false }])( 'interpolatePath (server: $server)', ({ server }) => { + it.each(['/files/$', '/files/prefix{$}suffix'])( + 'tracks splat dependencies without changing normal aliases: %s', + (path) => { + const options = { path, params: { _splat: 'a/b' }, server } + const normal = interpolatePath(options) + const tracked = interpolatePath({ ...options, trackParams: true }) + expect(normal.usedParams).toEqual({ _splat: 'a/b', '*': 'a/b' }) + expect(tracked.usedParams).toEqual({ _splat: 'a/b' }) + expect(tracked.interpolatedPath).toBe(normal.interpolatedPath) + }, + ) + + it('includes absent optional dependencies only when tracking is requested', () => { + const options = { path: '/items/{-$id}', params: {}, server } + expect(interpolatePath(options).usedParams).toEqual({}) + expect( + interpolatePath({ ...options, trackParams: true }).usedParams, + ).toEqual({ + id: undefined, + }) + }) + describe('regular usage', () => { it.each([ {