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({
'process.env.__NEXT_CLIENT_SEGMENT_CACHE': Boolean(
config.experimental.clientSegmentCache
),
'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean(
config.experimental.dynamicOnHover
),
'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE':
config.experimental.optimisticClientCache ?? true,
'process.env.__NEXT_MIDDLEWARE_PREFETCH':
......
......@@ -153,6 +153,12 @@ type InternalLinkProps = {
*/
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
* a different locale, or can be set to `false` to opt out of automatic locale behavior.
......@@ -336,6 +342,7 @@ export default function LinkComponent(
legacyBehavior = false,
onNavigate,
ref: forwardedRef,
unstable_dynamicOnHover,
...restProps
} = props
......@@ -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
* - 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
* - 'unstable_dynamicOnHover': this starts in "auto" mode, but switches to "full" when the link is hovered
*/
const appPrefetchKind =
prefetchProp === null ? PrefetchKind.AUTO : PrefetchKind.FULL
......@@ -408,6 +416,7 @@ export default function LinkComponent(
shallow: true,
passHref: true,
prefetch: true,
unstable_dynamicOnHover: true,
onClick: true,
onMouseEnter: true,
onTouchStart: true,
......@@ -447,7 +456,8 @@ export default function LinkComponent(
key === 'shallow' ||
key === 'passHref' ||
key === 'prefetch' ||
key === 'legacyBehavior'
key === 'legacyBehavior' ||
key === 'unstable_dynamicOnHover'
) {
if (props[key] != null && valType !== 'boolean') {
throw createPropError({
......@@ -639,7 +649,11 @@ export default function LinkComponent(
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
? undefined
......@@ -664,7 +678,11 @@ export default function LinkComponent(
return
}
onNavigationIntent(e.currentTarget as HTMLAnchorElement | SVGAElement)
const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true
onNavigationIntent(
e.currentTarget as HTMLAnchorElement | SVGAElement,
upgradeToDynamicPrefetch
)
},
}
......
......@@ -10,7 +10,7 @@ import {
PrefetchPriority,
schedulePrefetchTask as scheduleSegmentPrefetchTask,
cancelPrefetchTask,
bumpPrefetchTask,
reschedulePrefetchTask,
} from './segment-cache'
import { startTransition } from 'react'
......@@ -257,7 +257,10 @@ export function onLinkVisibilityChanged(element: Element, isVisible: boolean) {
rescheduleLinkPrefetch(instance)
}
export function onNavigationIntent(element: HTMLAnchorElement | SVGAElement) {
export function onNavigationIntent(
element: HTMLAnchorElement | SVGAElement,
unstable_upgradeToDynamicPrefetch: boolean
) {
const instance = prefetchable.get(element)
if (instance === undefined) {
return
......@@ -265,6 +268,13 @@ export function onNavigationIntent(element: HTMLAnchorElement | SVGAElement) {
// Prefetch the link on hover/touchstart.
if (instance !== undefined) {
instance.wasHoveredOrTouched = true
if (
process.env.__NEXT_DYNAMIC_ON_HOVER &&
unstable_upgradeToDynamicPrefetch
) {
// Switch to a full, dynamic prefetch
instance.kind = PrefetchKind.FULL
}
rescheduleLinkPrefetch(instance)
}
}
......@@ -279,7 +289,7 @@ function rescheduleLinkPrefetch(instance: PrefetchableInstance) {
cancelPrefetchTask(existingPrefetchTask)
}
// 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
// worry about whether an old task object is stale).
return
......@@ -301,12 +311,12 @@ function rescheduleLinkPrefetch(instance: PrefetchableInstance) {
const priority = instance.wasHoveredOrTouched
? PrefetchPriority.Intent
: PrefetchPriority.Default
if (existingPrefetchTask === null) {
// Initiate a prefetch task.
const appRouterState = getCurrentAppRouterState()
if (appRouterState !== null) {
const appRouterState = getCurrentAppRouterState()
if (appRouterState !== null) {
const treeAtTimeOfPrefetch = appRouterState.tree
if (existingPrefetchTask === null) {
// Initiate a prefetch task.
const nextUrl = appRouterState.nextUrl
const treeAtTimeOfPrefetch = appRouterState.tree
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
instance.prefetchTask = scheduleSegmentPrefetchTask(
cacheKey,
......@@ -314,12 +324,20 @@ function rescheduleLinkPrefetch(instance: PrefetchableInstance) {
instance.kind === PrefetchKind.FULL,
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
// effectively the same as canceling the old task and creating a new one.
bumpPrefetchTask(existingPrefetchTask, priority)
// Keep track of the cache version at the time the prefetch was requested.
// This is used to check if the prefetch is stale.
instance.cacheVersion = getCurrentCacheVersion()
}
}
......
......@@ -220,8 +220,10 @@ export function cancelPrefetchTask(task: PrefetchTask): void {
heapDelete(taskHeap, task)
}
export function bumpPrefetchTask(
export function reschedulePrefetchTask(
task: PrefetchTask,
treeAtTimeOfPrefetch: FlightRouterState,
includeDynamicData: boolean,
priority: PrefetchPriority
): void {
// Bump the prefetch task to the top of the queue, as if it were a fresh
......@@ -233,12 +235,16 @@ export function bumpPrefetchTask(
// Un-cancel the task, in case it was previously canceled.
task.isCanceled = false
task.phase = PrefetchPhase.RouteTree
// Assign a new sort ID to move it ahead of all other tasks at the same
// priority level. (Higher sort IDs are processed first.)
task.sortId = sortIdCounter++
task.priority = priority
task.treeAtTimeOfPrefetch = treeAtTimeOfPrefetch
task.includeDynamicData = includeDynamicData
if (task._heapIndex !== -1) {
// The task is already in the queue.
heapResift(taskHeap, task)
......
......@@ -76,10 +76,10 @@ export const cancelPrefetchTask: typeof import('./segment-cache-impl/scheduler')
}
: 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
? function (...args) {
return require('./segment-cache-impl/scheduler').bumpPrefetchTask(
return require('./segment-cache-impl/scheduler').reschedulePrefetchTask(
...args
)
}
......
......@@ -395,6 +395,7 @@ async function exportAppImpl(
nextConfig.experimental.clientSegmentCache === 'client-only'
? 'client-only'
: Boolean(nextConfig.experimental.clientSegmentCache),
dynamicOnHover: nextConfig.experimental.dynamicOnHover ?? false,
inlineCss: nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts,
},
......
......@@ -214,6 +214,7 @@ export interface RenderOptsPartial {
clientTraceMetadata: string[] | undefined
dynamicIO: boolean
clientSegmentCache: boolean | 'client-only'
dynamicOnHover: boolean
inlineCss: boolean
authInterrupts: boolean
}
......
......@@ -607,6 +607,7 @@ export default abstract class Server<
this.nextConfig.experimental.clientSegmentCache === 'client-only'
? 'client-only'
: Boolean(this.nextConfig.experimental.clientSegmentCache),
dynamicOnHover: this.nextConfig.experimental.dynamicOnHover ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
},
......
......@@ -302,6 +302,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
clientSegmentCache: z
.union([z.boolean(), z.literal('client-only')])
.optional(),
dynamicOnHover: z.boolean().optional(),
disableOptimizedLoading: z.boolean().optional(),
disablePostcssPresetEnv: z.boolean().optional(),
dynamicIO: z.boolean().optional(),
......
......@@ -270,6 +270,7 @@ export interface ExperimentalConfig {
linkNoTouchStart?: boolean
caseSensitiveRoutes?: boolean
clientSegmentCache?: boolean | 'client-only'
dynamicOnHover?: boolean
appDocumentPreloading?: boolean
preloadEntriesOnStart?: boolean
/** @default true */
......@@ -1198,6 +1199,7 @@ export const defaultConfig: NextConfig = {
linkNoTouchStart: false,
caseSensitiveRoutes: false,
clientSegmentCache: false,
dynamicOnHover: false,
appDocumentPreloading: undefined,
preloadEntriesOnStart: 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