Unverified Commit 8fe154f4 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Finish deleting Mutable from router implementation (#88046)

Based on:

- #87991

---

The Mutable type was used by an earlier implementation of App Router
when the reducer used to run during React's render phase. It was used to
prevent certain operations from running multiple times if an update was
reapplied by React.

Now that router "reducer" actions run outside React's render phase, we
no longer need this indirection — we can compute the next state object
directly.

Most of the Mutable-related logic was deleted in previous PRs; this
finishes the migration by inlining handleMutable into its callers.
parent 2f046d90
......@@ -40,7 +40,7 @@ import {
type GlobalErrorState,
} from './app-router-instance'
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'
import { isRedirectError, RedirectType } from './redirect-error'
import { isRedirectError } from './redirect-error'
import { pingVisibleLinks } from './links'
import RootErrorBoundary from './errors/root-error-boundary'
import DefaultGlobalError from './builtin/global-error'
......@@ -236,7 +236,7 @@ function Router({
const redirectType = getRedirectTypeFromError(error)
// TODO: This should access the router methods directly, rather than
// go through the public interface.
if (redirectType === RedirectType.push) {
if (redirectType === 'push') {
publicAppRouterInstance.push(url, {})
} else {
publicAppRouterInstance.replace(url, {})
......
......@@ -7,9 +7,13 @@ export function unstable_isUnrecognizedActionError(): boolean {
}
export { redirect, permanentRedirect } from './redirect'
export { RedirectType } from './redirect-error'
export { notFound } from './not-found'
export { forbidden } from './forbidden'
export { unauthorized } from './unauthorized'
export { unstable_rethrow } from './unstable-rethrow'
export { ReadonlyURLSearchParams }
export const RedirectType = {
push: 'push',
replace: 'replace',
}
......@@ -3,7 +3,7 @@ import React, { useEffect } from 'react'
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'
import { useRouter } from './navigation'
import { getRedirectTypeFromError, getURLFromRedirectError } from './redirect'
import { RedirectType, isRedirectError } from './redirect-error'
import { type RedirectType, isRedirectError } from './redirect-error'
interface RedirectBoundaryProps {
router: AppRouterInstance
......@@ -23,7 +23,7 @@ function HandleRedirect({
useEffect(() => {
React.startTransition(() => {
if (redirectType === RedirectType.push) {
if (redirectType === 'push') {
router.push(redirect, {})
} else {
router.replace(redirect, {})
......
......@@ -2,10 +2,7 @@ import { RedirectStatusCode } from './redirect-status-code'
export const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT'
export enum RedirectType {
push = 'push',
replace = 'replace',
}
export type RedirectType = 'push' | 'replace'
export type RedirectError = Error & {
digest: `${typeof REDIRECT_ERROR_CODE};${RedirectType};${string};${RedirectStatusCode};`
......
import { RedirectStatusCode } from './redirect-status-code'
import {
RedirectType,
type RedirectType,
type RedirectError,
isRedirectError,
REDIRECT_ERROR_CODE,
......@@ -40,9 +40,7 @@ export function redirect(
url: string,
type?: RedirectType
): never {
type ??= actionAsyncStorage?.getStore()?.isAction
? RedirectType.push
: RedirectType.replace
type ??= actionAsyncStorage?.getStore()?.isAction ? 'push' : 'replace'
throw getRedirectError(url, type, RedirectStatusCode.TemporaryRedirect)
}
......@@ -61,7 +59,7 @@ export function redirect(
export function permanentRedirect(
/** The URL to redirect to */
url: string,
type: RedirectType = RedirectType.replace
type: RedirectType = 'replace'
): never {
throw getRedirectError(url, type, RedirectStatusCode.PermanentRedirect)
}
......
import { computeChangedPath } from './compute-changed-path'
import type {
Mutable,
ReadonlyReducerState,
ReducerState,
} from './router-reducer-types'
function isNotUndefined<T>(value: T): value is Exclude<T, undefined> {
return typeof value !== 'undefined'
}
export function handleMutable(
state: ReadonlyReducerState,
mutable: Mutable
): ReducerState {
// shouldScroll is true by default, can override to false.
const shouldScroll = mutable.shouldScroll ?? true
let previousNextUrl = state.previousNextUrl
let nextUrl = state.nextUrl
if (isNotUndefined(mutable.patchedTree)) {
// If we received a patched tree, we need to compute the changed path.
const changedPath = computeChangedPath(state.tree, mutable.patchedTree)
if (changedPath) {
// If the tree changed, we need to update the nextUrl
previousNextUrl = nextUrl
nextUrl = changedPath
} else if (!nextUrl) {
// if the tree ends up being the same (ie, no changed path), and we don't have a nextUrl, then we should use the canonicalUrl
nextUrl = state.canonicalUrl
}
// otherwise this will be a no-op and continue to use the existing nextUrl
}
return {
// Set href.
canonicalUrl: mutable.canonicalUrl ?? state.canonicalUrl,
renderedSearch: mutable.renderedSearch ?? state.renderedSearch,
pushRef: {
pendingPush: isNotUndefined(mutable.pendingPush)
? mutable.pendingPush
: state.pushRef.pendingPush,
mpaNavigation: isNotUndefined(mutable.mpaNavigation)
? mutable.mpaNavigation
: state.pushRef.mpaNavigation,
preserveCustomHistoryState: isNotUndefined(
mutable.preserveCustomHistoryState
)
? mutable.preserveCustomHistoryState
: state.pushRef.preserveCustomHistoryState,
},
// All navigation requires scroll and focus management to trigger.
focusAndScrollRef: {
apply: shouldScroll
? isNotUndefined(mutable?.scrollableSegments)
? true
: state.focusAndScrollRef.apply
: // If shouldScroll is false then we should not apply scroll and focus management.
false,
onlyHashChange: mutable.onlyHashChange || false,
hashFragment: shouldScroll
? // Empty hash should trigger default behavior of scrolling layout into view.
// #top is handled in layout-router.
mutable.hashFragment && mutable.hashFragment !== ''
? // Remove leading # and decode hash to make non-latin hashes work.
decodeURIComponent(mutable.hashFragment.slice(1))
: state.focusAndScrollRef.hashFragment
: // If shouldScroll is false then we should not apply scroll and focus management.
null,
segmentPaths: shouldScroll
? (mutable?.scrollableSegments ?? state.focusAndScrollRef.segmentPaths)
: // If shouldScroll is false then we should not apply scroll and focus management.
[],
},
// Apply cache.
cache: mutable.cache ? mutable.cache : state.cache,
// Apply patched router state.
tree: isNotUndefined(mutable.patchedTree)
? mutable.patchedTree
: state.tree,
nextUrl,
previousNextUrl: previousNextUrl,
debugInfo: mutable.collectedDebugInfo ?? null,
}
}
import type {
FlightRouterState,
FlightSegmentPath,
} from '../../../../shared/lib/app-router-types'
import { createHrefFromUrl } from '../create-href-from-url'
import type {
Mutable,
NavigateAction,
ReadonlyReducerState,
ReducerState,
} from '../router-reducer-types'
import { handleMutable } from '../handle-mutable'
import {
completeHardNavigation,
navigate as navigateUsingSegmentCache,
type NavigationResult,
} from '../../segment-cache/navigation'
import { NavigationResultTag } from '../../segment-cache/types'
import { getStaleTimeMs } from '../../segment-cache/cache'
import { FreshnessPolicy } from '../ppr-navigations'
import { isJavaScriptURLString } from '../../../lib/javascript-url'
// These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`)
// and default to 5 minutes (static) / 0 seconds (dynamic)
......@@ -29,141 +20,20 @@ export const STATIC_STALETIME_MS = getStaleTimeMs(
Number(process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME)
)
export function handleExternalUrl(
state: ReadonlyReducerState,
mutable: Mutable,
url: string,
pendingPush: boolean
) {
if (isJavaScriptURLString(url)) {
console.error(
'Next.js has blocked a javascript: URL as a security precaution.'
)
return handleMutable(state, mutable)
}
mutable.mpaNavigation = true
mutable.canonicalUrl = url
mutable.pendingPush = pendingPush
mutable.scrollableSegments = undefined
return handleMutable(state, mutable)
}
export function generateSegmentsFromPatch(
flightRouterPatch: FlightRouterState
): FlightSegmentPath[] {
const segments: FlightSegmentPath[] = []
const [segment, parallelRoutes] = flightRouterPatch
if (Object.keys(parallelRoutes).length === 0) {
return [[segment]]
}
for (const [parallelRouteKey, parallelRoute] of Object.entries(
parallelRoutes
)) {
for (const childSegment of generateSegmentsFromPatch(parallelRoute)) {
// If the segment is empty, it means we are at the root of the tree
if (segment === '') {
segments.push([parallelRouteKey, ...childSegment])
} else {
segments.push([segment, parallelRouteKey, ...childSegment])
}
}
}
return segments
}
export function handleNavigationResult(
url: URL,
state: ReadonlyReducerState,
mutable: Mutable,
pendingPush: boolean,
result: NavigationResult
): ReducerState {
switch (result.tag) {
case NavigationResultTag.MPA: {
// Perform an MPA navigation.
const newUrl = result.data
return handleExternalUrl(state, mutable, newUrl, pendingPush)
}
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
// Check if the only thing that changed was the hash fragment.
const oldUrl = new URL(state.canonicalUrl, url)
const onlyHashChange =
// We don't need to compare the origins, because client-driven
// navigations are always same-origin.
url.pathname === oldUrl.pathname &&
url.search === oldUrl.search &&
url.hash !== oldUrl.hash
if (onlyHashChange) {
// The only updated part of the URL is the hash.
mutable.onlyHashChange = true
mutable.shouldScroll = result.data.shouldScroll
mutable.hashFragment = url.hash
// Setting this to an empty array triggers a scroll for all new and
// updated segments. See `ScrollAndFocusHandler` for more details.
mutable.scrollableSegments = []
}
return handleMutable(state, mutable)
}
case NavigationResultTag.Async: {
return result.data.then(
(asyncResult) =>
handleNavigationResult(url, state, mutable, pendingPush, asyncResult),
// If the navigation failed, return the current state.
// TODO: This matches the current behavior but we need to do something
// better here if the network fails.
() => {
return state
}
)
}
default: {
result satisfies never
return state
}
}
}
export function navigateReducer(
state: ReadonlyReducerState,
action: NavigateAction
): ReducerState {
const { url, isExternalUrl, navigateType, shouldScroll } = action
const mutable: Mutable = {}
const href = createHrefFromUrl(url)
const pendingPush = navigateType === 'push'
mutable.preserveCustomHistoryState = false
mutable.pendingPush = pendingPush
if (isExternalUrl) {
return handleExternalUrl(state, mutable, url.toString(), pendingPush)
return completeHardNavigation(state, url, navigateType)
}
// Handles case where `<meta http-equiv="refresh">` tag is present,
// which will trigger an MPA navigation.
if (document.getElementById('__next-page-redirect')) {
return handleExternalUrl(state, mutable, href, pendingPush)
return completeHardNavigation(state, url, navigateType)
}
// Temporary glue code between the router reducer and the new navigation
......@@ -171,7 +41,8 @@ export function navigateReducer(
// state machine.
const currentUrl = new URL(state.canonicalUrl, location.origin)
const currentRenderedSearch = state.renderedSearch
const result = navigateUsingSegmentCache(
return navigateUsingSegmentCache(
state,
url,
currentUrl,
currentRenderedSearch,
......@@ -180,7 +51,6 @@ export function navigateReducer(
state.nextUrl,
FreshnessPolicy.Default,
shouldScroll,
mutable
navigateType
)
return handleNavigationResult(url, state, mutable, pendingPush, result)
}
import type {
Mutable,
ReadonlyReducerState,
ReducerState,
} from '../router-reducer-types'
import { handleNavigationResult } from './navigate-reducer'
import {
convertServerPatchToFullTree,
navigateToKnownRoute,
......@@ -45,7 +43,7 @@ export function refreshDynamicData(
const currentUrl = new URL(currentCanonicalUrl, location.origin)
const currentRenderedSearch = state.renderedSearch
const currentFlightRouterState = state.tree
const shouldScroll = true
const shouldScroll = false
// Create a NavigationSeed from the current FlightRouterState.
// TODO: Eventually we will store this type directly on the state object
......@@ -58,8 +56,10 @@ export function refreshDynamicData(
)
const now = Date.now()
const result = navigateToKnownRoute(
const navigateType = 'replace'
return navigateToKnownRoute(
now,
state,
currentUrl,
currentCanonicalUrl,
refreshSeed,
......@@ -69,11 +69,8 @@ export function refreshDynamicData(
currentFlightRouterState,
freshnessPolicy,
nextUrlForRefresh,
shouldScroll
shouldScroll,
navigateType,
null
)
const mutable: Mutable = {}
mutable.preserveCustomHistoryState = false
return handleNavigationResult(currentUrl, state, mutable, false, result)
}
import { createHrefFromUrl } from '../create-href-from-url'
import type {
ReadonlyReducerState,
ReducerState,
......@@ -12,9 +11,11 @@ import {
type NavigationRequestAccumulation,
} from '../ppr-navigations'
import type { FlightRouterState } from '../../../../shared/lib/app-router-types'
import { handleExternalUrl } from './navigate-reducer'
import type { Mutable } from '../router-reducer-types'
import { convertServerPatchToFullTree } from '../../segment-cache/navigation'
import {
completeHardNavigation,
completeTraverseNavigation,
convertServerPatchToFullTree,
} from '../../segment-cache/navigation'
export function restoreReducer(
state: ReadonlyReducerState,
......@@ -39,7 +40,6 @@ export function restoreReducer(
const currentUrl = new URL(state.canonicalUrl, location.origin)
const restoredUrl = action.url
const restoredCanonicalUrl = createHrefFromUrl(restoredUrl)
const restoredNextUrl =
extractPathFromFlightRouterState(treeToRestore) ?? restoredUrl.pathname
......@@ -69,12 +69,8 @@ export function restoreReducer(
)
if (task === null) {
const mutable: Mutable = {
preserveCustomHistoryState: true,
}
return handleExternalUrl(state, mutable, restoredCanonicalUrl, false)
return completeHardNavigation(state, restoredUrl, 'replace')
}
spawnDynamicRequests(
task,
restoredUrl,
......@@ -82,27 +78,12 @@ export function restoreReducer(
FreshnessPolicy.HistoryTraversal,
accumulation
)
return {
// Set canonical url
canonicalUrl: restoredCanonicalUrl,
return completeTraverseNavigation(
state,
restoredUrl,
renderedSearch,
pushRef: {
pendingPush: false,
mpaNavigation: false,
// Ensures that the custom history state that was set is preserved when applying this update.
preserveCustomHistoryState: true,
},
focusAndScrollRef: state.focusAndScrollRef,
cache: task.node,
// Restore provided tree
tree: task.route,
nextUrl: restoredNextUrl,
// TODO: We need to restore previousNextUrl, too, which represents the
// Next-Url that was used to fetch the data. Anywhere we fetch using the
// canonical URL, there should be a corresponding Next-Url.
previousNextUrl: null,
debugInfo: null,
}
task.node,
task.route,
restoredNextUrl
)
}
......@@ -28,11 +28,9 @@ import type {
ReadonlyReducerState,
ReducerState,
ServerActionAction,
ServerActionMutable,
} from '../router-reducer-types'
import { assignLocation } from '../../../assign-location'
import { createHrefFromUrl } from '../create-href-from-url'
import { handleExternalUrl, handleNavigationResult } from './navigate-reducer'
import { hasInterceptionRouteInCurrentTree } from './has-interception-route-in-current-tree'
import {
normalizeFlightData,
......@@ -40,7 +38,7 @@ import {
type NormalizedFlightData,
} from '../../../flight-data-helpers'
import { getRedirectError } from '../../redirect'
import { RedirectType } from '../../redirect-error'
import type { RedirectType } from '../../redirect-error'
import { removeBasePath } from '../../../remove-base-path'
import { hasBasePath } from '../../../has-base-path'
import {
......@@ -50,9 +48,10 @@ import {
import { revalidateEntireCache } from '../../segment-cache/cache'
import { getDeploymentId } from '../../../../shared/lib/deployment-id'
import {
completeHardNavigation,
convertServerPatchToFullTree,
navigateToKnownRoute,
navigate as navigateUsingSegmentCache,
navigate,
} from '../../segment-cache/navigation'
import type { NormalizedSearch } from '../../segment-cache/cache-key'
import {
......@@ -155,10 +154,10 @@ async function fetchServerAction(
let redirectType: RedirectType | undefined
switch (_redirectType) {
case 'push':
redirectType = RedirectType.push
redirectType = 'push'
break
case 'replace':
redirectType = RedirectType.replace
redirectType = 'replace'
break
default:
redirectType = undefined
......@@ -255,9 +254,6 @@ export function serverActionReducer(
action: ServerActionAction
): ReducerState {
const { resolve, reject } = action
const mutable: ServerActionMutable = {}
mutable.preserveCustomHistoryState = false
// only pass along the `nextUrl` param (used for interception routes) if the current route was intercepted.
// If the route has been intercepted, the action should be as well.
......@@ -302,9 +298,7 @@ export function serverActionReducer(
}
}
const pendingPush = redirectType !== RedirectType.replace
state.pushRef.pendingPush = pendingPush
mutable.pendingPush = pendingPush
const navigateType = redirectType || 'push'
if (redirectLocation !== undefined) {
// If the action triggered a redirect, the action promise will be rejected with
......@@ -313,17 +307,16 @@ export function serverActionReducer(
// the component that called the action as the error boundary will remount the tree.
// The status code doesn't matter here as the action handler will have already sent
// a response with the correct status code.
const resolvedRedirectType = redirectType || RedirectType.push
if (isExternalURL(redirectLocation)) {
// External redirect. Triggers an MPA navigation.
const redirectHref = redirectLocation.href
const redirectError = createRedirectErrorForAction(
redirectHref,
resolvedRedirectType
navigateType
)
reject(redirectError)
return handleExternalUrl(state, mutable, redirectHref, pendingPush)
return completeHardNavigation(state, redirectLocation, navigateType)
} else {
// Internal redirect. Triggers an SPA navigation.
const redirectWithBasepath = createHrefFromUrl(
......@@ -335,7 +328,7 @@ export function serverActionReducer(
: redirectWithBasepath
const redirectError = createRedirectErrorForAction(
redirectHref,
resolvedRedirectType
navigateType
)
reject(redirectError)
}
......@@ -363,18 +356,17 @@ export function serverActionReducer(
// an external redirect.
// TODO: We should refactor the action response type to be more explicit
// about the various response types.
return handleExternalUrl(
state,
mutable,
redirectLocation.href,
pendingPush
)
return completeHardNavigation(state, redirectLocation, navigateType)
}
if (typeof flightData === 'string') {
// If the flight data is just a string, something earlier in the
// response handling triggered an external redirect.
return handleExternalUrl(state, mutable, flightData, pendingPush)
return completeHardNavigation(
state,
new URL(flightData, location.origin),
navigateType
)
}
// The action triggered a navigation — either a redirect, a revalidation,
......@@ -413,8 +405,9 @@ export function serverActionReducer(
flightDataRenderedSearch
)
const now = Date.now()
const result = navigateToKnownRoute(
return navigateToKnownRoute(
now,
state,
redirectUrl,
redirectCanonicalUrl,
redirectSeed,
......@@ -424,20 +417,16 @@ export function serverActionReducer(
currentFlightRouterState,
freshnessPolicy,
nextUrl,
shouldScroll
)
return handleNavigationResult(
redirectUrl,
state,
mutable,
pendingPush,
result
shouldScroll,
navigateType,
null
)
}
// The server did not send back new data. We'll perform a regular, non-
// seeded navigation — effectively the same as <Link> or router.push().
const result = navigateUsingSegmentCache(
return navigate(
state,
redirectUrl,
currentUrl,
currentRenderedSearch,
......@@ -446,14 +435,7 @@ export function serverActionReducer(
nextUrl,
freshnessPolicy,
shouldScroll,
mutable
)
return handleNavigationResult(
redirectUrl,
state,
mutable,
pendingPush,
result
navigateType
)
},
(e: any) => {
......
......@@ -3,10 +3,11 @@ import type {
ServerPatchAction,
ReducerState,
ReadonlyReducerState,
Mutable,
} from '../router-reducer-types'
import { handleExternalUrl, handleNavigationResult } from './navigate-reducer'
import { navigateToKnownRoute } from '../../segment-cache/navigation'
import {
completeHardNavigation,
navigateToKnownRoute,
} from '../../segment-cache/navigation'
import { refreshReducer } from './refresh-reducer'
import { FreshnessPolicy } from '../ppr-navigations'
......@@ -14,9 +15,6 @@ export function serverPatchReducer(
state: ReadonlyReducerState,
action: ServerPatchAction
): ReducerState {
const mutable: Mutable = {}
mutable.preserveCustomHistoryState = false
// A "retry" is a navigation that happens due to a route mismatch. It's
// similar to a refresh, because we will omit any existing dynamic data on
// the page. But we seed the retry navigation with the exact tree that the
......@@ -24,10 +22,12 @@ export function serverPatchReducer(
const retryMpa = action.mpa
const retryUrl = new URL(action.url, location.origin)
const retrySeed = action.seed
// A retry should not create a new history entry.
const navigateType = 'replace'
if (retryMpa || retrySeed === null) {
// If the server did not send back data during the mismatch, fall back to
// an MPA navigation.
return handleExternalUrl(state, mutable, retryUrl.href, false)
return completeHardNavigation(state, retryUrl, navigateType)
}
const currentUrl = new URL(state.canonicalUrl, location.origin)
const currentRenderedSearch = state.renderedSearch
......@@ -41,12 +41,11 @@ export function serverPatchReducer(
// using the tree we just received from the server.
const retryCanonicalUrl = createHrefFromUrl(retryUrl)
const retryNextUrl = action.nextUrl
// A retry should not create a new history entry.
const pendingPush = false
const shouldScroll = true
const now = Date.now()
const result = navigateToKnownRoute(
return navigateToKnownRoute(
now,
state,
retryUrl,
retryCanonicalUrl,
retrySeed,
......@@ -56,7 +55,8 @@ export function serverPatchReducer(
state.tree,
FreshnessPolicy.RefreshAll,
retryNextUrl,
shouldScroll
shouldScroll,
navigateType,
null
)
return handleNavigationResult(retryUrl, state, mutable, pendingPush, result)
}
......@@ -23,25 +23,6 @@ export type RouterChangeByServerResponse = ({
serverResponse: FetchServerResponseResult
}) => void
export interface Mutable {
mpaNavigation?: boolean
patchedTree?: FlightRouterState
renderedSearch?: string
canonicalUrl?: string
scrollableSegments?: FlightSegmentPath[]
pendingPush?: boolean
cache?: CacheNode
hashFragment?: string
shouldScroll?: boolean
preserveCustomHistoryState?: boolean
onlyHashChange?: boolean
collectedDebugInfo?: Array<unknown>
}
export interface ServerActionMutable extends Mutable {
inFlightServerAction?: Promise<any> | null
}
/**
* Refresh triggers a refresh of the full page data.
* - fetches the Flight data and fills rsc at the root of the cache.
......
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