Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: beforeNavigate #3473

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/router/eslint/create-route-property-order.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ For the following functions, the property order of the passed in object matters
The correct property order is as follows

- `params`, `validateSearch`
- `loaderDeps`, `search.middlewares`
- `loaderDeps`, `search.middlewares`, `beforeNavigate`
- `context`
- `beforeLoad`
- `loader`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export type CreateRouteFunction = (typeof createRouteFunctions)[number]

export const sortRules = [
[['params', 'validateSearch'], ['search']],
[['search'], ['loaderDeps']],
[['search'], ['loaderDeps', 'beforeNavigate']],
[['loaderDeps'], ['context']],
[['context'], ['beforeLoad']],
[['beforeLoad'], ['loader']],
Expand Down
5 changes: 1 addition & 4 deletions packages/react-router/src/RouterProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,7 @@ export type BuildLocationFn = <
TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
TMaskTo extends string = '',
>(
opts: ToOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {
leaveParams?: boolean
_includeValidateSearch?: boolean
},
opts: ToOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo>,
) => ParsedLocation

export function RouterContextProvider<
Expand Down
4 changes: 2 additions & 2 deletions packages/react-router/src/Transitioner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ export function Transitioner() {
React.useEffect(() => {
const unsub = router.history.subscribe(router.load)

const nextLocation = router.buildLocation({
const nextLocation = router.buildLocationInternal({
to: router.latestLocation.pathname,
search: true,
params: true,
hash: true,
state: true,
_includeValidateSearch: true,
})
}).location

if (
trimPathRight(router.latestLocation.href) !==
Expand Down
7 changes: 7 additions & 0 deletions packages/react-router/src/cancelNavigation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function cancelNavigation() {
return { __isCancelNavigation: true }
}

export function isCancelNavigation(obj: any) {
return !!obj?.__isCancelNavigation
}
24 changes: 23 additions & 1 deletion packages/react-router/src/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,21 @@ export type FileBaseRouteOptions<
TRouteContextFn = AnyContext,
TBeforeLoadFn = AnyContext,
TRemountDepsFn = AnyContext,
TBeforeNavigateFn = undefined,
> = ParamsOptions<TPath, TParams> & {
validateSearch?: Constrain<TSearchValidator, AnyValidator, DefaultValidator>

beforeNavigate?: Constrain<
TBeforeNavigateFn,
(
opt: BeforeNavigateOptions<
Expand<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>,
Expand<ResolveAllParamsFromParent<TParentRoute, TParams>>,
TRouterContext
>,
) => void | Promise<void>
>

shouldReload?:
| boolean
| ((
Expand Down Expand Up @@ -210,7 +222,7 @@ export type FileBaseRouteOptions<
(
opt: RemountDepsOptions<
TId,
FullSearchSchemaOption<TParentRoute, TSearchValidator>,
Expand<ResolveFullSearchSchema<TParentRoute, TSearchValidator>>,
Expand<ResolveAllParamsFromParent<TParentRoute, TParams>>,
TLoaderDeps
>,
Expand Down Expand Up @@ -288,6 +300,16 @@ export interface RouteContextOptions<
context: Expand<RouteContextParameter<TParentRoute, TRouterContext>>
}

export interface BeforeNavigateOptions<
in out TFullSearchSchema,
in out TAllParams,
in out TRouterContext,
> {
search: TFullSearchSchema
params: TAllParams
context: TRouterContext
}

export interface RemountDepsOptions<
in out TRouteId,
in out TFullSearchSchema,
Expand Down
55 changes: 49 additions & 6 deletions packages/react-router/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { isRedirect, isResolvedRedirect } from './redirects'
import { isNotFound } from './not-found'

import { setupScrollRestoration } from './scroll-restoration'
import { isCancelNavigation } from './cancelNavigation'
import type * as React from 'react'
import type {
HistoryLocation,
Expand Down Expand Up @@ -530,8 +531,22 @@ export interface BuildNextOptions {
export interface MatchedRoutesResult {
matchedRoutes: Array<AnyRoute>
routeParams: Record<string, string>
foundRoute?: AnyRoute
}

type BuildLocationInternalFn = <
TRouter extends RegisteredRouter,
TTo extends string | undefined,
TFrom extends RoutePaths<TRouter['routeTree']> | string = string,
TMaskFrom extends RoutePaths<TRouter['routeTree']> | string = TFrom,
TMaskTo extends string = '',
>(
opts: ToOptions<TRouter, TFrom, TTo, TMaskFrom, TMaskTo> & {
leaveParams?: boolean
_includeValidateSearch?: boolean
},
) => { location: ParsedLocation; matchedRoutesResult: MatchedRoutesResult }

export type RouterConstructorOptions<
TRouteTree extends AnyRoute,
TTrailingSlashOption extends TrailingSlashOption,
Expand Down Expand Up @@ -1396,7 +1411,10 @@ export class Router<
return matches
}

getMatchedRoutes = (next: ParsedLocation, dest?: BuildNextOptions) => {
getMatchedRoutes = (
next: ParsedLocation,
dest?: BuildNextOptions,
): MatchedRoutesResult => {
let routeParams: Record<string, string> = {}
const trimmedPath = trimPathRight(next.pathname)
const getMatchedParams = (route: AnyRoute) => {
Expand Down Expand Up @@ -1455,6 +1473,10 @@ export class Router<
}

buildLocation: BuildLocationFn = (opts) => {
return this.buildLocationInternal(opts as any).location
}

buildLocationInternal: BuildLocationInternalFn = (opts) => {
const build = (
dest: BuildNextOptions & {
unmaskOnReload?: boolean
Expand Down Expand Up @@ -1742,7 +1764,7 @@ export class Router<
final.maskedLocation = maskedFinal
}

return final
return { location: final, matchedRoutesResult: nextMatches }
}

if (opts.mask) {
Expand Down Expand Up @@ -1864,10 +1886,10 @@ export class Router<
rest.hash = parsed.hash.slice(1)
}

const location = this.buildLocation({
const location = this.buildLocationInternal({
...(rest as any),
_includeValidateSearch: true,
})
}).location
return this.commitLocation({
...location,
viewTransition,
Expand All @@ -1878,7 +1900,7 @@ export class Router<
})
}

navigate: NavigateFn = ({ to, reloadDocument, href, ...rest }) => {
navigate: NavigateFn = async ({ to, reloadDocument, href, ...rest }) => {
if (reloadDocument) {
if (!href) {
const location = this.buildLocation({ to, ...rest } as any)
Expand All @@ -1891,7 +1913,28 @@ export class Router<
}
return
}

const next = this.buildLocationInternal({
to,
...rest,
_includeValidateSearch: true,
} as any)
try {
await next.matchedRoutesResult.foundRoute?.options.beforeNavigate?.({
context: this.options.context,
search: next.location.search as any,
params: next.matchedRoutesResult.routeParams,
})
} catch (err) {
if (isRedirect(err)) {
return this.navigate({
...err,
})
}
if (isCancelNavigation(err)) {
return
}
throw err
}
return this.buildAndCommitLocation({
...rest,
href,
Expand Down
6 changes: 5 additions & 1 deletion packages/react-router/tests/link.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -223,10 +223,13 @@ describe('Link', () => {
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
validateSearch: z.object({ foo: z.string().optional() }),
component: () => {
const { foo } = indexRoute.useSearch()
return (
<>
<h1>Index</h1>
<div data-testid="foo-value">{foo ?? '$undefined'}</div>
<Link
to="/"
activeOptions={{ exact: true }}
Expand Down Expand Up @@ -345,7 +348,8 @@ describe('Link', () => {
expect(indexFooBarLink).not.toHaveAttribute('data-status', 'active')

// navigate to /?foo=bar
fireEvent.click(indexFooBarLink)
act(() => fireEvent.click(indexFooBarLink))
expect(await screen.findByTestId('foo-value')).toHaveTextContent('bar')

expect(indexExactLink).toHaveClass('inactive')
expect(indexExactLink).not.toHaveClass('active')
Expand Down
Loading