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

[Segment Cache] Refresh on same-page navigation (#76223)

It's a common UI pattern for apps to refresh when you click a link to
the current page. So when this happens, we refresh the dynamic data in
the page segments.

Note that this does not apply if the any part of the hash or search
query has changed. This might feel a bit weird but it makes more sense
when you consider that the way to trigger this behavior is to click the
same link multiple times.

We should probably refresh the *entire* route when this case occurs, not
just the page segments. Essentially treating it the same as a refresh()
triggered by an action, which is the more explicit way of modeling the
UI pattern described above.

Also note that this only refreshes the dynamic data, not static/cached
data. If the page segment is fully static and prefetched, the request is
skipped. (This is also how refresh() works.)
parent db0a723d
...@@ -92,6 +92,7 @@ export function startPPRNavigation( ...@@ -92,6 +92,7 @@ export function startPPRNavigation(
prefetchData: CacheNodeSeedData | null, prefetchData: CacheNodeSeedData | null,
prefetchHead: HeadData | null, prefetchHead: HeadData | null,
isPrefetchHeadPartial: boolean, isPrefetchHeadPartial: boolean,
isSamePageNavigation: boolean,
scrollableSegmentsResult: Array<FlightSegmentPath> scrollableSegmentsResult: Array<FlightSegmentPath>
): Task | null { ): Task | null {
const segmentPath: Array<FlightSegmentPath> = [] const segmentPath: Array<FlightSegmentPath> = []
...@@ -103,6 +104,7 @@ export function startPPRNavigation( ...@@ -103,6 +104,7 @@ export function startPPRNavigation(
prefetchData, prefetchData,
prefetchHead, prefetchHead,
isPrefetchHeadPartial, isPrefetchHeadPartial,
isSamePageNavigation,
segmentPath, segmentPath,
scrollableSegmentsResult scrollableSegmentsResult
) )
...@@ -116,6 +118,7 @@ function updateCacheNodeOnNavigation( ...@@ -116,6 +118,7 @@ function updateCacheNodeOnNavigation(
prefetchData: CacheNodeSeedData | null, prefetchData: CacheNodeSeedData | null,
prefetchHead: HeadData | null, prefetchHead: HeadData | null,
isPrefetchHeadPartial: boolean, isPrefetchHeadPartial: boolean,
isSamePageNavigation: boolean,
segmentPath: FlightSegmentPath, segmentPath: FlightSegmentPath,
scrollableSegmentsResult: Array<FlightSegmentPath> scrollableSegmentsResult: Array<FlightSegmentPath>
): Task | null { ): Task | null {
...@@ -234,6 +237,44 @@ function updateCacheNodeOnNavigation( ...@@ -234,6 +237,44 @@ function updateCacheNodeOnNavigation(
scrollableSegmentsResult scrollableSegmentsResult
) )
} }
} else if (
isSamePageNavigation &&
// Check if this is a page segment.
// TODO: We're not consistent about how we do this check. Some places
// check if the segment starts with PAGE_SEGMENT_KEY, but most seem to
// check if there any any children, which is why I'm doing it here. We
// should probably encode an empty children set as `null` though. Either
// way, we should update all the checks to be consistent.
Object.keys(newRouterStateChild[1]).length === 0
) {
// We special case navigations to the exact same URL as the current
// location. It's a common UI pattern for apps to refresh when you click a
// link to the current page. So when this happens, we refresh the dynamic
// data in the page segments.
//
// Note that this does not apply if the any part of the hash or search
// query has changed. This might feel a bit weird but it makes more sense
// when you consider that the way to trigger this behavior is to click
// the same link multiple times.
//
// TODO: We should probably refresh the *entire* route when this case
// occurs, not just the page segments. Essentially treating it the same as
// a refresh() triggered by an action, which is the more explicit way of
// modeling the UI pattern described above.
//
// Also note that this only refreshes the dynamic data, not static/
// cached data. If the page segment is fully static and prefetched, the
// request is skipped. (This is also how refresh() works.)
taskChild = beginRenderingNewRouteTree(
oldRouterStateChild,
newRouterStateChild,
didFindRootLayout,
prefetchDataChild !== undefined ? prefetchDataChild : null,
prefetchHead,
isPrefetchHeadPartial,
newSegmentPathChild,
scrollableSegmentsResult
)
} else if ( } else if (
oldRouterStateChild !== undefined && oldRouterStateChild !== undefined &&
oldSegmentChild !== undefined && oldSegmentChild !== undefined &&
...@@ -253,6 +294,7 @@ function updateCacheNodeOnNavigation( ...@@ -253,6 +294,7 @@ function updateCacheNodeOnNavigation(
prefetchDataChild, prefetchDataChild,
prefetchHead, prefetchHead,
isPrefetchHeadPartial, isPrefetchHeadPartial,
isSamePageNavigation,
newSegmentPathChild, newSegmentPathChild,
scrollableSegmentsResult scrollableSegmentsResult
) )
......
...@@ -334,6 +334,7 @@ export function navigateReducer( ...@@ -334,6 +334,7 @@ export function navigateReducer(
seedData, seedData,
head, head,
isHeadPartial, isHeadPartial,
false,
scrollableSegments scrollableSegments
) )
......
...@@ -80,8 +80,35 @@ export function navigate( ...@@ -80,8 +80,35 @@ export function navigate(
shouldScroll: boolean shouldScroll: boolean
): NavigationResult { ): NavigationResult {
const now = Date.now() const now = Date.now()
const href = url.href
const cacheKey = createCacheKey(url.href, nextUrl) // We special case navigations to the exact same URL as the current location.
// It's a common UI pattern for apps to refresh when you click a link to the
// current page. So when this happens, we refresh the dynamic data in the page
// segments.
//
// Note that this does not apply if the any part of the hash or search query
// has changed. This might feel a bit weird but it makes more sense when you
// consider that the way to trigger this behavior is to click the same link
// multiple times.
//
// TODO: We should probably refresh the *entire* route when this case occurs,
// not just the page segments. Essentially treating it the same as a refresh()
// triggered by an action, which is the more explicit way of modeling the UI
// pattern described above.
//
// Also note that this only refreshes the dynamic data, not static/ cached
// data. If the page segment is fully static and prefetched, the request is
// skipped. (This is also how refresh() works.)
const isSamePageNavigation =
// TODO: This is not the only place we read from the location, but we should
// consider storing the current URL in the router state instead of reading
// from the location object. In practice I don't think this matters much
// since we keep them in sync anyway, but having two sources of truth can
// lead to subtle bugs and race conditions.
href === window.location.href
const cacheKey = createCacheKey(href, nextUrl)
const route = readRouteCacheEntry(now, cacheKey) const route = readRouteCacheEntry(now, cacheKey)
if (route !== null && route.status === EntryStatus.Fulfilled) { if (route !== null && route.status === EntryStatus.Fulfilled) {
// We have a matching prefetch. // We have a matching prefetch.
...@@ -94,6 +121,7 @@ export function navigate( ...@@ -94,6 +121,7 @@ export function navigate(
return navigateUsingPrefetchedRouteTree( return navigateUsingPrefetchedRouteTree(
url, url,
nextUrl, nextUrl,
isSamePageNavigation,
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
prefetchFlightRouterState, prefetchFlightRouterState,
...@@ -111,6 +139,7 @@ export function navigate( ...@@ -111,6 +139,7 @@ export function navigate(
data: navigateDynamicallyWithNoPrefetch( data: navigateDynamicallyWithNoPrefetch(
url, url,
nextUrl, nextUrl,
isSamePageNavigation,
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
shouldScroll, shouldScroll,
...@@ -122,6 +151,7 @@ export function navigate( ...@@ -122,6 +151,7 @@ export function navigate(
function navigateUsingPrefetchedRouteTree( function navigateUsingPrefetchedRouteTree(
url: URL, url: URL,
nextUrl: string | null, nextUrl: string | null,
isSamePageNavigation: boolean,
currentCacheNode: CacheNode, currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
prefetchFlightRouterState: FlightRouterState, prefetchFlightRouterState: FlightRouterState,
...@@ -146,6 +176,7 @@ function navigateUsingPrefetchedRouteTree( ...@@ -146,6 +176,7 @@ function navigateUsingPrefetchedRouteTree(
prefetchSeedData, prefetchSeedData,
prefetchHead, prefetchHead,
isPrefetchHeadPartial, isPrefetchHeadPartial,
isSamePageNavigation,
scrollableSegments scrollableSegments
) )
if (task !== null) { if (task !== null) {
...@@ -283,6 +314,7 @@ function readRenderSnapshotFromCache( ...@@ -283,6 +314,7 @@ function readRenderSnapshotFromCache(
async function navigateDynamicallyWithNoPrefetch( async function navigateDynamicallyWithNoPrefetch(
url: URL, url: URL,
nextUrl: string | null, nextUrl: string | null,
isSamePageNavigation: boolean,
currentCacheNode: CacheNode, currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
shouldScroll: boolean, shouldScroll: boolean,
...@@ -345,6 +377,7 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -345,6 +377,7 @@ async function navigateDynamicallyWithNoPrefetch(
prefetchSeedData, prefetchSeedData,
prefetchHead, prefetchHead,
isPrefetchHeadPartial, isPrefetchHeadPartial,
isSamePageNavigation,
scrollableSegments scrollableSegments
) )
if (task !== null) { if (task !== null) {
......
import { Suspense } from 'react'
import { connection } from 'next/server'
async function Content({ children }: { children: React.ReactNode }) {
// Treat the layout as dynamic so we can detect when it's refreshed
await connection()
return <div id="same-page-nav-layout">{children}</div>
}
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<Suspense fallback="Loading...">
<Content>{children}</Content>
</Suspense>
)
}
import Link from 'next/link'
import { connection } from 'next/server'
export default async function SamePageNav() {
// Treat the page as dynamic so we can detect when it's refreshed
await connection()
return (
<>
<p>
Demonstrates that when navigating to the exact same URL as the current
location, we refresh the page segments.
</p>
<p>
Observe that the random number below changes if you click the same link
multiple times, but not when you switch between links.
</p>
<p>
Random number (changes on each refresh):{' '}
<span id="random-number">
{Math.floor(Math.random() * 1_000_000_000)}
</span>
</p>
<ul>
<li>
<Link href="/same-page-nav">Link to current page</Link>
</li>
<li id="hash-b">
<Link href="/same-page-nav#hash-a">
Link to current page with hash fragment <code>#hash-a</code>
</Link>
</li>
<li id="hash-a">
<Link href="/same-page-nav#hash-b">
Link to current page with hash fragment <code>#hash-b</code>
</Link>
</li>
</ul>
</>
)
}
...@@ -16,7 +16,7 @@ export function LinkAccordion({ href, children }) { ...@@ -16,7 +16,7 @@ export function LinkAccordion({ href, children }) {
{isVisible ? ( {isVisible ? (
<Link href={href}>{children}</Link> <Link href={href}>{children}</Link>
) : ( ) : (
`${children} (link is hidden)` <>{children} (link is hidden)</>
)} )}
</> </>
) )
......
...@@ -241,4 +241,70 @@ describe('segment cache (basic tests)', () => { ...@@ -241,4 +241,70 @@ describe('segment cache (basic tests)', () => {
const dynamicDiv = await browser.elementById('dynamic-page') const dynamicDiv = await browser.elementById('dynamic-page')
expect(await dynamicDiv.innerHTML()).toBe('Dynamic page') expect(await dynamicDiv.innerHTML()).toBe('Dynamic page')
}) })
it('refreshes page segments when navigating to the exact same URL as the current location', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/same-page-nav', {
beforePageLoad(page: Playwright.Page) {
act = createRouterAct(page)
},
})
const linkWithNoHash = await browser.elementByCss(
'a[href="/same-page-nav"]'
)
const linkWithHashA = await browser.elementByCss(
'a[href="/same-page-nav#hash-a"]'
)
const linkWithHashB = await browser.elementByCss(
'a[href="/same-page-nav#hash-b"]'
)
async function readRandomNumberFromPage() {
const randomNumber = await browser.elementById('random-number')
return await randomNumber.textContent()
}
// Navigating to the same URL should refresh the page
const randomNumber = await readRandomNumberFromPage()
await act(async () => {
await linkWithNoHash.click()
}, [
{
includes: 'random-number',
},
{
// Only the page segments should be refreshed, not the layouts.
// TODO: We plan to change this in the future.
block: 'reject',
includes: 'same-page-nav-layout',
},
])
const randomNumber2 = await readRandomNumberFromPage()
expect(randomNumber2).not.toBe(randomNumber)
// Navigating to a different hash should *not* refresh the page
await act(async () => {
await linkWithHashA.click()
}, 'no-requests')
expect(await readRandomNumberFromPage()).toBe(randomNumber2)
// Navigating to the same hash again should refresh the page
await act(
async () => {
await linkWithHashA.click()
},
{
includes: 'random-number',
}
)
const randomNumber3 = await readRandomNumberFromPage()
expect(randomNumber3).not.toBe(randomNumber2)
// Navigating to a different hash should *not* refresh the page
await act(async () => {
await linkWithHashB.click()
}, 'no-requests')
expect(await readRandomNumberFromPage()).toBe(randomNumber3)
})
}) })
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