Unverified Commit 85abc48c authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

suspend in render, not in reducers (#56497)

This removes our current convention of throwing promises in reducers in
favor of returning promises that can be consumed by `use` instead. This
will help unblock some future improvements (batching, PPR)

Reducers that would typically throw a promise now return their promise.
This gets maintained by a mutable queue (initialized in hydrate) to
ensure actions are processed in-order. The queue is also responsible for
mutating state and passing it as an input to subsequent actions.

This PR does not modify reducer behavior to keep changes minimal, but
there's more cleanup that we can do in a follow-up PR to remove things
that previously assumed reducers would be replayed.

(I recommend reviewing with whitespace turned off)

---------
Co-authored-by: 's avatarTim Neutkens <tim@timneutkens.nl>
parent be618048
...@@ -12,6 +12,10 @@ import { GlobalLayoutRouterContext } from '../shared/lib/app-router-context.shar ...@@ -12,6 +12,10 @@ import { GlobalLayoutRouterContext } from '../shared/lib/app-router-context.shar
import onRecoverableError from './on-recoverable-error' import onRecoverableError from './on-recoverable-error'
import { callServer } from './app-call-server' import { callServer } from './app-call-server'
import { isNextRouterError } from './components/is-next-router-error' import { isNextRouterError } from './components/is-next-router-error'
import {
ActionQueueContext,
createMutableActionQueue,
} from '../shared/lib/router/action-queue'
// Since React doesn't call onerror for errors caught in error boundaries. // Since React doesn't call onerror for errors caught in error boundaries.
const origConsoleError = window.console.error const origConsoleError = window.console.error
...@@ -222,6 +226,8 @@ export function hydrate() { ...@@ -222,6 +226,8 @@ export function hydrate() {
} }
} }
const actionQueue = createMutableActionQueue()
const reactEl = ( const reactEl = (
<StrictModeIfEnabled> <StrictModeIfEnabled>
<HeadManagerContext.Provider <HeadManagerContext.Provider
...@@ -229,9 +235,11 @@ export function hydrate() { ...@@ -229,9 +235,11 @@ export function hydrate() {
appDir: true, appDir: true,
}} }}
> >
<Root> <ActionQueueContext.Provider value={actionQueue}>
<RSCComponent /> <Root>
</Root> <RSCComponent />
</Root>
</ActionQueueContext.Provider>
</HeadManagerContext.Provider> </HeadManagerContext.Provider>
</StrictModeIfEnabled> </StrictModeIfEnabled>
) )
......
...@@ -24,7 +24,6 @@ import type { ...@@ -24,7 +24,6 @@ import type {
FlightData, FlightData,
} from '../../server/app-render/types' } from '../../server/app-render/types'
import type { ErrorComponent } from './error-boundary' import type { ErrorComponent } from './error-boundary'
import { reducer } from './router-reducer/router-reducer'
import { import {
ACTION_FAST_REFRESH, ACTION_FAST_REFRESH,
ACTION_NAVIGATE, ACTION_NAVIGATE,
...@@ -36,7 +35,6 @@ import { ...@@ -36,7 +35,6 @@ import {
PrefetchKind, PrefetchKind,
} from './router-reducer/router-reducer-types' } from './router-reducer/router-reducer-types'
import type { import type {
Mutable,
ReducerActions, ReducerActions,
RouterChangeByServerResponse, RouterChangeByServerResponse,
RouterNavigate, RouterNavigate,
...@@ -47,7 +45,10 @@ import { ...@@ -47,7 +45,10 @@ import {
SearchParamsContext, SearchParamsContext,
PathnameContext, PathnameContext,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { useReducerWithReduxDevtools } from './use-reducer-with-devtools' import {
useReducerWithReduxDevtools,
useUnwrapState,
} from './use-reducer-with-devtools'
import { ErrorBoundary } from './error-boundary' import { ErrorBoundary } from './error-boundary'
import { createInitialRouterState } from './router-reducer/create-initial-router-state' import { createInitialRouterState } from './router-reducer/create-initial-router-state'
import type { InitialRouterStateParameters } from './router-reducer/create-initial-router-state' import type { InitialRouterStateParameters } from './router-reducer/create-initial-router-state'
...@@ -73,9 +74,9 @@ export function getServerActionDispatcher() { ...@@ -73,9 +74,9 @@ export function getServerActionDispatcher() {
return globalServerActionDispatcher return globalServerActionDispatcher
} }
let globalMutable: Mutable['globalMutable'] = { const globalMutable: {
refresh: () => {}, // noop until the router is initialized pendingMpaPath?: string
} } = {}
export function urlToUrlWithoutFlightMarker(url: string): URL { export function urlToUrlWithoutFlightMarker(url: string): URL {
const urlWithoutFlightParameters = new URL(url, location.origin) const urlWithoutFlightParameters = new URL(url, location.origin)
...@@ -131,7 +132,7 @@ function HistoryUpdater({ tree, pushRef, canonicalUrl, sync }: any) { ...@@ -131,7 +132,7 @@ function HistoryUpdater({ tree, pushRef, canonicalUrl, sync }: any) {
return null return null
} }
const createEmptyCacheNode = () => ({ export const createEmptyCacheNode = () => ({
status: CacheStates.LAZY_INITIALIZED, status: CacheStates.LAZY_INITIALIZED,
data: null, data: null,
subTreeData: null, subTreeData: null,
...@@ -145,7 +146,7 @@ function useServerActionDispatcher(dispatch: React.Dispatch<ReducerActions>) { ...@@ -145,7 +146,7 @@ function useServerActionDispatcher(dispatch: React.Dispatch<ReducerActions>) {
dispatch({ dispatch({
...actionPayload, ...actionPayload,
type: ACTION_SERVER_ACTION, type: ACTION_SERVER_ACTION,
mutable: { globalMutable }, mutable: {},
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
}) })
}) })
...@@ -174,7 +175,7 @@ function useChangeByServerResponse( ...@@ -174,7 +175,7 @@ function useChangeByServerResponse(
previousTree, previousTree,
overrideCanonicalUrl, overrideCanonicalUrl,
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
mutable: { globalMutable }, mutable: {},
}) })
}) })
}, },
...@@ -186,7 +187,6 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate { ...@@ -186,7 +187,6 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
return useCallback( return useCallback(
(href, navigateType, forceOptimisticNavigation, shouldScroll) => { (href, navigateType, forceOptimisticNavigation, shouldScroll) => {
const url = new URL(addBasePath(href), location.href) const url = new URL(addBasePath(href), location.href)
globalMutable.pendingNavigatePath = createHrefFromUrl(url)
return dispatch({ return dispatch({
type: ACTION_NAVIGATE, type: ACTION_NAVIGATE,
...@@ -197,7 +197,7 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate { ...@@ -197,7 +197,7 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
shouldScroll: shouldScroll ?? true, shouldScroll: shouldScroll ?? true,
navigateType, navigateType,
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
mutable: { globalMutable }, mutable: {},
}) })
}, },
[dispatch] [dispatch]
...@@ -229,25 +229,15 @@ function Router({ ...@@ -229,25 +229,15 @@ function Router({
}), }),
[buildId, children, initialCanonicalUrl, initialTree, initialHead] [buildId, children, initialCanonicalUrl, initialTree, initialHead]
) )
const [ const [reducerState, dispatch, sync] =
{ useReducerWithReduxDevtools(initialState)
tree,
cache,
prefetchCache,
pushRef,
focusAndScrollRef,
canonicalUrl,
nextUrl,
},
dispatch,
sync,
] = useReducerWithReduxDevtools(reducer, initialState)
useEffect(() => { useEffect(() => {
// Ensure initialParallelRoutes is cleaned up from memory once it's used. // Ensure initialParallelRoutes is cleaned up from memory once it's used.
initialParallelRoutes = null! initialParallelRoutes = null!
}, []) }, [])
const { canonicalUrl } = useUnwrapState(reducerState)
// Add memoized pathname/query for useSearchParams and usePathname. // Add memoized pathname/query for useSearchParams and usePathname.
const { searchParams, pathname } = useMemo(() => { const { searchParams, pathname } = useMemo(() => {
const url = new URL( const url = new URL(
...@@ -322,7 +312,7 @@ function Router({ ...@@ -322,7 +312,7 @@ function Router({
dispatch({ dispatch({
type: ACTION_REFRESH, type: ACTION_REFRESH,
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
mutable: { globalMutable }, mutable: {},
origin: window.location.origin, origin: window.location.origin,
}) })
}) })
...@@ -338,7 +328,7 @@ function Router({ ...@@ -338,7 +328,7 @@ function Router({
dispatch({ dispatch({
type: ACTION_FAST_REFRESH, type: ACTION_FAST_REFRESH,
cache: createEmptyCacheNode(), cache: createEmptyCacheNode(),
mutable: { globalMutable }, mutable: {},
origin: window.location.origin, origin: window.location.origin,
}) })
}) })
...@@ -356,11 +346,10 @@ function Router({ ...@@ -356,11 +346,10 @@ function Router({
} }
}, [appRouter]) }, [appRouter])
useEffect(() => {
globalMutable.refresh = appRouter.refresh
}, [appRouter.refresh])
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { cache, prefetchCache, tree } = useUnwrapState(reducerState)
// This hook is in a conditional but that is ok because `process.env.NODE_ENV` never changes // This hook is in a conditional but that is ok because `process.env.NODE_ENV` never changes
// eslint-disable-next-line react-hooks/rules-of-hooks // eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => { useEffect(() => {
...@@ -408,6 +397,7 @@ function Router({ ...@@ -408,6 +397,7 @@ function Router({
// probably safe because we know this is a singleton component and it's never // probably safe because we know this is a singleton component and it's never
// in <Offscreen>. At least I hope so. (It will run twice in dev strict mode, // in <Offscreen>. At least I hope so. (It will run twice in dev strict mode,
// but that's... fine?) // but that's... fine?)
const { pushRef } = useUnwrapState(reducerState)
if (pushRef.mpaNavigation) { if (pushRef.mpaNavigation) {
// if there's a re-render, we don't want to trigger another redirect if one is already in flight to the same URL // if there's a re-render, we don't want to trigger another redirect if one is already in flight to the same URL
if (globalMutable.pendingMpaPath !== canonicalUrl) { if (globalMutable.pendingMpaPath !== canonicalUrl) {
...@@ -466,6 +456,9 @@ function Router({ ...@@ -466,6 +456,9 @@ function Router({
} }
}, [onPopState]) }, [onPopState])
const { cache, tree, nextUrl, focusAndScrollRef } =
useUnwrapState(reducerState)
const head = useMemo(() => { const head = useMemo(() => {
return findHeadInCache(cache, tree[1]) return findHeadInCache(cache, tree[1])
}, [cache, tree]) }, [cache, tree])
...@@ -513,7 +506,7 @@ function Router({ ...@@ -513,7 +506,7 @@ function Router({
<LayoutRouterContext.Provider <LayoutRouterContext.Provider
value={{ value={{
childNodes: cache.parallelRoutes, childNodes: cache.parallelRoutes,
tree: tree, tree,
// Root node always has `url` // Root node always has `url`
// Provided in AppTreeContext to ensure it can be overwritten in layout-router // Provided in AppTreeContext to ensure it can be overwritten in layout-router
url: canonicalUrl, url: canonicalUrl,
......
import { readRecordValue } from './read-record-value'
import { createRecordFromThenable } from './create-record-from-thenable'
describe('readRecordValue', () => {
it('successful promise', async () => {
const thenable = Promise.resolve('success')
const record = createRecordFromThenable(thenable)
expect(() => readRecordValue(record)).toThrow()
await thenable
expect(readRecordValue(record)).toBe('success')
})
it('rejecting promise', async () => {
const thenable = Promise.reject('failed')
const record = createRecordFromThenable(thenable)
expect(() => readRecordValue(record)).toThrow()
await thenable.catch(() => {})
expect(() => readRecordValue(record)).toThrow()
const result: any = (() => {
try {
return readRecordValue(record)
} catch (err) {
return err
}
})()
expect(result.status).toBe('rejected')
expect(result.reason).toBe('failed')
})
})
import type { ThenableRecord } from './router-reducer-types'
/**
* Read record value or throw Promise if it's not resolved yet.
*/
export function readRecordValue<T>(thenable: ThenableRecord<T>): T {
if (thenable.status === 'fulfilled') {
return thenable.value
} else {
throw thenable
}
}
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable' import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url' 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'
...@@ -40,70 +39,79 @@ function fastRefreshReducerImpl( ...@@ -40,70 +39,79 @@ function fastRefreshReducerImpl(
) )
) )
} }
const [flightData, canonicalUrlOverride] = readRecordValue(cache.data!)
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return handleExternalUrl(
state,
mutable,
flightData,
state.pushRef.pendingPush
)
}
// Remove cache.data as it has been resolved at this point.
cache.data = null
let currentTree = state.tree
let currentCache = state.cache
for (const flightDataPath of flightData) {
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log('REFRESH FAILED')
return state
}
// Given the path can only have two items the items are only the router state and subTreeData for the root.
const [treePatch] = flightDataPath
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
[''],
currentTree,
treePatch
)
if (newTree === null) {
throw new Error('SEGMENT MISMATCH')
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, state.pushRef.pendingPush)
}
const canonicalUrlOverrideHref = canonicalUrlOverride return cache.data.then(
? createHrefFromUrl(canonicalUrlOverride) ([flightData, canonicalUrlOverride]) => {
: undefined // Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
if (canonicalUrlOverride) { return handleExternalUrl(
mutable.canonicalUrl = canonicalUrlOverrideHref state,
} mutable,
const applied = applyFlightData(currentCache, cache, flightDataPath) flightData,
state.pushRef.pendingPush
if (applied) { )
mutable.cache = cache }
currentCache = cache
} // Remove cache.data as it has been resolved at this point.
cache.data = null
mutable.previousTree = currentTree
mutable.patchedTree = newTree let currentTree = state.tree
mutable.canonicalUrl = href let currentCache = state.cache
currentTree = newTree for (const flightDataPath of flightData) {
} // FlightDataPath with more than two items means unexpected Flight data was returned
return handleMutable(state, mutable) if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log('REFRESH FAILED')
return state
}
// Given the path can only have two items the items are only the router state and subTreeData for the root.
const [treePatch] = flightDataPath
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
[''],
currentTree,
treePatch
)
if (newTree === null) {
throw new Error('SEGMENT MISMATCH')
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(
state,
mutable,
href,
state.pushRef.pendingPush
)
}
const canonicalUrlOverrideHref = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride)
: undefined
if (canonicalUrlOverride) {
mutable.canonicalUrl = canonicalUrlOverrideHref
}
const applied = applyFlightData(currentCache, cache, flightDataPath)
if (applied) {
mutable.cache = cache
currentCache = cache
}
mutable.previousTree = currentTree
mutable.patchedTree = newTree
mutable.canonicalUrl = href
currentTree = newTree
}
return handleMutable(state, mutable)
},
() => state
)
} }
function fastRefreshReducerNoop( function fastRefreshReducerNoop(
......
...@@ -102,10 +102,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [ ...@@ -102,10 +102,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [
true, true,
] ]
const globalMutable = {
refresh: () => {},
}
async function runPromiseThrowChain(fn: any): Promise<any> { async function runPromiseThrowChain(fn: any): Promise<any> {
try { try {
return await fn() return await fn()
...@@ -194,7 +190,7 @@ describe('navigateReducer', () => { ...@@ -194,7 +190,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
const newState = await runPromiseThrowChain(() => const newState = await runPromiseThrowChain(() =>
...@@ -438,7 +434,7 @@ describe('navigateReducer', () => { ...@@ -438,7 +434,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -633,7 +629,7 @@ describe('navigateReducer', () => { ...@@ -633,7 +629,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -792,7 +788,7 @@ describe('navigateReducer', () => { ...@@ -792,7 +788,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -948,7 +944,7 @@ describe('navigateReducer', () => { ...@@ -948,7 +944,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -1147,7 +1143,7 @@ describe('navigateReducer', () => { ...@@ -1147,7 +1143,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -1317,7 +1313,7 @@ describe('navigateReducer', () => { ...@@ -1317,7 +1313,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -1630,7 +1626,7 @@ describe('navigateReducer', () => { ...@@ -1630,7 +1626,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => navigateReducer(state, action)) await runPromiseThrowChain(() => navigateReducer(state, action))
...@@ -1841,7 +1837,6 @@ describe('navigateReducer', () => { ...@@ -1841,7 +1837,6 @@ describe('navigateReducer', () => {
hashFragment: '#hash', hashFragment: '#hash',
pendingPush: true, pendingPush: true,
shouldScroll: true, shouldScroll: true,
globalMutable,
}, },
} }
...@@ -1984,7 +1979,7 @@ describe('navigateReducer', () => { ...@@ -1984,7 +1979,7 @@ describe('navigateReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
const newState = await runPromiseThrowChain(() => const newState = await runPromiseThrowChain(() =>
......
...@@ -7,7 +7,6 @@ import type { ...@@ -7,7 +7,6 @@ import type {
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import type { FetchServerResponseResult } from '../fetch-server-response' import type { FetchServerResponseResult } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable' import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url' import { createHrefFromUrl } from '../create-href-from-url'
import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath' import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath'
import { fillCacheWithDataProperty } from '../fill-cache-with-data-property' import { fillCacheWithDataProperty } from '../fill-cache-with-data-property'
...@@ -248,139 +247,140 @@ export function navigateReducer( ...@@ -248,139 +247,140 @@ export function navigateReducer(
prefetchQueue.bump(data!) prefetchQueue.bump(data!)
// Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves. return data!.then(
const [flightData, canonicalUrlOverride, postponed] = readRecordValue(data!) ([flightData, canonicalUrlOverride, postponed]) => {
// we only want to mark this once
if (prefetchValues && !prefetchValues.lastUsedTime) {
// important: we should only mark the cache node as dirty after we unsuspend from the call above
prefetchValues.lastUsedTime = Date.now()
}
// we only want to mark this once // Handle case when navigating to page in `pages` from `app`
if (!prefetchValues.lastUsedTime) { if (typeof flightData === 'string') {
// important: we should only mark the cache node as dirty after we unsuspend from the call above return handleExternalUrl(state, mutable, flightData, pendingPush)
prefetchValues.lastUsedTime = Date.now() }
}
// Handle case when navigating to page in `pages` from `app` let currentTree = state.tree
if (typeof flightData === 'string') { let currentCache = state.cache
return handleExternalUrl(state, mutable, flightData, pendingPush) let scrollableSegments: FlightSegmentPath[] = []
} for (const flightDataPath of flightData) {
const flightSegmentPath = flightDataPath.slice(
0,
-4
) as unknown as FlightSegmentPath
// The one before last item is the router state tree patch
const treePatch = flightDataPath.slice(-3)[0] as FlightRouterState
let currentTree = state.tree
let currentCache = state.cache
let scrollableSegments: FlightSegmentPath[] = []
for (const flightDataPath of flightData) {
const flightSegmentPath = flightDataPath.slice(
0,
-4
) as unknown as FlightSegmentPath
// The one before last item is the router state tree patch
const treePatch = flightDataPath.slice(-3)[0] as FlightRouterState
// TODO-APP: remove ''
const flightSegmentPathWithLeadingEmpty = ['', ...flightSegmentPath]
// Create new tree based on the flightSegmentPath and router state patch
let newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty,
currentTree,
treePatch
)
// If the tree patch can't be applied to the current tree then we use the tree at time of prefetch
// TODO-APP: This should instead fill in the missing pieces in `currentTree` with the data from `treeAtTimeOfPrefetch`, then apply the patch.
if (newTree === null) {
newTree = applyRouterStatePatchToTree(
// TODO-APP: remove '' // TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, const flightSegmentPathWithLeadingEmpty = ['', ...flightSegmentPath]
treeAtTimeOfPrefetch,
treePatch // Create new tree based on the flightSegmentPath and router state patch
) let newTree = applyRouterStatePatchToTree(
} // TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty,
currentTree,
treePatch
)
if (newTree !== null) { // If the tree patch can't be applied to the current tree then we use the tree at time of prefetch
if (isNavigatingToNewRootLayout(currentTree, newTree)) { // TODO-APP: This should instead fill in the missing pieces in `currentTree` with the data from `treeAtTimeOfPrefetch`, then apply the patch.
return handleExternalUrl(state, mutable, href, pendingPush) if (newTree === null) {
} newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty,
treeAtTimeOfPrefetch,
treePatch
)
}
if (newTree !== null) {
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
// TODO-APP: If the prefetch was postponed, we don't want to apply it let applied = applyFlightData(
// until we land router changes to handle the postponed case.
let applied = postponed
? false
: applyFlightData(
currentCache, currentCache,
cache, cache,
flightDataPath, flightDataPath,
prefetchValues.kind === 'auto' && prefetchValues?.kind === 'auto' &&
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable
) )
if ( if (
!applied && (!applied &&
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.stale prefetchEntryCacheStatus === PrefetchCacheEntryStatus.stale) ||
) { // TODO-APP: If the prefetch was postponed, we don't want to apply it
applied = addRefetchToLeafSegments( // until we land router changes to handle the postponed case.
cache, postponed
currentCache, ) {
flightSegmentPath, applied = addRefetchToLeafSegments(
treePatch, cache,
// eslint-disable-next-line no-loop-func currentCache,
() => flightSegmentPath,
createRecordFromThenable( treePatch,
fetchServerResponse( // eslint-disable-next-line no-loop-func
url, () =>
currentTree, createRecordFromThenable(
state.nextUrl, fetchServerResponse(
state.buildId url,
) currentTree,
state.nextUrl,
state.buildId
)
)
) )
) }
}
const hardNavigate = shouldHardNavigate( const hardNavigate = shouldHardNavigate(
// TODO-APP: remove '' // TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty, flightSegmentPathWithLeadingEmpty,
currentTree currentTree
) )
if (hardNavigate) {
cache.status = CacheStates.READY
// Copy subTreeData for the root node of the cache.
cache.subTreeData = currentCache.subTreeData
invalidateCacheBelowFlightSegmentPath( if (hardNavigate) {
cache, cache.status = CacheStates.READY
currentCache, // Copy subTreeData for the root node of the cache.
flightSegmentPath cache.subTreeData = currentCache.subTreeData
)
// Ensure the existing cache value is used when the cache was not invalidated.
mutable.cache = cache
} else if (applied) {
mutable.cache = cache
}
currentCache = cache invalidateCacheBelowFlightSegmentPath(
currentTree = newTree cache,
currentCache,
for (const subSegment of generateSegmentsFromPatch(treePatch)) { flightSegmentPath
const scrollableSegmentPath = [...flightSegmentPath, ...subSegment] )
// Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case. // Ensure the existing cache value is used when the cache was not invalidated.
if ( mutable.cache = cache
scrollableSegmentPath[scrollableSegmentPath.length - 1] !== } else if (applied) {
'__DEFAULT__' mutable.cache = cache
) { }
scrollableSegments.push(scrollableSegmentPath)
currentCache = cache
currentTree = newTree
for (const subSegment of generateSegmentsFromPatch(treePatch)) {
const scrollableSegmentPath = [...flightSegmentPath, ...subSegment]
// Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case.
if (
scrollableSegmentPath[scrollableSegmentPath.length - 1] !==
'__DEFAULT__'
) {
scrollableSegments.push(scrollableSegmentPath)
}
}
} }
} }
}
}
mutable.previousTree = state.tree mutable.previousTree = state.tree
mutable.patchedTree = currentTree mutable.patchedTree = currentTree
mutable.canonicalUrl = canonicalUrlOverride mutable.canonicalUrl = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride) ? createHrefFromUrl(canonicalUrlOverride)
: href : href
mutable.pendingPush = pendingPush mutable.pendingPush = pendingPush
mutable.scrollableSegments = scrollableSegments mutable.scrollableSegments = scrollableSegments
mutable.hashFragment = hash mutable.hashFragment = hash
mutable.shouldScroll = shouldScroll mutable.shouldScroll = shouldScroll
return handleMutable(state, mutable) return handleMutable(state, mutable)
},
() => state
)
} }
import type { ReducerState } from '../router-reducer-types' import type { AppRouterState } from '../router-reducer-types'
import { import {
PrefetchCacheEntryStatus, PrefetchCacheEntryStatus,
getPrefetchEntryCacheStatus, getPrefetchEntryCacheStatus,
} from '../get-prefetch-cache-entry-status' } from '../get-prefetch-cache-entry-status'
export function prunePrefetchCache( export function prunePrefetchCache(
prefetchCache: ReducerState['prefetchCache'] prefetchCache: AppRouterState['prefetchCache']
) { ) {
for (const [href, prefetchCacheEntry] of prefetchCache) { for (const [href, prefetchCacheEntry] of prefetchCache) {
if ( if (
......
...@@ -64,10 +64,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [ ...@@ -64,10 +64,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [
true, true,
] ]
const globalMutable = {
refresh: () => {},
}
async function runPromiseThrowChain(fn: any): Promise<any> { async function runPromiseThrowChain(fn: any): Promise<any> {
try { try {
return await fn() return await fn()
...@@ -141,7 +137,7 @@ describe('refreshReducer', () => { ...@@ -141,7 +137,7 @@ describe('refreshReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
...@@ -302,7 +298,7 @@ describe('refreshReducer', () => { ...@@ -302,7 +298,7 @@ describe('refreshReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
...@@ -489,7 +485,7 @@ describe('refreshReducer', () => { ...@@ -489,7 +485,7 @@ describe('refreshReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
...@@ -725,7 +721,7 @@ describe('refreshReducer', () => { ...@@ -725,7 +721,7 @@ describe('refreshReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
origin: new URL('/linking', 'https://localhost').origin, origin: new URL('/linking', 'https://localhost').origin,
} }
......
import { fetchServerResponse } from '../fetch-server-response' import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable' import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url' 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'
...@@ -42,78 +41,87 @@ export function refreshReducer( ...@@ -42,78 +41,87 @@ export function refreshReducer(
) )
) )
} }
const [flightData, canonicalUrlOverride] = readRecordValue(cache.data!)
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return handleExternalUrl(
state,
mutable,
flightData,
state.pushRef.pendingPush
)
}
// Remove cache.data as it has been resolved at this point.
cache.data = null
for (const flightDataPath of flightData) {
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log('REFRESH FAILED')
return state
}
// Given the path can only have two items the items are only the router state and subTreeData for the root.
const [treePatch] = flightDataPath
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
[''],
currentTree,
treePatch
)
if (newTree === null) {
throw new Error('SEGMENT MISMATCH')
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, state.pushRef.pendingPush)
}
const canonicalUrlOverrideHref = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride)
: undefined
if (canonicalUrlOverride) {
mutable.canonicalUrl = canonicalUrlOverrideHref
}
// The one before last item is the router state tree patch
const [subTreeData, head] = flightDataPath.slice(-2)
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData !== null) {
cache.status = CacheStates.READY
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(
cache,
// Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined,
treePatch,
head
)
mutable.cache = cache
mutable.prefetchCache = new Map()
}
mutable.previousTree = currentTree
mutable.patchedTree = newTree
mutable.canonicalUrl = href
currentTree = newTree
}
return handleMutable(state, mutable) return cache.data.then(
([flightData, canonicalUrlOverride]) => {
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return handleExternalUrl(
state,
mutable,
flightData,
state.pushRef.pendingPush
)
}
// Remove cache.data as it has been resolved at this point.
cache.data = null
for (const flightDataPath of flightData) {
// FlightDataPath with more than two items means unexpected Flight data was returned
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better
console.log('REFRESH FAILED')
return state
}
// Given the path can only have two items the items are only the router state and subTreeData for the root.
const [treePatch] = flightDataPath
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
[''],
currentTree,
treePatch
)
if (newTree === null) {
throw new Error('SEGMENT MISMATCH')
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(
state,
mutable,
href,
state.pushRef.pendingPush
)
}
const canonicalUrlOverrideHref = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride)
: undefined
if (canonicalUrlOverride) {
mutable.canonicalUrl = canonicalUrlOverrideHref
}
// The one before last item is the router state tree patch
const [subTreeData, head] = flightDataPath.slice(-2)
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData !== null) {
cache.status = CacheStates.READY
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(
cache,
// Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined,
treePatch,
head
)
mutable.cache = cache
mutable.prefetchCache = new Map()
}
mutable.previousTree = currentTree
mutable.patchedTree = newTree
mutable.canonicalUrl = href
currentTree = newTree
}
return handleMutable(state, mutable)
},
() => state
)
} }
...@@ -11,7 +11,6 @@ import { ...@@ -11,7 +11,6 @@ import {
RSC_CONTENT_TYPE_HEADER, RSC_CONTENT_TYPE_HEADER,
} from '../../app-router-headers' } from '../../app-router-headers'
import { createRecordFromThenable } from '../create-record-from-thenable' import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
// // eslint-disable-next-line import/no-extraneous-dependencies // // eslint-disable-next-line import/no-extraneous-dependencies
// import { createFromFetch } from 'react-server-dom-webpack/client' // import { createFromFetch } from 'react-server-dom-webpack/client'
// // eslint-disable-next-line import/no-extraneous-dependencies // // eslint-disable-next-line import/no-extraneous-dependencies
...@@ -159,164 +158,132 @@ export function serverActionReducer( ...@@ -159,164 +158,132 @@ export function serverActionReducer(
return handleMutable(state, mutable) return handleMutable(state, mutable)
} }
if (mutable.inFlightServerAction) { mutable.inFlightServerAction = createRecordFromThenable(
// unblock if a navigation event comes through fetchServerAction(state, action)
// while we've suspended on an action )
if (
mutable.inFlightServerAction.status !== 'fulfilled' &&
mutable.globalMutable.pendingNavigatePath &&
mutable.globalMutable.pendingNavigatePath !== href
) {
mutable.inFlightServerAction.then(
() => {
if (mutable.actionResultResolved) return
// if the server action resolves after a navigation took place,
// reset ServerActionMutable values & trigger a refresh so that any stale data gets updated
mutable.inFlightServerAction = null
mutable.globalMutable.pendingNavigatePath = undefined
mutable.globalMutable.refresh()
mutable.actionResultResolved = true
},
() => {}
)
return state
}
} else {
mutable.inFlightServerAction = createRecordFromThenable(
fetchServerAction(state, action)
)
}
// TODO-APP: Make try/catch wrap only readRecordValue so that other errors bubble up through the reducer instead.
try {
// suspends until the server action is resolved.
const {
actionResult,
actionFlightData: flightData,
redirectLocation,
// revalidatedParts,
} = readRecordValue(
mutable.inFlightServerAction!
) as Awaited<FetchServerActionResult>
// Make sure the redirection is a push instead of a replace.
// Issue: https://github.com/vercel/next.js/issues/53911
if (redirectLocation) {
state.pushRef.pendingPush = true
mutable.pendingPush = true
}
mutable.previousTree = state.tree
if (!flightData) { // suspends until the server action is resolved.
if (!mutable.actionResultResolved) {
resolve(actionResult)
mutable.actionResultResolved = true
}
// If there is a redirect but no flight data we need to do a mpaNavigation. return mutable.inFlightServerAction.then(
({ actionResult, actionFlightData: flightData, redirectLocation }) => {
// Make sure the redirection is a push instead of a replace.
// Issue: https://github.com/vercel/next.js/issues/53911
if (redirectLocation) { if (redirectLocation) {
return handleExternalUrl( state.pushRef.pendingPush = true
state, mutable.pendingPush = true
mutable,
redirectLocation.href,
state.pushRef.pendingPush
)
} }
return state
}
if (typeof flightData === 'string') { mutable.previousTree = state.tree
// Handle case when navigating to page in `pages` from `app`
return handleExternalUrl(
state,
mutable,
flightData,
state.pushRef.pendingPush
)
}
// Remove cache.data as it has been resolved at this point. if (!flightData) {
mutable.inFlightServerAction = null if (!mutable.actionResultResolved) {
resolve(actionResult)
for (const flightDataPath of flightData) { mutable.actionResultResolved = true
// FlightDataPath with more than two items means unexpected Flight data was returned }
if (flightDataPath.length !== 3) {
// TODO-APP: handle this case better // If there is a redirect but no flight data we need to do a mpaNavigation.
console.log('SERVER ACTION APPLY FAILED') if (redirectLocation) {
return handleExternalUrl(
state,
mutable,
redirectLocation.href,
state.pushRef.pendingPush
)
}
return state return state
} }
// Given the path can only have two items the items are only the router state and subTreeData for the root. if (typeof flightData === 'string') {
const [treePatch] = flightDataPath // Handle case when navigating to page in `pages` from `app`
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
[''],
currentTree,
treePatch
)
if (newTree === null) {
throw new Error('SEGMENT MISMATCH')
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl( return handleExternalUrl(
state, state,
mutable, mutable,
href, flightData,
state.pushRef.pendingPush state.pushRef.pendingPush
) )
} }
// The one before last item is the router state tree patch // Remove cache.data as it has been resolved at this point.
const [subTreeData, head] = flightDataPath.slice(-2) mutable.inFlightServerAction = null
// Handles case where prefetch only returns the router tree patch without rendered components. for (const flightDataPath of flightData) {
if (subTreeData !== null) { // FlightDataPath with more than two items means unexpected Flight data was returned
cache.status = CacheStates.READY if (flightDataPath.length !== 3) {
cache.subTreeData = subTreeData // TODO-APP: handle this case better
fillLazyItemsTillLeafWithHead( console.log('SERVER ACTION APPLY FAILED')
cache, return state
// Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache. }
undefined,
treePatch, // Given the path can only have two items the items are only the router state and subTreeData for the root.
head const [treePatch] = flightDataPath
const newTree = applyRouterStatePatchToTree(
// TODO-APP: remove ''
[''],
currentTree,
treePatch
) )
mutable.cache = cache
mutable.prefetchCache = new Map()
}
mutable.previousTree = currentTree
mutable.patchedTree = newTree
mutable.canonicalUrl = href
currentTree = newTree if (newTree === null) {
} throw new Error('SEGMENT MISMATCH')
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(
state,
mutable,
href,
state.pushRef.pendingPush
)
}
// The one before last item is the router state tree patch
const [subTreeData, head] = flightDataPath.slice(-2)
// Handles case where prefetch only returns the router tree patch without rendered components.
if (subTreeData !== null) {
cache.status = CacheStates.READY
cache.subTreeData = subTreeData
fillLazyItemsTillLeafWithHead(
cache,
// Existing cache is not passed in as `router.refresh()` has to invalidate the entire cache.
undefined,
treePatch,
head
)
mutable.cache = cache
mutable.prefetchCache = new Map()
}
mutable.previousTree = currentTree
mutable.patchedTree = newTree
mutable.canonicalUrl = href
currentTree = newTree
}
if (redirectLocation) { if (redirectLocation) {
const newHref = createHrefFromUrl(redirectLocation, false) const newHref = createHrefFromUrl(redirectLocation, false)
mutable.canonicalUrl = newHref mutable.canonicalUrl = newHref
} }
if (!mutable.actionResultResolved) {
resolve(actionResult)
mutable.actionResultResolved = true
}
return handleMutable(state, mutable)
} catch (e: any) {
if (e.status === 'rejected') {
if (!mutable.actionResultResolved) { if (!mutable.actionResultResolved) {
reject(e.reason) resolve(actionResult)
mutable.actionResultResolved = true mutable.actionResultResolved = true
} }
return handleMutable(state, mutable)
},
(e: any) => {
if (e.status === 'rejected') {
if (!mutable.actionResultResolved) {
reject(e.reason)
mutable.actionResultResolved = true
}
// When the server action is rejected we don't update the state and instead call the reject handler of the promise. // When the server action is rejected we don't update the state and instead call the reject handler of the promise.
return state return state
} }
throw e throw e
} }
)
} }
...@@ -13,10 +13,6 @@ import { navigateReducer } from './navigate-reducer' ...@@ -13,10 +13,6 @@ import { navigateReducer } from './navigate-reducer'
import { serverPatchReducer } from './server-patch-reducer' import { serverPatchReducer } from './server-patch-reducer'
const buildId = 'development' const buildId = 'development'
const globalMutable = {
refresh: () => {},
}
jest.mock('../fetch-server-response', () => { jest.mock('../fetch-server-response', () => {
const flightData: FlightData = [ const flightData: FlightData = [
[ [
...@@ -181,7 +177,7 @@ describe('serverPatchReducer', () => { ...@@ -181,7 +177,7 @@ describe('serverPatchReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
const newState = await runPromiseThrowChain(() => const newState = await runPromiseThrowChain(() =>
...@@ -372,7 +368,7 @@ describe('serverPatchReducer', () => { ...@@ -372,7 +368,7 @@ describe('serverPatchReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
await runPromiseThrowChain(() => serverPatchReducer(state, action)) await runPromiseThrowChain(() => serverPatchReducer(state, action))
...@@ -511,7 +507,7 @@ describe('serverPatchReducer', () => { ...@@ -511,7 +507,7 @@ describe('serverPatchReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
const state = createInitialRouterState({ const state = createInitialRouterState({
...@@ -553,7 +549,7 @@ describe('serverPatchReducer', () => { ...@@ -553,7 +549,7 @@ describe('serverPatchReducer', () => {
subTreeData: null, subTreeData: null,
parallelRoutes: new Map(), parallelRoutes: new Map(),
}, },
mutable: { globalMutable }, mutable: {},
} }
const newState = await runPromiseThrowChain(() => const newState = await runPromiseThrowChain(() =>
......
...@@ -4,11 +4,6 @@ import type { ...@@ -4,11 +4,6 @@ import type {
FlightData, FlightData,
FlightSegmentPath, FlightSegmentPath,
} from '../../../server/app-render/types' } from '../../../server/app-render/types'
import type {
FulfilledThenable,
PendingThenable,
RejectedThenable,
} from 'react'
import type { FetchServerResponseResult } from './fetch-server-response' import type { FetchServerResponseResult } from './fetch-server-response'
export const ACTION_REFRESH = 'refresh' export const ACTION_REFRESH = 'refresh'
...@@ -43,11 +38,6 @@ export interface Mutable { ...@@ -43,11 +38,6 @@ export interface Mutable {
prefetchCache?: AppRouterState['prefetchCache'] prefetchCache?: AppRouterState['prefetchCache']
hashFragment?: string hashFragment?: string
shouldScroll?: boolean shouldScroll?: boolean
globalMutable: {
pendingNavigatePath?: string
pendingMpaPath?: string
refresh: () => void
}
} }
export interface ServerActionMutable extends Mutable { export interface ServerActionMutable extends Mutable {
...@@ -273,7 +263,7 @@ export type AppRouterState = { ...@@ -273,7 +263,7 @@ export type AppRouterState = {
} }
export type ReadonlyReducerState = Readonly<AppRouterState> export type ReadonlyReducerState = Readonly<AppRouterState>
export type ReducerState = AppRouterState export type ReducerState = Promise<AppRouterState> | AppRouterState
export type ReducerActions = Readonly< export type ReducerActions = Readonly<
| RefreshAction | RefreshAction
| NavigateAction | NavigateAction
...@@ -284,7 +274,36 @@ export type ReducerActions = Readonly< ...@@ -284,7 +274,36 @@ export type ReducerActions = Readonly<
| ServerActionAction | ServerActionAction
> >
export interface PendingThenable<T> extends ThenableImpl<T> {
status: 'pending'
}
export interface FulfilledThenable<T> extends ThenableImpl<T> {
status: 'fulfilled'
value: T
}
export interface RejectedThenable<T> extends ThenableImpl<T> {
status: 'rejected'
reason: unknown
}
interface ThenableImpl<T> {
then<TResult1 = T, TResult2 = never>(
onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,
onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null
): Promise<TResult1 | TResult2>
}
export type ThenableRecord<T> = export type ThenableRecord<T> =
| PendingThenable<T> | PendingThenable<T>
| RejectedThenable<T> | RejectedThenable<T>
| FulfilledThenable<T> | FulfilledThenable<T>
export function isThenable(value: any): value is Promise<AppRouterState> {
return (
value &&
(typeof value === 'object' || typeof value === 'function') &&
typeof value.then === 'function'
)
}
import type { reducer } from './router-reducer/router-reducer' import type { Dispatch } from 'react'
import type { import React, { use, useContext } from 'react'
ReducerState, import { useRef, useEffect, useCallback } from 'react'
ReducerAction, import {
MutableRefObject, isThenable,
Dispatch, type AppRouterState,
} from 'react' type ReducerActions,
import { useRef, useReducer, useEffect, useCallback } from 'react' type ReducerState,
} from './router-reducer/router-reducer-types'
import { ActionQueueContext } from '../../shared/lib/router/action-queue'
function normalizeRouterState(val: any): any { function normalizeRouterState(val: any): any {
if (val instanceof Map) { if (val instanceof Map) {
...@@ -61,70 +63,44 @@ function normalizeRouterState(val: any): any { ...@@ -61,70 +63,44 @@ function normalizeRouterState(val: any): any {
return val return val
} }
// Log router state when actions are triggered.
// function logReducer(fn: typeof reducer) {
// return (
// state: ReducerState<typeof reducer>,
// action: ReducerAction<typeof reducer>
// ) => {
// console.groupCollapsed(action.type)
// console.log('action', action)
// console.log('old', state)
// const res = fn(state, action)
// console.log('new', res)
// console.groupEnd()
// return res
// }
// }
declare global { declare global {
interface Window { interface Window {
__REDUX_DEVTOOLS_EXTENSION__: any __REDUX_DEVTOOLS_EXTENSION__: any
} }
} }
interface ReduxDevToolsInstance { export interface ReduxDevToolsInstance {
send(action: any, state: any): void send(action: any, state: any): void
init(initialState: any): void init(initialState: any): void
} }
function devToolReducer( export function useUnwrapState(state: ReducerState) {
fn: typeof reducer, // reducer actions can be async, so sometimes we need to suspend until the state is resolved
ref: MutableRefObject<ReduxDevToolsInstance | undefined> if (isThenable(state)) {
) { const result = use(state)
return ( return result
state: ReducerState<typeof reducer>,
action: ReducerAction<typeof reducer>
) => {
const res = fn(state, action)
if (ref.current) {
ref.current.send(action, normalizeRouterState(res))
}
return res
} }
return state
} }
function useReducerWithReduxDevtoolsNoop( function useReducerWithReduxDevtoolsNoop(
fn: typeof reducer, initialState: AppRouterState
initialState: ReturnType<typeof reducer> ): [ReducerState, Dispatch<ReducerActions>, () => void] {
): [ return [initialState, () => {}, () => {}]
ReturnType<typeof reducer>,
Dispatch<ReducerAction<typeof reducer>>,
() => void
] {
const [state, dispatch] = useReducer(fn, initialState)
return [state, dispatch, () => {}]
} }
function useReducerWithReduxDevtoolsImpl( function useReducerWithReduxDevtoolsImpl(
fn: typeof reducer, initialState: AppRouterState
initialState: ReturnType<typeof reducer> ): [ReducerState, Dispatch<ReducerActions>, () => void] {
): [ const [state, setState] = React.useState<ReducerState>(initialState)
ReturnType<typeof reducer>,
Dispatch<ReducerAction<typeof reducer>>, const actionQueue = useContext(ActionQueueContext)
() => void
] { if (!actionQueue) {
throw new Error('Invariant: Missing ActionQueueContext')
}
const devtoolsConnectionRef = useRef<ReduxDevToolsInstance>() const devtoolsConnectionRef = useRef<ReduxDevToolsInstance>()
const enabledRef = useRef<boolean>() const enabledRef = useRef<boolean>()
...@@ -149,16 +125,28 @@ function useReducerWithReduxDevtoolsImpl( ...@@ -149,16 +125,28 @@ function useReducerWithReduxDevtoolsImpl(
) )
if (devtoolsConnectionRef.current) { if (devtoolsConnectionRef.current) {
devtoolsConnectionRef.current.init(normalizeRouterState(initialState)) devtoolsConnectionRef.current.init(normalizeRouterState(initialState))
if (actionQueue) {
actionQueue.devToolsInstance = devtoolsConnectionRef.current
}
} }
return () => { return () => {
devtoolsConnectionRef.current = undefined devtoolsConnectionRef.current = undefined
} }
}, [initialState]) }, [initialState, actionQueue])
const dispatch = useCallback(
(action: ReducerActions) => {
if (!actionQueue.state) {
// we lazy initialize the mutable action queue state since the data needed
// to generate the state is not available when the actionQueue context is created
actionQueue.state = initialState
}
const [state, dispatch] = useReducer( actionQueue.dispatch(action, setState)
devToolReducer(/* logReducer( */ fn /*)*/, devtoolsConnectionRef), },
initialState [actionQueue, initialState]
) )
const sync = useCallback(() => { const sync = useCallback(() => {
...@@ -169,6 +157,7 @@ function useReducerWithReduxDevtoolsImpl( ...@@ -169,6 +157,7 @@ function useReducerWithReduxDevtoolsImpl(
) )
} }
}, [state]) }, [state])
return [state, dispatch, sync] return [state, dispatch, sync]
} }
......
import {
isThenable,
type AppRouterState,
type ReducerActions,
type ReducerState,
ACTION_REFRESH,
ACTION_SERVER_ACTION,
ACTION_NAVIGATE,
} from '../../../client/components/router-reducer/router-reducer-types'
import type { ReduxDevToolsInstance } from '../../../client/components/use-reducer-with-devtools'
import { reducer } from '../../../client/components/router-reducer/router-reducer'
import React, { startTransition } from 'react'
import { createEmptyCacheNode } from '../../../client/components/app-router'
export type DispatchStatePromise = React.Dispatch<ReducerState>
export type AppRouterActionQueue = {
state: AppRouterState | null
devToolsInstance?: ReduxDevToolsInstance
dispatch: (payload: ReducerActions, setState: DispatchStatePromise) => void
action: (state: AppRouterState, action: ReducerActions) => ReducerState
pending: ActionQueueNode | null
needsRefresh?: boolean
last: ActionQueueNode | null
}
export type ActionQueueNode = {
payload: ReducerActions
next: ActionQueueNode | null
resolve: (value: PromiseLike<AppRouterState> | AppRouterState) => void
reject: (err: Error) => void
discarded?: boolean
}
export const ActionQueueContext =
React.createContext<AppRouterActionQueue | null>(null)
function runRemainingActions(
actionQueue: AppRouterActionQueue,
setState: DispatchStatePromise
) {
if (actionQueue.pending !== null) {
actionQueue.pending = actionQueue.pending.next
if (actionQueue.pending !== null) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
runAction({
actionQueue,
action: actionQueue.pending,
setState,
})
}
}
}
async function runAction({
actionQueue,
action,
setState,
}: {
actionQueue: AppRouterActionQueue
action: ActionQueueNode
setState: DispatchStatePromise
}) {
const prevState = actionQueue.state
if (!prevState) {
// This shouldn't happen as the state is initialized in the dispatcher if it's not set
throw new Error('Invariant: Router state not initialized')
}
actionQueue.pending = action
actionQueue.last = action
const payload = action.payload
const actionResult = actionQueue.action(prevState, payload)
function handleResult(nextState: AppRouterState) {
// if we discarded this action, the state should also be discarded
if (action.discarded) {
// if a refresh is needed, we only want to trigger it once the action queue is empty
if (actionQueue.needsRefresh && actionQueue.pending === null) {
actionQueue.needsRefresh = false
actionQueue.dispatch(
{
type: ACTION_REFRESH,
cache: createEmptyCacheNode(),
mutable: {},
origin: window.location.origin,
},
setState
)
}
return
}
actionQueue.state = nextState
if (actionQueue.devToolsInstance) {
actionQueue.devToolsInstance.send(payload, nextState)
}
runRemainingActions(actionQueue, setState)
action.resolve(nextState)
}
// if the action is a promise, set up a callback to resolve it
if (isThenable(actionResult)) {
actionResult.then(handleResult, (err) => {
runRemainingActions(actionQueue, setState)
action.reject(err)
})
} else {
handleResult(actionResult)
}
}
function dispatchAction(
actionQueue: AppRouterActionQueue,
payload: ReducerActions,
setState: DispatchStatePromise
) {
let resolvers: {
resolve: (value: AppRouterState | PromiseLike<AppRouterState>) => void
reject: (reason: any) => void
}
// Create the promise and assign the resolvers to the object.
const deferredPromise = new Promise<AppRouterState>((resolve, reject) => {
resolvers = { resolve, reject }
})
const newAction: ActionQueueNode = {
payload,
next: null,
resolve: resolvers!.resolve,
reject: resolvers!.reject,
}
startTransition(() => {
// we immediately notify React of the pending promise -- the resolver is attached to the action node
// and will be called when the associated action promise resolves
setState(deferredPromise)
})
// Check if the queue is empty
if (actionQueue.pending === null) {
// The queue is empty, so add the action and start it immediately
runAction({
actionQueue,
action: newAction,
setState,
})
} else if (payload.type === ACTION_NAVIGATE) {
// Navigations take priority over any pending actions.
// Mark the pending action as discarded (so the state is never applied) and start the navigation action immediately.
actionQueue.pending.discarded = true
// if the pending action was a server action, mark the queue as needing a refresh once events are processed
if (actionQueue.pending.payload.type === ACTION_SERVER_ACTION) {
actionQueue.needsRefresh = true
}
runAction({
actionQueue,
action: newAction,
setState,
})
} else {
// The queue is not empty, so add the action to the end of the queue
// It will be started by finishRunningAction after the previous action finishes
if (actionQueue.last !== null) {
actionQueue.last.next = newAction
}
actionQueue.last = newAction
}
}
export function createMutableActionQueue(): AppRouterActionQueue {
const actionQueue: AppRouterActionQueue = {
state: null,
dispatch: (payload: ReducerActions, setState: DispatchStatePromise) =>
dispatchAction(actionQueue, payload, setState),
action: async (state: AppRouterState, action: ReducerActions) => {
if (state === null) {
throw new Error('Invariant: Router state not initialized')
}
const result = reducer(state, action)
return result
},
pending: null,
last: null,
}
return actionQueue
}
...@@ -288,6 +288,27 @@ createNextDescribe( ...@@ -288,6 +288,27 @@ createNextDescribe(
await check(() => browser.url(), `${next.url}/client`, true, 2) await check(() => browser.url(), `${next.url}/client`, true, 2)
}) })
it('should trigger a refresh for a server action that gets discarded due to a navigation', async () => {
let browser = await next.browser('/client')
const initialRandomNumber = await browser
.elementByCss('#random-number')
.text()
await browser.elementByCss('#slow-inc').click()
// navigate to server
await browser.elementByCss('#navigate-server').click()
// wait for the action to be completed
await check(async () => {
const newRandomNumber = await browser
.elementByCss('#random-number')
.text()
return newRandomNumber === initialRandomNumber ? 'fail' : 'success'
}, 'success')
})
it('should support next/dynamic with ssr: false', async () => { it('should support next/dynamic with ssr: false', async () => {
const browser = await next.browser('/dynamic-csr') const browser = await next.browser('/dynamic-csr')
......
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