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

Refactor: Navigate and refresh simultaneously (#86747)

This is a refactor of the ppr-navigations module to support navigating
to a new tree and refreshing shared layouts within the same navigation.

Rather than modeling navigations and refreshes/revalidations as separate
operations, a refresh is considered a special case of a navigation where
any existing dynamic data is disregarded, and new data is fetched from
the server. The rest of the tree is diffed as usual, and the routing
behavior is the same.

Previously, the ppr-navigations module would revert to the "create" path
whenever it was missing dynamic data (the CacheNode) for a shared
segment. Now, the FlightRouterState alone is used to diff the old and
new trees.

When dynamic data is missing, any shared segment (one that exists in
both the old and new trees) is considered to be part of a "refresh", and
any segment that is present only in the new tree is considered to be
part of a "navigation". There are subtle distinctions in behavior
between refreshes and navigations. For example, refreshed page segments
aren't scrolled to, but navigated page segments are.
parent 2fdb231e
...@@ -80,11 +80,21 @@ export function handleNavigationResult( ...@@ -80,11 +80,21 @@ export function handleNavigationResult(
const newUrl = result.data const newUrl = result.data
return handleExternalUrl(state, mutable, newUrl, pendingPush) return handleExternalUrl(state, mutable, newUrl, pendingPush)
} }
case NavigationResultTag.NoOp: { case NavigationResultTag.Success: {
// The server responded with no change to the current page. However, if // Received a new result.
// the URL changed, we still need to update that. mutable.cache = result.data.cacheNode
const newCanonicalUrl = result.data.canonicalUrl mutable.patchedTree = result.data.flightRouterState
mutable.canonicalUrl = newCanonicalUrl mutable.renderedSearch = result.data.renderedSearch
mutable.canonicalUrl = result.data.canonicalUrl
// TODO: During a refresh, we don't set the `scrollableSegments`. There's
// some confusing and subtle logic in `handleMutable` that decides what
// to do when `shouldScroll` is set but `scrollableSegments` is not. I'm
// not convinced it's totally coherent but the tests assert on this
// particular behavior so I've ported the logic as-is from the previous
// router implementation, for now.
mutable.scrollableSegments = result.data.scrollableSegments ?? undefined
mutable.shouldScroll = result.data.shouldScroll
mutable.hashFragment = result.data.hash
// Check if the only thing that changed was the hash fragment. // Check if the only thing that changed was the hash fragment.
const oldUrl = new URL(state.canonicalUrl, url) const oldUrl = new URL(state.canonicalUrl, url)
...@@ -106,23 +116,6 @@ export function handleNavigationResult( ...@@ -106,23 +116,6 @@ export function handleNavigationResult(
return handleMutable(state, mutable) return handleMutable(state, mutable)
} }
case NavigationResultTag.Success: {
// Received a new result.
mutable.cache = result.data.cacheNode
mutable.patchedTree = result.data.flightRouterState
mutable.renderedSearch = result.data.renderedSearch
mutable.canonicalUrl = result.data.canonicalUrl
// TODO: During a refresh, we don't set the `scrollableSegments`. There's
// some confusing and subtle logic in `handleMutable` that decides what
// to do when `shouldScroll` is set but `scrollableSegments` is not. I'm
// not convinced it's totally coherent but the tests assert on this
// particular behavior so I've ported the logic as-is from the previous
// router implementation, for now.
mutable.scrollableSegments = result.data.scrollableSegments ?? undefined
mutable.shouldScroll = result.data.shouldScroll
mutable.hashFragment = result.data.hash
return handleMutable(state, mutable)
}
case NavigationResultTag.Async: { case NavigationResultTag.Async: {
return result.data.then( return result.data.then(
(asyncResult) => (asyncResult) =>
......
...@@ -6,14 +6,23 @@ import type { ...@@ -6,14 +6,23 @@ import type {
} from '../router-reducer-types' } from '../router-reducer-types'
import { handleNavigationResult } from './navigate-reducer' import { handleNavigationResult } from './navigate-reducer'
import { refresh as refreshUsingSegmentCache } from '../../segment-cache/navigation' import { refresh as refreshUsingSegmentCache } from '../../segment-cache/navigation'
import { revalidateEntireCache } from '../../segment-cache/cache'
export function refreshReducer( export function refreshReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: RefreshAction action: RefreshAction
): ReducerState { ): ReducerState {
// TODO: Currently, all refreshes purge the prefetch cache. In the future,
// only client-side refreshes will have this behavior; the server-side
// `refresh` should send new data without purging the prefetch cache.
const currentNextUrl = state.nextUrl
const currentRouterState = state.tree
revalidateEntireCache(currentNextUrl, currentRouterState)
const currentUrl = new URL(state.canonicalUrl, action.origin) const currentUrl = new URL(state.canonicalUrl, action.origin)
const result = refreshUsingSegmentCache( const result = refreshUsingSegmentCache(
currentUrl, currentUrl,
state.cache,
state.tree, state.tree,
state.nextUrl, state.nextUrl,
state.renderedSearch, state.renderedSearch,
......
...@@ -12,9 +12,8 @@ import type { NormalizedFlightData } from '../../flight-data-helpers' ...@@ -12,9 +12,8 @@ import type { NormalizedFlightData } from '../../flight-data-helpers'
import { fetchServerResponse } from '../router-reducer/fetch-server-response' import { fetchServerResponse } from '../router-reducer/fetch-server-response'
import { import {
startPPRNavigation, startPPRNavigation,
startPPRRefresh,
listenForDynamicRequest, listenForDynamicRequest,
type Task as PPRNavigationTask, type NavigationTask,
type NavigationRequestAccumulation, type NavigationRequestAccumulation,
} from '../router-reducer/ppr-navigations' } from '../router-reducer/ppr-navigations'
import { createHrefFromUrl } from '../router-reducer/create-href-from-url' import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
...@@ -37,14 +36,6 @@ type MPANavigationResult = { ...@@ -37,14 +36,6 @@ type MPANavigationResult = {
data: string data: string
} }
type NoOpNavigationResult = {
tag: NavigationResultTag.NoOp
data: {
canonicalUrl: string
shouldScroll: boolean
}
}
type SuccessfulNavigationResult = { type SuccessfulNavigationResult = {
tag: NavigationResultTag.Success tag: NavigationResultTag.Success
data: { data: {
...@@ -60,15 +51,12 @@ type SuccessfulNavigationResult = { ...@@ -60,15 +51,12 @@ type SuccessfulNavigationResult = {
type AsyncNavigationResult = { type AsyncNavigationResult = {
tag: NavigationResultTag.Async tag: NavigationResultTag.Async
data: Promise< data: Promise<MPANavigationResult | SuccessfulNavigationResult>
MPANavigationResult | NoOpNavigationResult | SuccessfulNavigationResult
>
} }
export type NavigationResult = export type NavigationResult =
| MPANavigationResult | MPANavigationResult
| SuccessfulNavigationResult | SuccessfulNavigationResult
| NoOpNavigationResult
| AsyncNavigationResult | AsyncNavigationResult
/** /**
...@@ -82,7 +70,7 @@ export type NavigationResult = ...@@ -82,7 +70,7 @@ export type NavigationResult =
export function navigate( export function navigate(
url: URL, url: URL,
currentUrl: URL, currentUrl: URL,
currentCacheNode: CacheNode, currentCacheNode: CacheNode | null,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
nextUrl: string | null, nextUrl: string | null,
shouldScroll: boolean, shouldScroll: boolean,
...@@ -223,25 +211,34 @@ export function navigate( ...@@ -223,25 +211,34 @@ export function navigate(
export function refresh( export function refresh(
currentUrl: URL, currentUrl: URL,
currentCacheNode: CacheNode,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
currentNextUrl: string | null, currentNextUrl: string | null,
currentRenderedSearch: string, currentRenderedSearch: string,
currentCanonicalUrl: string currentCanonicalUrl: string
): SuccessfulNavigationResult | NoOpNavigationResult | MPANavigationResult { ): SuccessfulNavigationResult | MPANavigationResult {
// A refresh is a special case of a navigation where all the dynamic data // A refresh is a special case of a navigation where all the dynamic data
// on the current router is re-fetched. Most of the logic is handled within // on the current router is re-fetched. Most of the logic is handled within
// the ppr-navigations module. The main difference here is that we call // the ppr-navigations module. The main difference here is that we set
// startPPRRefresh instead of startPPRNavigation. // shouldRefreshDynamicData to true.
const now = Date.now() const now = Date.now()
const shouldScroll = true const shouldScroll = true
const accumulation: NavigationRequestAccumulation = { const accumulation: NavigationRequestAccumulation = {
scrollableSegments: [], scrollableSegments: [],
separateRefreshUrls: null, separateRefreshUrls: null,
} }
const task = startPPRRefresh( const shouldRefreshDynamicData = true
const task = startPPRNavigation(
now, now,
currentUrl,
currentCacheNode,
currentFlightRouterState,
currentFlightRouterState, currentFlightRouterState,
currentNextUrl, shouldRefreshDynamicData,
null,
null,
false,
true,
accumulation accumulation
) )
if (task !== null) { if (task !== null) {
...@@ -268,31 +265,26 @@ export function refresh( ...@@ -268,31 +265,26 @@ export function refresh(
const newTree = task.route const newTree = task.route
const newCacheNode = task.node const newCacheNode = task.node
if (newTree !== null && newCacheNode !== null) { // Re-render with the new data. All the other data remains the same.
// Re-render with the new data. All the other data remains the same. return {
return { tag: NavigationResultTag.Success,
tag: NavigationResultTag.Success, data: {
data: { flightRouterState: newTree,
flightRouterState: newTree, cacheNode: newCacheNode,
cacheNode: newCacheNode, canonicalUrl: currentCanonicalUrl,
canonicalUrl: currentCanonicalUrl, renderedSearch: currentRenderedSearch,
renderedSearch: currentRenderedSearch, // During a refresh, we don't set the `scrollableSegments`. See
// During a refresh, we don't set the `scrollableSegments`. See // corresponding comment in navigate-reducer.ts for context.
// corresponding comment in navigate-reducer.ts for context. scrollableSegments: null,
scrollableSegments: null, shouldScroll,
shouldScroll, hash: currentUrl.hash,
hash: currentUrl.hash, },
},
}
} }
} }
// Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.
return { return {
tag: NavigationResultTag.NoOp, tag: NavigationResultTag.MPA,
data: { data: currentCanonicalUrl,
canonicalUrl: currentCanonicalUrl,
shouldScroll,
},
} }
} }
...@@ -302,7 +294,7 @@ function navigateUsingPrefetchedRouteTree( ...@@ -302,7 +294,7 @@ function navigateUsingPrefetchedRouteTree(
currentUrl: URL, currentUrl: URL,
nextUrl: string | null, nextUrl: string | null,
isSamePageNavigation: boolean, isSamePageNavigation: boolean,
currentCacheNode: CacheNode, currentCacheNode: CacheNode | null,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
prefetchFlightRouterState: FlightRouterState, prefetchFlightRouterState: FlightRouterState,
prefetchSeedData: CacheNodeSeedData | null, prefetchSeedData: CacheNodeSeedData | null,
...@@ -312,7 +304,7 @@ function navigateUsingPrefetchedRouteTree( ...@@ -312,7 +304,7 @@ function navigateUsingPrefetchedRouteTree(
renderedSearch: string, renderedSearch: string,
shouldScroll: boolean, shouldScroll: boolean,
hash: string hash: string
): SuccessfulNavigationResult | NoOpNavigationResult | MPANavigationResult { ): SuccessfulNavigationResult | MPANavigationResult {
// Recursively construct a prefetch tree by reading from the Segment Cache. To // Recursively construct a prefetch tree by reading from the Segment Cache. To
// maintain compatibility, we output the same data structures as the old // maintain compatibility, we output the same data structures as the old
// prefetching implementation: FlightRouterState and CacheNodeSeedData. // prefetching implementation: FlightRouterState and CacheNodeSeedData.
...@@ -323,12 +315,14 @@ function navigateUsingPrefetchedRouteTree( ...@@ -323,12 +315,14 @@ function navigateUsingPrefetchedRouteTree(
scrollableSegments: [], scrollableSegments: [],
separateRefreshUrls: null, separateRefreshUrls: null,
} }
const shouldRefreshDynamicData = false
const task = startPPRNavigation( const task = startPPRNavigation(
now, now,
currentUrl, currentUrl,
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
prefetchFlightRouterState, prefetchFlightRouterState,
shouldRefreshDynamicData,
prefetchSeedData, prefetchSeedData,
prefetchHead, prefetchHead,
isPrefetchHeadPartial, isPrefetchHeadPartial,
...@@ -348,7 +342,6 @@ function navigateUsingPrefetchedRouteTree( ...@@ -348,7 +342,6 @@ function navigateUsingPrefetchedRouteTree(
} }
return navigationTaskToResult( return navigationTaskToResult(
task, task,
currentCacheNode,
canonicalUrl, canonicalUrl,
renderedSearch, renderedSearch,
accumulation.scrollableSegments, accumulation.scrollableSegments,
...@@ -356,41 +349,26 @@ function navigateUsingPrefetchedRouteTree( ...@@ -356,41 +349,26 @@ function navigateUsingPrefetchedRouteTree(
hash hash
) )
} }
// The server sent back an empty tree patch. There's nothing to update, except // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.
// possibly the URL.
return { return {
tag: NavigationResultTag.NoOp, tag: NavigationResultTag.MPA,
data: { data: canonicalUrl,
canonicalUrl,
shouldScroll,
},
} }
} }
function navigationTaskToResult( function navigationTaskToResult(
task: PPRNavigationTask, task: NavigationTask,
currentCacheNode: CacheNode,
canonicalUrl: string, canonicalUrl: string,
renderedSearch: string, renderedSearch: string,
scrollableSegments: Array<FlightSegmentPath>, scrollableSegments: Array<FlightSegmentPath>,
shouldScroll: boolean, shouldScroll: boolean,
hash: string hash: string
): SuccessfulNavigationResult | MPANavigationResult { ): SuccessfulNavigationResult | MPANavigationResult {
const flightRouterState = task.route
if (flightRouterState === null) {
// When no router state is provided, it signals that we should perform an
// MPA navigation.
return {
tag: NavigationResultTag.MPA,
data: canonicalUrl,
}
}
const newCacheNode = task.node
return { return {
tag: NavigationResultTag.Success, tag: NavigationResultTag.Success,
data: { data: {
flightRouterState, flightRouterState: task.route,
cacheNode: newCacheNode !== null ? newCacheNode : currentCacheNode, cacheNode: task.node,
canonicalUrl, canonicalUrl,
renderedSearch, renderedSearch,
scrollableSegments, scrollableSegments,
...@@ -534,14 +512,12 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -534,14 +512,12 @@ async function navigateDynamicallyWithNoPrefetch(
currentUrl: URL, currentUrl: URL,
nextUrl: string | null, nextUrl: string | null,
isSamePageNavigation: boolean, isSamePageNavigation: boolean,
currentCacheNode: CacheNode, currentCacheNode: CacheNode | null,
currentFlightRouterState: FlightRouterState, currentFlightRouterState: FlightRouterState,
shouldScroll: boolean, shouldScroll: boolean,
hash: string, hash: string,
collectedDebugInfo: Array<unknown> collectedDebugInfo: Array<unknown>
): Promise< ): Promise<MPANavigationResult | SuccessfulNavigationResult> {
MPANavigationResult | SuccessfulNavigationResult | NoOpNavigationResult
> {
// Runs when a navigation happens but there's no cached prefetch we can use. // Runs when a navigation happens but there's no cached prefetch we can use.
// Don't bother to wait for a prefetch response; go straight to a full // Don't bother to wait for a prefetch response; go straight to a full
// navigation that contains both static and dynamic data in a single stream. // navigation that contains both static and dynamic data in a single stream.
...@@ -597,12 +573,14 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -597,12 +573,14 @@ async function navigateDynamicallyWithNoPrefetch(
scrollableSegments: [], scrollableSegments: [],
separateRefreshUrls: null, separateRefreshUrls: null,
} }
const shouldRefreshDynamicData = false
const task = startPPRNavigation( const task = startPPRNavigation(
now, now,
currentUrl, currentUrl,
currentCacheNode, currentCacheNode,
currentFlightRouterState, currentFlightRouterState,
prefetchFlightRouterState, prefetchFlightRouterState,
shouldRefreshDynamicData,
prefetchSeedData, prefetchSeedData,
prefetchHead, prefetchHead,
isPrefetchHeadPartial, isPrefetchHeadPartial,
...@@ -633,7 +611,6 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -633,7 +611,6 @@ async function navigateDynamicallyWithNoPrefetch(
} }
return navigationTaskToResult( return navigationTaskToResult(
task, task,
currentCacheNode,
createHrefFromUrl(canonicalUrl), createHrefFromUrl(canonicalUrl),
renderedSearch, renderedSearch,
accumulation.scrollableSegments, accumulation.scrollableSegments,
...@@ -641,14 +618,10 @@ async function navigateDynamicallyWithNoPrefetch( ...@@ -641,14 +618,10 @@ async function navigateDynamicallyWithNoPrefetch(
hash hash
) )
} }
// The server sent back an empty tree patch. There's nothing to update, except // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.
// possibly the URL.
return { return {
tag: NavigationResultTag.NoOp, tag: NavigationResultTag.MPA,
data: { data: createHrefFromUrl(canonicalUrl),
canonicalUrl: createHrefFromUrl(canonicalUrl),
shouldScroll,
},
} }
} }
......
...@@ -86,3 +86,4 @@ export function getSelectedLayoutSegmentPath( ...@@ -86,3 +86,4 @@ export function getSelectedLayoutSegmentPath(
export const PAGE_SEGMENT_KEY = '__PAGE__' export const PAGE_SEGMENT_KEY = '__PAGE__'
export const DEFAULT_SEGMENT_KEY = '__DEFAULT__' export const DEFAULT_SEGMENT_KEY = '__DEFAULT__'
export const NOT_FOUND_SEGMENT_KEY = '/_not-found'
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