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

Unify Link and Form prefetching (#76184)

This updates the Form component to use the same visibility tracking
implementation as the Link component.

It's basically the same changes that were introduced in
https://github.com/vercel/next.js/pull/74670. The resulting improvements
are the same as those for Link:

- Prefetches are initiated directly inside the IntersectionObserver, not
in a useEffect.
- Prefetches initiated by a form component will be canceled if the form
exits the viewport (if the Segment Cache is enabled).
- Prefetches will be re-triggered when the cache is invalidated (if the
Segment Cache is enabled).
parent b0416fbb
'use client' 'use client'
import { useEffect, type FormEvent, useContext } from 'react' import { useCallback, type FormEvent, useContext } from 'react'
import { addBasePath } from '../add-base-path' import { addBasePath } from '../add-base-path'
import { useIntersection } from '../use-intersection'
import { useMergedRef } from '../use-merged-ref' import { useMergedRef } from '../use-merged-ref'
import { import {
AppRouterContext, AppRouterContext,
...@@ -17,6 +16,10 @@ import { ...@@ -17,6 +16,10 @@ import {
hasUnsupportedSubmitterAttributes, hasUnsupportedSubmitterAttributes,
type FormProps, type FormProps,
} from '../form-shared' } from '../form-shared'
import {
mountLinkInstance,
unmountLinkInstance,
} from '../components/segment-cache/links'
export type { FormProps } export type { FormProps }
...@@ -93,31 +96,25 @@ export default function Form({ ...@@ -93,31 +96,25 @@ export default function Form({
// if we don't have an action path, we can't prefetch anything. // if we don't have an action path, we can't prefetch anything.
!!router && isNavigatingForm && prefetch === null !!router && isNavigatingForm && prefetch === null
const [setIntersectionRef, isVisible] = useIntersection({ const observeFormVisibilityOnMount = useCallback(
rootMargin: '200px', (element: HTMLFormElement) => {
disabled: !isPrefetchEnabled, if (isPrefetchEnabled && router !== null) {
}) mountLinkInstance(element, actionProp, router, PrefetchKind.AUTO)
}
return () => {
unmountLinkInstance(element)
}
},
[isPrefetchEnabled, actionProp, router]
)
const ownRef = useMergedRef<HTMLFormElement>( const mergedRef = useMergedRef(
setIntersectionRef, observeFormVisibilityOnMount,
externalRef ?? null externalRef ?? null
) )
useEffect(() => {
if (!isVisible || !isPrefetchEnabled) {
return
}
try {
const prefetchKind = PrefetchKind.AUTO
router.prefetch(actionProp, { kind: prefetchKind })
} catch (err) {
console.error(err)
}
}, [isPrefetchEnabled, isVisible, actionProp, prefetch, router])
if (!isNavigatingForm) { if (!isNavigatingForm) {
return <form {...props} ref={ownRef} /> return <form {...props} ref={mergedRef} />
} }
const actionHref = addBasePath(actionProp) const actionHref = addBasePath(actionProp)
...@@ -125,7 +122,7 @@ export default function Form({ ...@@ -125,7 +122,7 @@ export default function Form({
return ( return (
<form <form
{...props} {...props}
ref={ownRef} ref={mergedRef}
action={actionHref} action={actionHref}
onSubmit={(event) => onSubmit={(event) =>
onFormSubmit(event, { onFormSubmit(event, {
......
This diff is collapsed.
...@@ -62,7 +62,7 @@ import { prefetch as prefetchWithSegmentCache } from '../components/segment-cach ...@@ -62,7 +62,7 @@ import { prefetch as prefetchWithSegmentCache } from '../components/segment-cach
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect' import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'
import { isRedirectError, RedirectType } from './redirect-error' import { isRedirectError, RedirectType } from './redirect-error'
import { prefetchReducer } from './router-reducer/reducers/prefetch-reducer' import { prefetchReducer } from './router-reducer/reducers/prefetch-reducer'
import { pingVisibleLinks } from '../app-dir/link' import { pingVisibleLinks } from './segment-cache/links'
const globalMutable: { const globalMutable: {
pendingMpaPath?: string pendingMpaPath?: string
......
...@@ -360,12 +360,17 @@ export function serverActionReducer( ...@@ -360,12 +360,17 @@ export function serverActionReducer(
} }
if (redirectLocation && redirectHref) { if (redirectLocation && redirectHref) {
// Because the RedirectBoundary will trigger a navigation, we need to seed the prefetch cache if (!process.env.__NEXT_CLIENT_SEGMENT_CACHE && !actionRevalidated) {
// with the FlightData that we got from the server action for the target page, so that it's // Because the RedirectBoundary will trigger a navigation, we need to seed the prefetch cache
// available when the page is navigated to and doesn't need to be re-fetched. // with the FlightData that we got from the server action for the target page, so that it's
// We only do this if the server action didn't revalidate any data, as in that case the // available when the page is navigated to and doesn't need to be re-fetched.
// client cache will be cleared and the data will be re-fetched anyway. // We only do this if the server action didn't revalidate any data, as in that case the
if (!actionRevalidated) { // client cache will be cleared and the data will be re-fetched anyway.
// NOTE: We don't do this in the Segment Cache implementation.
// Dynamic data should never be placed into the cache, unless it's
// "converted" to static data using <Link prefetch={true}>. What we
// do instead is re-prefetch links and forms whenever the cache is
// invalidated.
createSeededPrefetchCacheEntry({ createSeededPrefetchCacheEntry({
url: redirectLocation, url: redirectLocation,
data: { data: {
......
...@@ -52,7 +52,7 @@ import type { ...@@ -52,7 +52,7 @@ import type {
} from '../../../server/app-render/types' } from '../../../server/app-render/types'
import { normalizeFlightData } from '../../flight-data-helpers' import { normalizeFlightData } from '../../flight-data-helpers'
import { STATIC_STALETIME_MS } from '../router-reducer/prefetch-cache-utils' import { STATIC_STALETIME_MS } from '../router-reducer/prefetch-cache-utils'
import { pingVisibleLinks } from '../../app-dir/link' import { pingVisibleLinks } from './links'
// A note on async/await when working in the prefetch cache: // A note on async/await when working in the prefetch cache:
// //
......
import type { FlightRouterState } from '../../../server/app-render/types'
import type { AppRouterInstance } from '../../../shared/lib/app-router-context.shared-runtime'
import { getCurrentAppRouterState } from '../../../shared/lib/router/action-queue'
import { createPrefetchURL } from '../app-router'
import { PrefetchKind } from '../router-reducer/router-reducer-types'
import { getCurrentCacheVersion } from './cache'
import { createCacheKey } from './cache-key'
import {
type PrefetchTask,
PrefetchPriority,
schedulePrefetchTask as scheduleSegmentPrefetchTask,
cancelPrefetchTask,
bumpPrefetchTask,
} from './scheduler'
type LinkElement = HTMLAnchorElement | SVGAElement | HTMLFormElement
type LinkInstance = {
router: AppRouterInstance
kind: PrefetchKind.AUTO | PrefetchKind.FULL
prefetchHref: string
isVisible: boolean
wasHoveredOrTouched: boolean
// The most recently initiated prefetch task. It may or may not have
// already completed. The same prefetch task object can be reused across
// multiple prefetches of the same link.
prefetchTask: PrefetchTask | null
// The cache version at the time the task was initiated. This is used to
// determine if the cache was invalidated since the task was initiated.
cacheVersion: number
}
// Use a WeakMap to associate a Link instance with its DOM element. This is
// used by the IntersectionObserver to track the link's visibility.
const links: WeakMap<LinkElement, LinkInstance> | Map<Element, LinkInstance> =
typeof WeakMap === 'function' ? new WeakMap() : new Map()
// A Set of the currently visible links. We re-prefetch visible links after a
// cache invalidation, or when the current URL changes. It's a separate data
// structure from the WeakMap above because only the visible links need to
// be enumerated.
const visibleLinks: Set<LinkInstance> = new Set()
// A single IntersectionObserver instance shared by all <Link> components.
const observer: IntersectionObserver | null =
typeof IntersectionObserver === 'function'
? new IntersectionObserver(handleIntersect, {
rootMargin: '200px',
})
: null
export function mountLinkInstance(
element: LinkElement,
href: string,
router: AppRouterInstance,
kind: PrefetchKind.AUTO | PrefetchKind.FULL
) {
let prefetchUrl: URL | null = null
try {
prefetchUrl = createPrefetchURL(href)
if (prefetchUrl === null) {
// We only track the link if it's prefetchable. For example, this excludes
// links to external URLs.
return
}
} catch {
// createPrefetchURL sometimes throws an error if an invalid URL is
// provided, though I'm not sure if it's actually necessary.
// TODO: Consider removing the throw from the inner function, or change it
// to reportError. Or maybe the error isn't even necessary for automatic
// prefetches, just navigations.
const reportErrorFn =
typeof reportError === 'function' ? reportError : console.error
reportErrorFn(
`Cannot prefetch '${href}' because it cannot be converted to a URL.`
)
return
}
const instance: LinkInstance = {
prefetchHref: prefetchUrl.href,
router,
kind,
isVisible: false,
wasHoveredOrTouched: false,
prefetchTask: null,
cacheVersion: -1,
}
const existingInstance = links.get(element)
if (existingInstance !== undefined) {
// This shouldn't happen because each <Link> component should have its own
// anchor tag instance, but it's defensive coding to avoid a memory leak in
// case there's a logical error somewhere else.
unmountLinkInstance(element)
}
links.set(element, instance)
if (observer !== null) {
observer.observe(element)
}
}
export function unmountLinkInstance(element: LinkElement) {
const instance = links.get(element)
if (instance !== undefined) {
links.delete(element)
visibleLinks.delete(instance)
const prefetchTask = instance.prefetchTask
if (prefetchTask !== null) {
cancelPrefetchTask(prefetchTask)
}
}
if (observer !== null) {
observer.unobserve(element)
}
}
function handleIntersect(entries: Array<IntersectionObserverEntry>) {
for (const entry of entries) {
// Some extremely old browsers or polyfills don't reliably support
// isIntersecting so we check intersectionRatio instead. (Do we care? Not
// really. But whatever this is fine.)
const isVisible = entry.intersectionRatio > 0
onLinkVisibilityChanged(entry.target as HTMLAnchorElement, isVisible)
}
}
export function onLinkVisibilityChanged(
element: LinkElement,
isVisible: boolean
) {
if (process.env.NODE_ENV !== 'production') {
// Prefetching on viewport is disabled in development for performance
// reasons, because it requires compiling the target page.
// TODO: Investigate re-enabling this.
return
}
const instance = links.get(element)
if (instance === undefined) {
return
}
instance.isVisible = isVisible
if (isVisible) {
visibleLinks.add(instance)
} else {
visibleLinks.delete(instance)
}
rescheduleLinkPrefetch(instance)
}
export function onNavigationIntent(element: HTMLAnchorElement | SVGAElement) {
const instance = links.get(element)
if (instance === undefined) {
return
}
// Prefetch the link on hover/touchstart.
if (instance !== undefined) {
instance.wasHoveredOrTouched = true
rescheduleLinkPrefetch(instance)
}
}
function rescheduleLinkPrefetch(instance: LinkInstance) {
const existingPrefetchTask = instance.prefetchTask
if (!instance.isVisible) {
// Cancel any in-progress prefetch task. (If it already finished then this
// is a no-op.)
if (existingPrefetchTask !== null) {
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
// micro-optimization but also makes the code simpler (don't need to
// worry about whether an old task object is stale).
return
}
if (!process.env.__NEXT_CLIENT_SEGMENT_CACHE) {
// The old prefetch implementation does not have different priority levels.
// Just schedule a new prefetch task.
prefetchWithOldCacheImplementation(instance)
return
}
// In the Segment Cache implementation, we assign a higher priority level to
// links that were at one point hovered or touched. Since the queue is last-
// in-first-out, the highest priority Link is whichever one was hovered last.
//
// We also increase the relative priority of links whenever they re-enter the
// viewport, as if they were being scheduled for the first time.
const priority = instance.wasHoveredOrTouched
? PrefetchPriority.Intent
: PrefetchPriority.Default
if (existingPrefetchTask === null) {
// Initiate a prefetch task.
const appRouterState = getCurrentAppRouterState()
if (appRouterState !== null) {
const nextUrl = appRouterState.nextUrl
const treeAtTimeOfPrefetch = appRouterState.tree
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
instance.prefetchTask = scheduleSegmentPrefetchTask(
cacheKey,
treeAtTimeOfPrefetch,
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.
bumpPrefetchTask(existingPrefetchTask, priority)
}
}
export function pingVisibleLinks(
nextUrl: string | null,
tree: FlightRouterState
) {
// For each currently visible link, cancel the existing prefetch task (if it
// exists) and schedule a new one. This is effectively the same as if all the
// visible links left and then re-entered the viewport.
//
// This is called when the Next-Url or the base tree changes, since those
// may affect the result of a prefetch task. It's also called after a
// cache invalidation.
const currentCacheVersion = getCurrentCacheVersion()
for (const instance of visibleLinks) {
const task = instance.prefetchTask
if (
task !== null &&
instance.cacheVersion === currentCacheVersion &&
task.key.nextUrl === nextUrl &&
task.treeAtTimeOfPrefetch === tree
) {
// The cache has not been invalidated, and none of the inputs have
// changed. Bail out.
continue
}
// Something changed. Cancel the existing prefetch task and schedule a
// new one.
if (task !== null) {
cancelPrefetchTask(task)
}
const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)
const priority = instance.wasHoveredOrTouched
? PrefetchPriority.Intent
: PrefetchPriority.Default
instance.prefetchTask = scheduleSegmentPrefetchTask(
cacheKey,
tree,
instance.kind === PrefetchKind.FULL,
priority
)
instance.cacheVersion = getCurrentCacheVersion()
}
}
function prefetchWithOldCacheImplementation(instance: LinkInstance) {
// This is the path used when the Segment Cache is not enabled.
if (typeof window === 'undefined') {
return
}
const doPrefetch = async () => {
// note that `appRouter.prefetch()` is currently sync,
// so we have to wrap this call in an async function to be able to catch() errors below.
return instance.router.prefetch(instance.prefetchHref, {
kind: instance.kind,
})
}
// Prefetch the page if asked (only in the client)
// We need to handle a prefetch error here since we may be
// loading with priority which can reject but we don't
// want to force navigation since this is only a prefetch
doPrefetch().catch((err) => {
if (process.env.NODE_ENV !== 'production') {
// rethrow to show invalid URL errors
throw err
}
})
}
import { revalidatePath, revalidateTag } from 'next/cache' import { revalidatePath, revalidateTag } from 'next/cache'
import { LinkAccordion } from '../components/link-accordion' import { LinkAccordion, FormAccordion } from '../components/link-accordion'
import Link from 'next/link' import Link from 'next/link'
export default async function Page() { export default async function Page() {
...@@ -31,6 +31,11 @@ export default async function Page() { ...@@ -31,6 +31,11 @@ export default async function Page() {
Link to target page with prefetching enabled Link to target page with prefetching enabled
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<FormAccordion action="/greeting">
Form pointing to target page with prefetching enabled
</FormAccordion>
</li>
<li> <li>
<Link prefetch={false} href="/greeting"> <Link prefetch={false} href="/greeting">
Link to target with prefetching disabled Link to target with prefetching disabled
......
'use client' 'use client'
import Link from 'next/link' import Link from 'next/link'
import Form from 'next/form'
import { useState } from 'react' import { useState } from 'react'
export function LinkAccordion({ export function LinkAccordion({
...@@ -31,3 +32,32 @@ export function LinkAccordion({ ...@@ -31,3 +32,32 @@ export function LinkAccordion({
</> </>
) )
} }
export function FormAccordion({
action,
children,
prefetch,
}: {
action: string
children: React.ReactNode
prefetch?: null | false
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-form-accordion={action}
/>
{isVisible ? (
<Form action={action} prefetch={prefetch}>
<button>{children}</button>
</Form>
) : (
<>{children} (form is hidden)</>
)}
</>
)
}
...@@ -97,6 +97,59 @@ describe('segment cache (revalidation)', () => { ...@@ -97,6 +97,59 @@ describe('segment cache (revalidation)', () => {
}, 'no-requests') }, 'no-requests')
}) })
it('refetch visible Form components after cache is revalidated', async () => {
// This is the same as the previous test, but for forms. Since the
// prefetching implementation is shared between Link and Form, we don't
// bother to test every feature using both Link and Form; this test should
// be sufficient.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page: Playwright.Page) {
act = createRouterAct(page)
},
})
const formVisibilityToggle = await browser.elementByCss(
'input[data-form-accordion="/greeting"]'
)
// Reveal the form that points to the target page to trigger a prefetch
await act(
async () => {
await formVisibilityToggle.click()
},
{
includes: 'random-greeting',
}
)
// Perform an action that calls revalidatePath. This should cause the
// corresponding entry to be evicted from the client cache, and a new
// prefetch to be requested.
await act(
async () => {
const revalidateByPath = await browser.elementById('revalidate-by-path')
await revalidateByPath.click()
},
{
includes: 'random-greeting [1]',
}
)
TestLog.assert(['REQUEST: random-greeting'])
// Navigate to the target page.
await act(async () => {
const button = await browser.elementByCss(
'form[action="/greeting"] button'
)
await button.click()
// Navigation should finish immedately because the page is
// fully prefetched.
const greeting = await browser.elementById('greeting')
expect(await greeting.innerHTML()).toBe('random-greeting [1]')
}, 'no-requests')
})
it('evict client cache when Server Action calls revalidateTag', async () => { it('evict client cache when Server Action calls revalidateTag', async () => {
let act: ReturnType<typeof createRouterAct> let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', { const browser = await next.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