Unverified Commit 65a74b1b authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Remove `mutable` field from action types (#59221)

Similar in spirit to #58938.

The app router reducer state used to be managed by useReducer, so it was
written to be resilient to rebasing — the same action may be processed
multiple times. Now that we've lifted the reducer outside of React
(#56497), each action runs only a single time. So we can simplify some
of the logic.

The purpose of the `mutable` field was so that if an action is processed
multiple times, state could be reused between each run; for example, to
prevent redundant network fetches. Now that this scenario can no longer
happen, we can remove it.

I had to update some of the unit tests in navigate-reducer because they
were written with the assumption that the reducer was called multiple
times. As far as I can tell, most of this behavior is covered by e2e
tests anyway, so I don't think it's too risky.

Closes NEXT-1782
parent b2e183ec
...@@ -162,7 +162,6 @@ function useServerActionDispatcher(dispatch: React.Dispatch<ReducerActions>) { ...@@ -162,7 +162,6 @@ function useServerActionDispatcher(dispatch: React.Dispatch<ReducerActions>) {
dispatch({ dispatch({
...actionPayload, ...actionPayload,
type: ACTION_SERVER_ACTION, type: ACTION_SERVER_ACTION,
mutable: {},
}) })
}) })
}, },
...@@ -189,7 +188,6 @@ function useChangeByServerResponse( ...@@ -189,7 +188,6 @@ function useChangeByServerResponse(
flightData, flightData,
previousTree, previousTree,
overrideCanonicalUrl, overrideCanonicalUrl,
mutable: {},
}) })
}) })
}, },
...@@ -209,7 +207,6 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate { ...@@ -209,7 +207,6 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
locationSearch: location.search, locationSearch: location.search,
shouldScroll: shouldScroll ?? true, shouldScroll: shouldScroll ?? true,
navigateType, navigateType,
mutable: {},
}) })
}, },
[dispatch] [dispatch]
...@@ -329,7 +326,6 @@ function Router({ ...@@ -329,7 +326,6 @@ function Router({
startTransition(() => { startTransition(() => {
dispatch({ dispatch({
type: ACTION_REFRESH, type: ACTION_REFRESH,
mutable: {},
origin: window.location.origin, origin: window.location.origin,
}) })
}) })
...@@ -344,7 +340,6 @@ function Router({ ...@@ -344,7 +340,6 @@ function Router({
startTransition(() => { startTransition(() => {
dispatch({ dispatch({
type: ACTION_FAST_REFRESH, type: ACTION_FAST_REFRESH,
mutable: {},
origin: window.location.origin, origin: window.location.origin,
}) })
}) })
......
...@@ -6,6 +6,7 @@ import type { ...@@ -6,6 +6,7 @@ import type {
ReadonlyReducerState, ReadonlyReducerState,
ReducerState, ReducerState,
FastRefreshAction, FastRefreshAction,
Mutable,
} from '../router-reducer-types' } from '../router-reducer-types'
import { handleExternalUrl } from './navigate-reducer' import { handleExternalUrl } from './navigate-reducer'
import { handleMutable } from '../handle-mutable' import { handleMutable } from '../handle-mutable'
...@@ -18,16 +19,10 @@ function fastRefreshReducerImpl( ...@@ -18,16 +19,10 @@ function fastRefreshReducerImpl(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: FastRefreshAction action: FastRefreshAction
): ReducerState { ): ReducerState {
const { mutable, origin } = action const { origin } = action
const mutable: Mutable = {}
const href = state.canonicalUrl const href = state.canonicalUrl
const isForCurrentTree =
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
if (isForCurrentTree) {
return handleMutable(state, mutable)
}
mutable.preserveCustomHistoryState = false mutable.preserveCustomHistoryState = false
const cache: CacheNode = createEmptyCacheNode() const cache: CacheNode = createEmptyCacheNode()
...@@ -102,7 +97,6 @@ function fastRefreshReducerImpl( ...@@ -102,7 +97,6 @@ function fastRefreshReducerImpl(
currentCache = cache currentCache = cache
} }
mutable.previousTree = currentTree
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.canonicalUrl = href mutable.canonicalUrl = href
......
...@@ -35,7 +35,6 @@ export function handleExternalUrl( ...@@ -35,7 +35,6 @@ export function handleExternalUrl(
url: string, url: string,
pendingPush: boolean pendingPush: boolean
) { ) {
mutable.previousTree = state.tree
mutable.mpaNavigation = true mutable.mpaNavigation = true
mutable.canonicalUrl = url mutable.canonicalUrl = url
mutable.pendingPush = pendingPush mutable.pendingPush = pendingPush
...@@ -99,20 +98,14 @@ export function navigateReducer( ...@@ -99,20 +98,14 @@ export function navigateReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: NavigateAction action: NavigateAction
): ReducerState { ): ReducerState {
const { url, isExternalUrl, navigateType, mutable, shouldScroll } = action const { url, isExternalUrl, navigateType, shouldScroll } = action
const mutable: Mutable = {}
const { hash } = url const { hash } = url
const href = createHrefFromUrl(url) const href = createHrefFromUrl(url)
const pendingPush = navigateType === 'push' const pendingPush = navigateType === 'push'
// we want to prune the prefetch cache on every navigation to avoid it growing too large // we want to prune the prefetch cache on every navigation to avoid it growing too large
prunePrefetchCache(state.prefetchCache) prunePrefetchCache(state.prefetchCache)
const isForCurrentTree =
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
if (isForCurrentTree) {
return handleMutable(state, mutable)
}
mutable.preserveCustomHistoryState = false mutable.preserveCustomHistoryState = false
if (isExternalUrl) { if (isExternalUrl) {
...@@ -277,7 +270,6 @@ export function navigateReducer( ...@@ -277,7 +270,6 @@ export function navigateReducer(
} }
} }
mutable.previousTree = state.tree
mutable.patchedTree = currentTree mutable.patchedTree = currentTree
mutable.canonicalUrl = canonicalUrlOverride mutable.canonicalUrl = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride) ? createHrefFromUrl(canonicalUrlOverride)
......
...@@ -135,7 +135,6 @@ describe('refreshReducer', () => { ...@@ -135,7 +135,6 @@ describe('refreshReducer', () => {
}) })
const action: RefreshAction = { const action: RefreshAction = {
type: ACTION_REFRESH, type: ACTION_REFRESH,
mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
...@@ -291,7 +290,6 @@ describe('refreshReducer', () => { ...@@ -291,7 +290,6 @@ describe('refreshReducer', () => {
const action: RefreshAction = { const action: RefreshAction = {
type: ACTION_REFRESH, type: ACTION_REFRESH,
mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
...@@ -473,7 +471,6 @@ describe('refreshReducer', () => { ...@@ -473,7 +471,6 @@ describe('refreshReducer', () => {
const action: RefreshAction = { const action: RefreshAction = {
type: ACTION_REFRESH, type: ACTION_REFRESH,
mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
...@@ -704,7 +701,6 @@ describe('refreshReducer', () => { ...@@ -704,7 +701,6 @@ describe('refreshReducer', () => {
const action: RefreshAction = { const action: RefreshAction = {
type: ACTION_REFRESH, type: ACTION_REFRESH,
mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
......
...@@ -3,6 +3,7 @@ import { createHrefFromUrl } from '../create-href-from-url' ...@@ -3,6 +3,7 @@ import { createHrefFromUrl } from '../create-href-from-url'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree' import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
import type { import type {
Mutable,
ReadonlyReducerState, ReadonlyReducerState,
ReducerState, ReducerState,
RefreshAction, RefreshAction,
...@@ -20,18 +21,12 @@ export function refreshReducer( ...@@ -20,18 +21,12 @@ export function refreshReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: RefreshAction action: RefreshAction
): ReducerState { ): ReducerState {
const { mutable, origin } = action const { origin } = action
const mutable: Mutable = {}
const href = state.canonicalUrl const href = state.canonicalUrl
let currentTree = state.tree let currentTree = state.tree
const isForCurrentTree =
JSON.stringify(mutable.previousTree) === JSON.stringify(currentTree)
if (isForCurrentTree) {
return handleMutable(state, mutable)
}
mutable.preserveCustomHistoryState = false mutable.preserveCustomHistoryState = false
const cache: CacheNode = createEmptyCacheNode() const cache: CacheNode = createEmptyCacheNode()
...@@ -117,7 +112,6 @@ export function refreshReducer( ...@@ -117,7 +112,6 @@ export function refreshReducer(
mutable.prefetchCache = new Map() mutable.prefetchCache = new Map()
} }
mutable.previousTree = currentTree
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.canonicalUrl = href mutable.canonicalUrl = href
......
...@@ -26,6 +26,7 @@ import type { ...@@ -26,6 +26,7 @@ import type {
ReadonlyReducerState, ReadonlyReducerState,
ReducerState, ReducerState,
ServerActionAction, ServerActionAction,
ServerActionMutable,
} from '../router-reducer-types' } from '../router-reducer-types'
import { addBasePath } from '../../../add-base-path' import { addBasePath } from '../../../add-base-path'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
...@@ -157,18 +158,12 @@ export function serverActionReducer( ...@@ -157,18 +158,12 @@ export function serverActionReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: ServerActionAction action: ServerActionAction
): ReducerState { ): ReducerState {
const { mutable, resolve, reject } = action const { resolve, reject } = action
const mutable: ServerActionMutable = {}
const href = state.canonicalUrl const href = state.canonicalUrl
let currentTree = state.tree let currentTree = state.tree
const isForCurrentTree =
JSON.stringify(mutable.previousTree) === JSON.stringify(currentTree)
if (isForCurrentTree) {
return handleMutable(state, mutable)
}
mutable.preserveCustomHistoryState = false mutable.preserveCustomHistoryState = false
mutable.inFlightServerAction = fetchServerAction(state, action) mutable.inFlightServerAction = fetchServerAction(state, action)
...@@ -183,8 +178,6 @@ export function serverActionReducer( ...@@ -183,8 +178,6 @@ export function serverActionReducer(
mutable.pendingPush = true mutable.pendingPush = true
} }
mutable.previousTree = state.tree
if (!flightData) { if (!flightData) {
if (!mutable.actionResultResolved) { if (!mutable.actionResultResolved) {
resolve(actionResult) resolve(actionResult)
...@@ -268,7 +261,6 @@ export function serverActionReducer( ...@@ -268,7 +261,6 @@ export function serverActionReducer(
mutable.prefetchCache = new Map() mutable.prefetchCache = new Map()
} }
mutable.previousTree = currentTree
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.canonicalUrl = href mutable.canonicalUrl = href
......
...@@ -79,19 +79,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [ ...@@ -79,19 +79,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [
true, true,
] ]
async function runPromiseThrowChain(fn: any): Promise<any> {
try {
return await fn()
} catch (err) {
if (err instanceof Promise) {
await err
return await runPromiseThrowChain(fn)
}
throw err
}
}
describe('serverPatchReducer', () => { describe('serverPatchReducer', () => {
beforeAll(() => { beforeAll(() => {
jest.useFakeTimers() jest.useFakeTimers()
...@@ -171,12 +158,9 @@ describe('serverPatchReducer', () => { ...@@ -171,12 +158,9 @@ describe('serverPatchReducer', () => {
true, true,
], ],
overrideCanonicalUrl: undefined, overrideCanonicalUrl: undefined,
mutable: {},
} }
const newState = await runPromiseThrowChain(() => const newState = await serverPatchReducer(state, action)
serverPatchReducer(state, action)
)
expect(newState).toMatchInlineSnapshot(` expect(newState).toMatchInlineSnapshot(`
{ {
...@@ -276,172 +260,6 @@ describe('serverPatchReducer', () => { ...@@ -276,172 +260,6 @@ describe('serverPatchReducer', () => {
`) `)
}) })
it('should apply server patch (concurrent)', async () => {
const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking'
const children = (
<html>
<head></head>
<body>Root layout</body>
</html>
)
const initialParallelRoutes: CacheNode['parallelRoutes'] = new Map([
[
'children',
new Map([
[
'linking',
{
status: CacheStates.READY,
parallelRoutes: new Map([
[
'children',
new Map([
[
'',
{
status: CacheStates.READY,
data: null,
subTreeData: <>Linking page</>,
parallelRoutes: new Map(),
},
],
]),
],
]),
data: null,
subTreeData: <>Linking layout level</>,
},
],
]),
],
])
const state = createInitialRouterState({
buildId,
initialTree,
initialHead: null,
initialCanonicalUrl,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking/about', 'https://localhost') as any,
})
const state2 = createInitialRouterState({
buildId,
initialTree,
initialHead: null,
initialCanonicalUrl,
initialSeedData: ['', null, children],
initialParallelRoutes,
isServer: false,
location: new URL('/linking/about', 'https://localhost') as any,
})
const action: ServerPatchAction = {
type: ACTION_SERVER_PATCH,
flightData: flightDataForPatch,
previousTree: [
'',
{
children: [
'linking',
{
children: ['somewhere-else', { children: ['', {}] }],
},
],
},
undefined,
undefined,
true,
],
overrideCanonicalUrl: undefined,
mutable: {},
}
await runPromiseThrowChain(() => serverPatchReducer(state, action))
const newState = await runPromiseThrowChain(() =>
serverPatchReducer(state2, action)
)
expect(newState).toMatchInlineSnapshot(`
{
"buildId": "development",
"cache": {
"data": null,
"parallelRoutes": Map {
"children" => Map {
"linking" => {
"data": null,
"parallelRoutes": Map {
"children" => Map {
"" => {
"data": null,
"parallelRoutes": Map {},
"status": "READY",
"subTreeData": <React.Fragment>
Linking page
</React.Fragment>,
},
},
},
"status": "READY",
"subTreeData": <React.Fragment>
Linking layout level
</React.Fragment>,
},
},
},
"status": "READY",
"subTreeData": <html>
<head />
<body>
Root layout
</body>
</html>,
},
"canonicalUrl": "/linking/about",
"focusAndScrollRef": {
"apply": false,
"hashFragment": null,
"onlyHashChange": false,
"segmentPaths": [],
},
"nextUrl": "/linking/about",
"prefetchCache": Map {},
"pushRef": {
"mpaNavigation": false,
"pendingPush": false,
"preserveCustomHistoryState": true,
},
"tree": [
"",
{
"children": [
"linking",
{
"children": [
"about",
{
"children": [
"",
{},
],
},
],
},
],
},
undefined,
undefined,
true,
],
}
`)
})
it('should apply server patch without affecting focusAndScrollRef', async () => { it('should apply server patch without affecting focusAndScrollRef', async () => {
const initialTree = getInitialRouterStateTree() const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking' const initialCanonicalUrl = '/linking'
...@@ -490,7 +308,6 @@ describe('serverPatchReducer', () => { ...@@ -490,7 +308,6 @@ describe('serverPatchReducer', () => {
locationSearch: '', locationSearch: '',
navigateType: 'push', navigateType: 'push',
shouldScroll: true, shouldScroll: true,
mutable: {},
} }
const state = createInitialRouterState({ const state = createInitialRouterState({
...@@ -504,9 +321,7 @@ describe('serverPatchReducer', () => { ...@@ -504,9 +321,7 @@ describe('serverPatchReducer', () => {
location: new URL(initialCanonicalUrl, 'https://localhost') as any, location: new URL(initialCanonicalUrl, 'https://localhost') as any,
}) })
const stateAfterNavigate = await runPromiseThrowChain(() => const stateAfterNavigate = await navigateReducer(state, navigateAction)
navigateReducer(state, navigateAction)
)
const action: ServerPatchAction = { const action: ServerPatchAction = {
type: ACTION_SERVER_PATCH, type: ACTION_SERVER_PATCH,
...@@ -526,12 +341,9 @@ describe('serverPatchReducer', () => { ...@@ -526,12 +341,9 @@ describe('serverPatchReducer', () => {
true, true,
], ],
overrideCanonicalUrl: undefined, overrideCanonicalUrl: undefined,
mutable: {},
} }
const newState = await runPromiseThrowChain(() => const newState = await serverPatchReducer(stateAfterNavigate, action)
serverPatchReducer(stateAfterNavigate, action)
)
expect(newState).toMatchInlineSnapshot(` expect(newState).toMatchInlineSnapshot(`
{ {
......
...@@ -5,6 +5,7 @@ import type { ...@@ -5,6 +5,7 @@ import type {
ServerPatchAction, ServerPatchAction,
ReducerState, ReducerState,
ReadonlyReducerState, ReadonlyReducerState,
Mutable,
} from '../router-reducer-types' } from '../router-reducer-types'
import { handleExternalUrl } from './navigate-reducer' import { handleExternalUrl } from './navigate-reducer'
import { applyFlightData } from '../apply-flight-data' import { applyFlightData } from '../apply-flight-data'
...@@ -16,23 +17,9 @@ export function serverPatchReducer( ...@@ -16,23 +17,9 @@ export function serverPatchReducer(
state: ReadonlyReducerState, state: ReadonlyReducerState,
action: ServerPatchAction action: ServerPatchAction
): ReducerState { ): ReducerState {
const { flightData, previousTree, overrideCanonicalUrl, mutable } = action const { flightData, overrideCanonicalUrl } = action
const isForCurrentTree = const mutable: Mutable = {}
JSON.stringify(previousTree) === JSON.stringify(state.tree)
// When a fetch is slow to resolve it could be that you navigated away while the request was happening or before the reducer runs.
// In that case opt-out of applying the patch given that the data could be stale.
if (!isForCurrentTree) {
// TODO-APP: Handle tree mismatch
console.log('TREE MISMATCH')
// Keep everything as-is.
return state
}
if (mutable.previousTree) {
return handleMutable(state, mutable)
}
mutable.preserveCustomHistoryState = false mutable.preserveCustomHistoryState = false
...@@ -85,7 +72,6 @@ export function serverPatchReducer( ...@@ -85,7 +72,6 @@ export function serverPatchReducer(
const cache: CacheNode = createEmptyCacheNode() const cache: CacheNode = createEmptyCacheNode()
applyFlightData(currentCache, cache, flightDataPath) applyFlightData(currentCache, cache, flightDataPath)
mutable.previousTree = currentTree
mutable.patchedTree = newTree mutable.patchedTree = newTree
mutable.cache = cache mutable.cache = cache
......
...@@ -28,7 +28,6 @@ export type RouterNavigate = ( ...@@ -28,7 +28,6 @@ export type RouterNavigate = (
export interface Mutable { export interface Mutable {
mpaNavigation?: boolean mpaNavigation?: boolean
previousTree?: FlightRouterState
patchedTree?: FlightRouterState patchedTree?: FlightRouterState
canonicalUrl?: string canonicalUrl?: string
scrollableSegments?: FlightSegmentPath[] scrollableSegments?: FlightSegmentPath[]
...@@ -52,13 +51,11 @@ export interface ServerActionMutable extends Mutable { ...@@ -52,13 +51,11 @@ export interface ServerActionMutable extends Mutable {
*/ */
export interface RefreshAction { export interface RefreshAction {
type: typeof ACTION_REFRESH type: typeof ACTION_REFRESH
mutable: Mutable
origin: Location['origin'] origin: Location['origin']
} }
export interface FastRefreshAction { export interface FastRefreshAction {
type: typeof ACTION_FAST_REFRESH type: typeof ACTION_FAST_REFRESH
mutable: Mutable
origin: Location['origin'] origin: Location['origin']
} }
...@@ -75,7 +72,6 @@ export interface ServerActionAction { ...@@ -75,7 +72,6 @@ export interface ServerActionAction {
actionArgs: any[] actionArgs: any[]
resolve: (value: any) => void resolve: (value: any) => void
reject: (reason?: any) => void reject: (reason?: any) => void
mutable: ServerActionMutable
} }
/** /**
...@@ -115,7 +111,6 @@ export interface NavigateAction { ...@@ -115,7 +111,6 @@ export interface NavigateAction {
locationSearch: Location['search'] locationSearch: Location['search']
navigateType: 'push' | 'replace' navigateType: 'push' | 'replace'
shouldScroll: boolean shouldScroll: boolean
mutable: Mutable
} }
/** /**
...@@ -141,7 +136,6 @@ export interface ServerPatchAction { ...@@ -141,7 +136,6 @@ export interface ServerPatchAction {
flightData: FlightData flightData: FlightData
previousTree: FlightRouterState previousTree: FlightRouterState
overrideCanonicalUrl: URL | undefined overrideCanonicalUrl: URL | undefined
mutable: Mutable
} }
/** /**
......
...@@ -80,7 +80,6 @@ async function runAction({ ...@@ -80,7 +80,6 @@ async function runAction({
actionQueue.dispatch( actionQueue.dispatch(
{ {
type: ACTION_REFRESH, type: ACTION_REFRESH,
mutable: {},
origin: window.location.origin, origin: window.location.origin,
}, },
setState setState
......
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