Unverified Commit d0dbd3ad authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[Experiment] <Link unstable_dynamicOnHover> (#77866)

This adds an unstable option to the Link component's called
`unstable_dynamicOnHover`. When set to true, the Link will initiate a
dynamic prefetch as soon as the link is hovered.

This is roughly equivalent to updating the prefetch prop to `true`
inside a mouse event handler.

Because this results in dynamic prefetching, semantically it has the
same implication as `prefetch={true}` — by the time the navigation
occurs, the target page's data may be slightly stale.
parent 66514a6b
...@@ -187,6 +187,9 @@ export function getDefineEnv({ ...@@ -187,6 +187,9 @@ export function getDefineEnv({
'process.env.__NEXT_CLIENT_SEGMENT_CACHE': Boolean( 'process.env.__NEXT_CLIENT_SEGMENT_CACHE': Boolean(
config.experimental.clientSegmentCache config.experimental.clientSegmentCache
), ),
'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean(
config.experimental.dynamicOnHover
),
'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE': 'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE':
config.experimental.optimisticClientCache ?? true, config.experimental.optimisticClientCache ?? true,
'process.env.__NEXT_MIDDLEWARE_PREFETCH': 'process.env.__NEXT_MIDDLEWARE_PREFETCH':
......
...@@ -153,6 +153,12 @@ type InternalLinkProps = { ...@@ -153,6 +153,12 @@ type InternalLinkProps = {
*/ */
prefetch?: boolean | null prefetch?: boolean | null
/**
* (unstable) Switch to a dynamic prefetch on hover. Effectively the same as
* updating the prefetch prop to `true` in a mouse event.
*/
unstable_dynamicOnHover?: boolean
/** /**
* The active locale is automatically prepended in the Pages Router. `locale` allows for providing * The active locale is automatically prepended in the Pages Router. `locale` allows for providing
* a different locale, or can be set to `false` to opt out of automatic locale behavior. * a different locale, or can be set to `false` to opt out of automatic locale behavior.
...@@ -336,6 +342,7 @@ export default function LinkComponent( ...@@ -336,6 +342,7 @@ export default function LinkComponent(
legacyBehavior = false, legacyBehavior = false,
onNavigate, onNavigate,
ref: forwardedRef, ref: forwardedRef,
unstable_dynamicOnHover,
...restProps ...restProps
} = props } = props
...@@ -356,6 +363,7 @@ export default function LinkComponent( ...@@ -356,6 +363,7 @@ export default function LinkComponent(
* - null: this is the default "auto" mode, where we will prefetch partially if the link is in the viewport * - null: this is the default "auto" mode, where we will prefetch partially if the link is in the viewport
* - true: we will prefetch if the link is visible and prefetch the full page, not just partially * - true: we will prefetch if the link is visible and prefetch the full page, not just partially
* - false: we will not prefetch if in the viewport at all * - false: we will not prefetch if in the viewport at all
* - 'unstable_dynamicOnHover': this starts in "auto" mode, but switches to "full" when the link is hovered
*/ */
const appPrefetchKind = const appPrefetchKind =
prefetchProp === null ? PrefetchKind.AUTO : PrefetchKind.FULL prefetchProp === null ? PrefetchKind.AUTO : PrefetchKind.FULL
...@@ -408,6 +416,7 @@ export default function LinkComponent( ...@@ -408,6 +416,7 @@ export default function LinkComponent(
shallow: true, shallow: true,
passHref: true, passHref: true,
prefetch: true, prefetch: true,
unstable_dynamicOnHover: true,
onClick: true, onClick: true,
onMouseEnter: true, onMouseEnter: true,
onTouchStart: true, onTouchStart: true,
...@@ -447,7 +456,8 @@ export default function LinkComponent( ...@@ -447,7 +456,8 @@ export default function LinkComponent(
key === 'shallow' || key === 'shallow' ||
key === 'passHref' || key === 'passHref' ||
key === 'prefetch' || key === 'prefetch' ||
key === 'legacyBehavior' key === 'legacyBehavior' ||
key === 'unstable_dynamicOnHover'
) { ) {
if (props[key] != null && valType !== 'boolean') { if (props[key] != null && valType !== 'boolean') {
throw createPropError({ throw createPropError({
...@@ -639,7 +649,11 @@ export default function LinkComponent( ...@@ -639,7 +649,11 @@ export default function LinkComponent(
return return
} }
onNavigationIntent(e.currentTarget as HTMLAnchorElement | SVGAElement) const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true
onNavigationIntent(
e.currentTarget as HTMLAnchorElement | SVGAElement,
upgradeToDynamicPrefetch
)
}, },
onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START
? undefined ? undefined
...@@ -664,7 +678,11 @@ export default function LinkComponent( ...@@ -664,7 +678,11 @@ export default function LinkComponent(
return return
} }
onNavigationIntent(e.currentTarget as HTMLAnchorElement | SVGAElement) const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true
onNavigationIntent(
e.currentTarget as HTMLAnchorElement | SVGAElement,
upgradeToDynamicPrefetch
)
}, },
} }
......
...@@ -10,7 +10,7 @@ import { ...@@ -10,7 +10,7 @@ import {
PrefetchPriority, PrefetchPriority,
schedulePrefetchTask as scheduleSegmentPrefetchTask, schedulePrefetchTask as scheduleSegmentPrefetchTask,
cancelPrefetchTask, cancelPrefetchTask,
bumpPrefetchTask, reschedulePrefetchTask,
} from './segment-cache' } from './segment-cache'
import { startTransition } from 'react' import { startTransition } from 'react'
...@@ -257,7 +257,10 @@ export function onLinkVisibilityChanged(element: Element, isVisible: boolean) { ...@@ -257,7 +257,10 @@ export function onLinkVisibilityChanged(element: Element, isVisible: boolean) {
rescheduleLinkPrefetch(instance) rescheduleLinkPrefetch(instance)
} }
export function onNavigationIntent(element: HTMLAnchorElement | SVGAElement) { export function onNavigationIntent(
element: HTMLAnchorElement | SVGAElement,
unstable_upgradeToDynamicPrefetch: boolean
) {
const instance = prefetchable.get(element) const instance = prefetchable.get(element)
if (instance === undefined) { if (instance === undefined) {
return return
...@@ -265,6 +268,13 @@ export function onNavigationIntent(element: HTMLAnchorElement | SVGAElement) { ...@@ -265,6 +268,13 @@ export function onNavigationIntent(element: HTMLAnchorElement | SVGAElement) {
// Prefetch the link on hover/touchstart. // Prefetch the link on hover/touchstart.
if (instance !== undefined) { if (instance !== undefined) {
instance.wasHoveredOrTouched = true instance.wasHoveredOrTouched = true
if (
process.env.__NEXT_DYNAMIC_ON_HOVER &&
unstable_upgradeToDynamicPrefetch
) {
// Switch to a full, dynamic prefetch
instance.kind = PrefetchKind.FULL
}
rescheduleLinkPrefetch(instance) rescheduleLinkPrefetch(instance)
} }
} }
...@@ -279,7 +289,7 @@ function rescheduleLinkPrefetch(instance: PrefetchableInstance) { ...@@ -279,7 +289,7 @@ function rescheduleLinkPrefetch(instance: PrefetchableInstance) {
cancelPrefetchTask(existingPrefetchTask) cancelPrefetchTask(existingPrefetchTask)
} }
// We don't need to reset the prefetchTask to null upon cancellation; an // We don't need to reset the prefetchTask to null upon cancellation; an
// old task object can be rescheduled with bumpPrefetchTask. This is a // old task object can be rescheduled with reschedulePrefetchTask. This is a
// micro-optimization but also makes the code simpler (don't need to // micro-optimization but also makes the code simpler (don't need to
// worry about whether an old task object is stale). // worry about whether an old task object is stale).
return return
...@@ -301,12 +311,12 @@ function rescheduleLinkPrefetch(instance: PrefetchableInstance) { ...@@ -301,12 +311,12 @@ function rescheduleLinkPrefetch(instance: PrefetchableInstance) {
const priority = instance.wasHoveredOrTouched const priority = instance.wasHoveredOrTouched
? PrefetchPriority.Intent ? PrefetchPriority.Intent
: PrefetchPriority.Default : PrefetchPriority.Default
if (existingPrefetchTask === null) { const appRouterState = getCurrentAppRouterState()
// Initiate a prefetch task. if (appRouterState !== null) {
const appRouterState = getCurrentAppRouterState() const treeAtTimeOfPrefetch = appRouterState.tree
if (appRouterState !== null) { if (existingPrefetchTask === null) {
// Initiate a prefetch task.
const nextUrl = appRouterState.nextUrl const nextUrl = appRouterState.nextUrl
const treeAtTimeOfPrefetch = appRouterState.tree
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl) const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
instance.prefetchTask = scheduleSegmentPrefetchTask( instance.prefetchTask = scheduleSegmentPrefetchTask(
cacheKey, cacheKey,
...@@ -314,12 +324,20 @@ function rescheduleLinkPrefetch(instance: PrefetchableInstance) { ...@@ -314,12 +324,20 @@ function rescheduleLinkPrefetch(instance: PrefetchableInstance) {
instance.kind === PrefetchKind.FULL, instance.kind === PrefetchKind.FULL,
priority priority
) )
instance.cacheVersion = getCurrentCacheVersion() } else {
// We already have an old task object that we can reschedule. This is
// effectively the same as canceling the old task and creating a new one.
reschedulePrefetchTask(
existingPrefetchTask,
treeAtTimeOfPrefetch,
instance.kind === PrefetchKind.FULL,
priority
)
} }
} else {
// We already have an old task object that we can reschedule. This is // Keep track of the cache version at the time the prefetch was requested.
// effectively the same as canceling the old task and creating a new one. // This is used to check if the prefetch is stale.
bumpPrefetchTask(existingPrefetchTask, priority) instance.cacheVersion = getCurrentCacheVersion()
} }
} }
......
...@@ -220,8 +220,10 @@ export function cancelPrefetchTask(task: PrefetchTask): void { ...@@ -220,8 +220,10 @@ export function cancelPrefetchTask(task: PrefetchTask): void {
heapDelete(taskHeap, task) heapDelete(taskHeap, task)
} }
export function bumpPrefetchTask( export function reschedulePrefetchTask(
task: PrefetchTask, task: PrefetchTask,
treeAtTimeOfPrefetch: FlightRouterState,
includeDynamicData: boolean,
priority: PrefetchPriority priority: PrefetchPriority
): void { ): void {
// Bump the prefetch task to the top of the queue, as if it were a fresh // Bump the prefetch task to the top of the queue, as if it were a fresh
...@@ -233,12 +235,16 @@ export function bumpPrefetchTask( ...@@ -233,12 +235,16 @@ export function bumpPrefetchTask(
// Un-cancel the task, in case it was previously canceled. // Un-cancel the task, in case it was previously canceled.
task.isCanceled = false task.isCanceled = false
task.phase = PrefetchPhase.RouteTree
// Assign a new sort ID to move it ahead of all other tasks at the same // Assign a new sort ID to move it ahead of all other tasks at the same
// priority level. (Higher sort IDs are processed first.) // priority level. (Higher sort IDs are processed first.)
task.sortId = sortIdCounter++ task.sortId = sortIdCounter++
task.priority = priority task.priority = priority
task.treeAtTimeOfPrefetch = treeAtTimeOfPrefetch
task.includeDynamicData = includeDynamicData
if (task._heapIndex !== -1) { if (task._heapIndex !== -1) {
// The task is already in the queue. // The task is already in the queue.
heapResift(taskHeap, task) heapResift(taskHeap, task)
......
...@@ -76,10 +76,10 @@ export const cancelPrefetchTask: typeof import('./segment-cache-impl/scheduler') ...@@ -76,10 +76,10 @@ export const cancelPrefetchTask: typeof import('./segment-cache-impl/scheduler')
} }
: notEnabled : notEnabled
export const bumpPrefetchTask: typeof import('./segment-cache-impl/scheduler').bumpPrefetchTask = export const reschedulePrefetchTask: typeof import('./segment-cache-impl/scheduler').reschedulePrefetchTask =
process.env.__NEXT_CLIENT_SEGMENT_CACHE process.env.__NEXT_CLIENT_SEGMENT_CACHE
? function (...args) { ? function (...args) {
return require('./segment-cache-impl/scheduler').bumpPrefetchTask( return require('./segment-cache-impl/scheduler').reschedulePrefetchTask(
...args ...args
) )
} }
......
...@@ -395,6 +395,7 @@ async function exportAppImpl( ...@@ -395,6 +395,7 @@ async function exportAppImpl(
nextConfig.experimental.clientSegmentCache === 'client-only' nextConfig.experimental.clientSegmentCache === 'client-only'
? 'client-only' ? 'client-only'
: Boolean(nextConfig.experimental.clientSegmentCache), : Boolean(nextConfig.experimental.clientSegmentCache),
dynamicOnHover: nextConfig.experimental.dynamicOnHover ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false, inlineCss: nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts, authInterrupts: !!nextConfig.experimental.authInterrupts,
}, },
......
...@@ -214,6 +214,7 @@ export interface RenderOptsPartial { ...@@ -214,6 +214,7 @@ export interface RenderOptsPartial {
clientTraceMetadata: string[] | undefined clientTraceMetadata: string[] | undefined
dynamicIO: boolean dynamicIO: boolean
clientSegmentCache: boolean | 'client-only' clientSegmentCache: boolean | 'client-only'
dynamicOnHover: boolean
inlineCss: boolean inlineCss: boolean
authInterrupts: boolean authInterrupts: boolean
} }
......
...@@ -607,6 +607,7 @@ export default abstract class Server< ...@@ -607,6 +607,7 @@ export default abstract class Server<
this.nextConfig.experimental.clientSegmentCache === 'client-only' this.nextConfig.experimental.clientSegmentCache === 'client-only'
? 'client-only' ? 'client-only'
: Boolean(this.nextConfig.experimental.clientSegmentCache), : Boolean(this.nextConfig.experimental.clientSegmentCache),
dynamicOnHover: this.nextConfig.experimental.dynamicOnHover ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false, inlineCss: this.nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts, authInterrupts: !!this.nextConfig.experimental.authInterrupts,
}, },
......
...@@ -302,6 +302,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -302,6 +302,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
clientSegmentCache: z clientSegmentCache: z
.union([z.boolean(), z.literal('client-only')]) .union([z.boolean(), z.literal('client-only')])
.optional(), .optional(),
dynamicOnHover: z.boolean().optional(),
disableOptimizedLoading: z.boolean().optional(), disableOptimizedLoading: z.boolean().optional(),
disablePostcssPresetEnv: z.boolean().optional(), disablePostcssPresetEnv: z.boolean().optional(),
dynamicIO: z.boolean().optional(), dynamicIO: z.boolean().optional(),
......
...@@ -270,6 +270,7 @@ export interface ExperimentalConfig { ...@@ -270,6 +270,7 @@ export interface ExperimentalConfig {
linkNoTouchStart?: boolean linkNoTouchStart?: boolean
caseSensitiveRoutes?: boolean caseSensitiveRoutes?: boolean
clientSegmentCache?: boolean | 'client-only' clientSegmentCache?: boolean | 'client-only'
dynamicOnHover?: boolean
appDocumentPreloading?: boolean appDocumentPreloading?: boolean
preloadEntriesOnStart?: boolean preloadEntriesOnStart?: boolean
/** @default true */ /** @default true */
...@@ -1198,6 +1199,7 @@ export const defaultConfig: NextConfig = { ...@@ -1198,6 +1199,7 @@ export const defaultConfig: NextConfig = {
linkNoTouchStart: false, linkNoTouchStart: false,
caseSensitiveRoutes: false, caseSensitiveRoutes: false,
clientSegmentCache: false, clientSegmentCache: false,
dynamicOnHover: false,
appDocumentPreloading: undefined, appDocumentPreloading: undefined,
preloadEntriesOnStart: true, preloadEntriesOnStart: true,
clientRouterFilter: true, clientRouterFilter: true,
......
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<div>
Static content in layout of dynamic page
<div>{children}</div>
</div>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
async function DynamicContent() {
await connection()
return <div id="dynamic-content">Dynamic content</div>
}
export default function Page() {
return (
<Suspense fallback={<div>Loading dynamic data...</div>}>
<DynamicContent />
</Suspense>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<LinkAccordion unstable_dynamicOnHover href="/dynamic">
Dynamic page
</LinkAccordion>
)
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
unstable_dynamicOnHover,
}: {
href: string
children: React.ReactNode
prefetch?: boolean
unstable_dynamicOnHover?: boolean
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link
href={href}
prefetch={prefetch}
// @ts-expect-error - unstable_dynamicOnHover is not part of the public types
unstable_dynamicOnHover={unstable_dynamicOnHover}
>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
describe('dynamic on hover', () => {
const { next, isNextDev, skipped } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
if (isNextDev || skipped) {
test('prefetching is disabled', () => {})
return
}
it('prefetches the dynamic data for a Link on hover', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// This Link's unstable_dynamicOnHover prop is set to true
const linkVisibilityToggle = await browser.elementByCss(
'input[data-link-accordion="/dynamic"]'
)
// Reveal the link to start prefetching. Since the link has not been hovered
// yet, the prefetch only includes static data.
await act(async () => {
await linkVisibilityToggle.click()
await browser.elementByCss('a[href="/dynamic"]')
}, [
{
includes: 'Static content in layout of dynamic page',
},
{
includes: 'Loading dynamic data...',
},
])
// Hover over the link to prefetch the dynamic data
const link = await browser.elementByCss('a[href="/dynamic"]')
await act(async () => {
await link.hover()
}, [
// The dynamic data was prefetched
{
includes: 'Dynamic content',
},
// The static content in the layout was not fetched again, because it
// was already cached.
{
includes: 'Static content in layout of dynamic page',
block: 'reject',
},
])
// When navigating to the page, no additional requests are issued, because
// the entire page was prefetched.
await act(async () => {
await link.click()
}, 'no-requests')
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: true,
dynamicIO: true,
clientSegmentCache: true,
dynamicOnHover: true,
},
}
module.exports = nextConfig
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