Unverified Commit 296e1800 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Add `transitionTypes` prop to `next/link` (#90701)

Co-authored-by: 's avatarVercel <vercel[bot]@users.noreply.github.com>
Co-authored-by: 's avatarCursor Agent <cursoragent@cursor.com>
parent eab44ed5
...@@ -70,13 +70,14 @@ The following props can be passed to the `<Link>` component: ...@@ -70,13 +70,14 @@ The following props can be passed to the `<Link>` component:
<AppOnly> <AppOnly>
| Prop | Example | Type | Required | | Prop | Example | Type | Required |
| --------------------------- | ------------------------ | ---------------- | -------- | | ------------------------------------- | -------------------------------- | ---------------- | -------- |
| [`href`](#href-required) | `href="/dashboard"` | String or Object | Yes | | [`href`](#href-required) | `href="/dashboard"` | String or Object | Yes |
| [`replace`](#replace) | `replace={false}` | Boolean | - | | [`replace`](#replace) | `replace={false}` | Boolean | - |
| [`scroll`](#scroll) | `scroll={false}` | Boolean | - | | [`scroll`](#scroll) | `scroll={false}` | Boolean | - |
| [`prefetch`](#prefetch) | `prefetch={false}` | Boolean or null | - | | [`prefetch`](#prefetch) | `prefetch={false}` | Boolean or null | - |
| [`onNavigate`](#onnavigate) | `onNavigate={(e) => {}}` | Function | - | | [`onNavigate`](#onnavigate) | `onNavigate={(e) => {}}` | Function | - |
| [`transitionTypes`](#transitiontypes) | `transitionTypes={['slide-in']}` | `string[]` | - |
</AppOnly> </AppOnly>
...@@ -499,6 +500,38 @@ export default function Page() { ...@@ -499,6 +500,38 @@ export default function Page() {
> - External URLs won't trigger `onNavigate` since it's only for client-side and same-origin navigations. > - External URLs won't trigger `onNavigate` since it's only for client-side and same-origin navigations.
> - Links with the `download` attribute will work with `onClick` but not `onNavigate` since the browser will treat the linked URL as a download. > - Links with the `download` attribute will work with `onClick` but not `onNavigate` since the browser will treat the linked URL as a download.
### `transitionTypes`
<AppOnly>
A list of transition types to apply to the navigation. These types are passed to [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType) inside the navigation transition, enabling [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components to apply different animations based on the type of navigation.
```tsx filename="app/page.tsx" switcher
import Link from 'next/link'
export default function Page() {
return (
<Link href="/about" transitionTypes={['slide-in']}>
About
</Link>
)
}
```
```jsx filename="app/page.js" switcher
import Link from 'next/link'
export default function Page() {
return (
<Link href="/about" transitionTypes={['slide-in']}>
About
</Link>
)
}
```
</AppOnly>
## Examples ## Examples
The following examples demonstrate how to use the `<Link>` component in different scenarios. The following examples demonstrate how to use the `<Link>` component in different scenarios.
......
...@@ -41,8 +41,8 @@ export default function Page() { ...@@ -41,8 +41,8 @@ export default function Page() {
## `useRouter()` ## `useRouter()`
- `router.push(href: string, { scroll: boolean })`: Perform a client-side navigation to the provided route. Adds a new entry into the [browser's history stack](https://developer.mozilla.org/docs/Web/API/History_API). - `router.push(href: string, { scroll: boolean, transitionTypes: string[] })`: Perform a client-side navigation to the provided route. Adds a new entry into the [browser's history stack](https://developer.mozilla.org/docs/Web/API/History_API). The optional `transitionTypes` are passed to [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType) inside the navigation Transition.
- `router.replace(href: string, { scroll: boolean })`: Perform a client-side navigation to the provided route without adding a new entry into the browser’s history stack. - `router.replace(href: string, { scroll: boolean, transitionTypes: string[] })`: Perform a client-side navigation to the provided route without adding a new entry into the browser’s history stack. The optional `transitionTypes` are passed to [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType) inside the navigation Transition.
- `router.refresh()`: Refresh the current route. Making a new request to the server, re-fetching data requests, and re-rendering Server Components. The client will merge the updated React Server Component payload without losing unaffected client-side React (e.g. `useState`) or browser state (e.g. scroll position). This clears the [Client Cache](/docs/app/glossary#client-cache) for the current route, but does **not** invalidate the server-side cache. Use [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) to invalidate server-side cached data. - `router.refresh()`: Refresh the current route. Making a new request to the server, re-fetching data requests, and re-rendering Server Components. The client will merge the updated React Server Component payload without losing unaffected client-side React (e.g. `useState`) or browser state (e.g. scroll position). This clears the [Client Cache](/docs/app/glossary#client-cache) for the current route, but does **not** invalidate the server-side cache. Use [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) to invalidate server-side cached data.
- `router.prefetch(href: string, options?: { onInvalidate?: () => void })`: [Prefetch](/docs/app/getting-started/linking-and-navigating#prefetching) the provided route for faster client-side transitions. The optional `onInvalidate` callback is called when the [prefetched data becomes stale](/docs/app/guides/prefetching#extending-or-ejecting-link). - `router.prefetch(href: string, options?: { onInvalidate?: () => void })`: [Prefetch](/docs/app/getting-started/linking-and-navigating#prefetching) the provided route for faster client-side transitions. The optional `onInvalidate` callback is called when the [prefetched data becomes stale](/docs/app/guides/prefetching#extending-or-ejecting-link).
- `router.back()`: Navigate back to the previous route in the browser’s history stack. - `router.back()`: Navigate back to the previous route in the browser’s history stack.
......
...@@ -211,6 +211,20 @@ type InternalLinkProps = { ...@@ -211,6 +211,20 @@ type InternalLinkProps = {
* Optional event handler for when the `<Link>` is navigated. * Optional event handler for when the `<Link>` is navigated.
*/ */
onNavigate?: OnNavigateEventHandler onNavigate?: OnNavigateEventHandler
/**
* Transition types to apply when navigating. These types are passed to
* [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)
* inside the navigation transition, enabling
* [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components
* to apply different animations based on the type of navigation.
*
* @example
* ```tsx
* <Link href="/about" transitionTypes={['slide-in']}>About</Link>
* ```
*/
transitionTypes?: string[]
} }
// TODO-APP: Include the full set of Anchor props // TODO-APP: Include the full set of Anchor props
...@@ -242,7 +256,8 @@ function linkClicked( ...@@ -242,7 +256,8 @@ function linkClicked(
linkInstanceRef: React.RefObject<LinkInstance | null>, linkInstanceRef: React.RefObject<LinkInstance | null>,
replace?: boolean, replace?: boolean,
scroll?: boolean, scroll?: boolean,
onNavigate?: OnNavigateEventHandler onNavigate?: OnNavigateEventHandler,
transitionTypes?: string[]
): void { ): void {
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
const { nodeName } = e.currentTarget const { nodeName } = e.currentTarget
...@@ -293,7 +308,8 @@ function linkClicked( ...@@ -293,7 +308,8 @@ function linkClicked(
href, href,
replace ? 'replace' : 'push', replace ? 'replace' : 'push',
scroll ?? true, scroll ?? true,
linkInstanceRef.current linkInstanceRef.current,
transitionTypes
) )
}) })
} }
...@@ -343,6 +359,7 @@ export default function LinkComponent( ...@@ -343,6 +359,7 @@ export default function LinkComponent(
onTouchStart: onTouchStartProp, onTouchStart: onTouchStartProp,
legacyBehavior = false, legacyBehavior = false,
onNavigate, onNavigate,
transitionTypes,
ref: forwardedRef, ref: forwardedRef,
unstable_dynamicOnHover, unstable_dynamicOnHover,
...restProps ...restProps
...@@ -420,6 +437,7 @@ export default function LinkComponent( ...@@ -420,6 +437,7 @@ export default function LinkComponent(
onTouchStart: true, onTouchStart: true,
legacyBehavior: true, legacyBehavior: true,
onNavigate: true, onNavigate: true,
transitionTypes: true,
} as const } as const
const optionalProps: LinkPropsOptional[] = Object.keys( const optionalProps: LinkPropsOptional[] = Object.keys(
optionalPropsGuard optionalPropsGuard
...@@ -475,6 +493,14 @@ export default function LinkComponent( ...@@ -475,6 +493,14 @@ export default function LinkComponent(
actual: valType, actual: valType,
}) })
} }
} else if (key === 'transitionTypes') {
if (props[key] != null && !Array.isArray(props[key])) {
throw createPropError({
key,
expected: '`string[]`',
actual: valType,
})
}
} else { } else {
// TypeScript trick for type-guarding: // TypeScript trick for type-guarding:
const _: never = key const _: never = key
...@@ -645,7 +671,8 @@ export default function LinkComponent( ...@@ -645,7 +671,8 @@ export default function LinkComponent(
linkInstanceRef, linkInstanceRef,
replace, replace,
scroll, scroll,
onNavigate onNavigate,
transitionTypes
) )
}, },
onMouseEnter(e) { onMouseEnter(e) {
......
...@@ -12,7 +12,7 @@ import { ...@@ -12,7 +12,7 @@ import {
type AppHistoryState, type AppHistoryState,
} from './router-reducer/router-reducer-types' } from './router-reducer/router-reducer-types'
import { reducer } from './router-reducer/router-reducer' import { reducer } from './router-reducer/router-reducer'
import { startTransition } from 'react' import { addTransitionType, startTransition } from 'react'
import { isThenable } from '../../shared/lib/is-thenable' import { isThenable } from '../../shared/lib/is-thenable'
import { import {
FetchStrategy, FetchStrategy,
...@@ -278,10 +278,18 @@ export function dispatchNavigateAction( ...@@ -278,10 +278,18 @@ export function dispatchNavigateAction(
href: string, href: string,
navigateType: NavigateAction['navigateType'], navigateType: NavigateAction['navigateType'],
shouldScroll: boolean, shouldScroll: boolean,
linkInstanceRef: LinkInstance | null linkInstanceRef: LinkInstance | null,
transitionTypes: string[] | undefined
): void { ): void {
// TODO: This stuff could just go into the reducer. Leaving as-is for now // TODO: This stuff could just go into the reducer. Leaving as-is for now
// since we're about to rewrite all the router reducer stuff anyway. // since we're about to rewrite all the router reducer stuff anyway.
if (transitionTypes) {
for (const type of transitionTypes) {
addTransitionType(type)
}
}
const url = new URL(addBasePath(href), location.href) const url = new URL(addBasePath(href), location.href)
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) { if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
window.next.__pendingUrl = url window.next.__pendingUrl = url
...@@ -431,7 +439,13 @@ export const publicAppRouterInstance: AppRouterInstance = { ...@@ -431,7 +439,13 @@ export const publicAppRouterInstance: AppRouterInstance = {
) )
} }
startTransition(() => { startTransition(() => {
dispatchNavigateAction(href, 'replace', options?.scroll ?? true, null) dispatchNavigateAction(
href,
'replace',
options?.scroll ?? true,
null,
options?.transitionTypes
)
}) })
}, },
push: (href: string, options?: NavigateOptions) => { push: (href: string, options?: NavigateOptions) => {
...@@ -441,7 +455,13 @@ export const publicAppRouterInstance: AppRouterInstance = { ...@@ -441,7 +455,13 @@ export const publicAppRouterInstance: AppRouterInstance = {
) )
} }
startTransition(() => { startTransition(() => {
dispatchNavigateAction(href, 'push', options?.scroll ?? true, null) dispatchNavigateAction(
href,
'push',
options?.scroll ?? true,
null,
options?.transitionTypes
)
}) })
}, },
refresh: () => { refresh: () => {
......
...@@ -113,6 +113,20 @@ type InternalLinkProps = { ...@@ -113,6 +113,20 @@ type InternalLinkProps = {
* Optional event handler for when the `<Link>` is navigated. * Optional event handler for when the `<Link>` is navigated.
*/ */
onNavigate?: OnNavigateEventHandler onNavigate?: OnNavigateEventHandler
/**
* Transition types to apply when navigating. These types are passed to
* [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)
* inside the navigation transition, enabling
* [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components
* to apply different animations based on the type of navigation.
*
* @example
* ```tsx
* <Link href="/about" transitionTypes={['slide-in']}>About</Link>
* ```
*/
transitionTypes?: string[]
} }
// TODO-APP: Include the full set of Anchor props // TODO-APP: Include the full set of Anchor props
...@@ -311,6 +325,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -311,6 +325,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
onMouseEnter: onMouseEnterProp, onMouseEnter: onMouseEnterProp,
onTouchStart: onTouchStartProp, onTouchStart: onTouchStartProp,
legacyBehavior = false, legacyBehavior = false,
transitionTypes,
...restProps ...restProps
} = props } = props
...@@ -381,6 +396,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -381,6 +396,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
onTouchStart: true, onTouchStart: true,
legacyBehavior: true, legacyBehavior: true,
onNavigate: true, onNavigate: true,
transitionTypes: true,
} as const } as const
const optionalProps: LinkPropsOptional[] = Object.keys( const optionalProps: LinkPropsOptional[] = Object.keys(
optionalPropsGuard optionalPropsGuard
...@@ -443,6 +459,14 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -443,6 +459,14 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
actual: valType, actual: valType,
}) })
} }
} else if (key === 'transitionTypes') {
if (props[key] != null && !Array.isArray(props[key])) {
throw createPropError({
key,
expected: '`string[]`',
actual: valType,
})
}
} else { } else {
// TypeScript trick for type-guarding: // TypeScript trick for type-guarding:
const _: never = key const _: never = key
......
...@@ -15,6 +15,14 @@ import React from 'react' ...@@ -15,6 +15,14 @@ import React from 'react'
export interface NavigateOptions { export interface NavigateOptions {
scroll?: boolean scroll?: boolean
/**
* Transition types to apply when navigating. These types are passed to
* [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)
* inside the navigation transition, enabling
* [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components
* to apply different animations based on the type of navigation.
*/
transitionTypes?: string[]
} }
export interface PrefetchOptions { export interface PrefetchOptions {
......
import { ViewTransition } from 'react'
import './styles.css'
export default function Layout({ children }) {
return (
<ViewTransition default={{ slide: 'slide' }}>
<div className="page">{children}</div>
</ViewTransition>
)
}
import Link from 'next/link'
export default function PageTwo() {
return (
<div>
<h1>Page Two</h1>
<Link href="/transition-types" transitionTypes={['slide']}>
Back to Page One (with slide)
</Link>
<Link href="/transition-types">Back to Page One (no slide)</Link>
</div>
)
}
import Link from 'next/link'
export default function PageOne() {
return (
<div>
<h1>Page One</h1>
<Link href="/transition-types/page-two" transitionTypes={['slide']}>
Go to Page Two (with slide)
</Link>
<Link href="/transition-types/page-two">Go to Page Two (no slide)</Link>
</div>
)
}
.page {
padding: 20px;
}
::view-transition-old(.slide) {
animation-name: slide-out;
animation-duration: 500ms;
animation-timing-function: ease-in-out;
}
::view-transition-new(.slide) {
animation-name: slide-in;
animation-duration: 500ms;
animation-timing-function: ease-in-out;
}
@keyframes slide-out {
from {
transform: translateX(0);
}
to {
transform: translateX(-100%);
}
}
@keyframes slide-in {
from {
transform: translateX(100%);
}
to {
transform: translateX(0);
}
}
...@@ -21,4 +21,17 @@ describe('view-transitions', () => { ...@@ -21,4 +21,17 @@ describe('view-transitions', () => {
await assertNoConsoleErrors(browser) await assertNoConsoleErrors(browser)
}) })
it('transitionTypes smoketest', async () => {
const browser = await next.browser('/transition-types')
await assertNoConsoleErrors(browser)
// Click the link to navigate to page two
// The first link causes a sliding transition
// The second link causes a default transition (cross-fade)
await browser.elementByCss('a[href="/transition-types/page-two"]').click()
await assertNoConsoleErrors(browser)
})
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment