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
import onRecoverableError from './on-recoverable-error'
import { callServer } from './app-call-server'
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.
const origConsoleError = window.console.error
......@@ -222,6 +226,8 @@ export function hydrate() {
}
}
const actionQueue = createMutableActionQueue()
const reactEl = (
<StrictModeIfEnabled>
<HeadManagerContext.Provider
......@@ -229,9 +235,11 @@ export function hydrate() {
appDir: true,
}}
>
<ActionQueueContext.Provider value={actionQueue}>
<Root>
<RSCComponent />
</Root>
</ActionQueueContext.Provider>
</HeadManagerContext.Provider>
</StrictModeIfEnabled>
)
......
......@@ -24,7 +24,6 @@ import type {
FlightData,
} from '../../server/app-render/types'
import type { ErrorComponent } from './error-boundary'
import { reducer } from './router-reducer/router-reducer'
import {
ACTION_FAST_REFRESH,
ACTION_NAVIGATE,
......@@ -36,7 +35,6 @@ import {
PrefetchKind,
} from './router-reducer/router-reducer-types'
import type {
Mutable,
ReducerActions,
RouterChangeByServerResponse,
RouterNavigate,
......@@ -47,7 +45,10 @@ import {
SearchParamsContext,
PathnameContext,
} 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 { createInitialRouterState } from './router-reducer/create-initial-router-state'
import type { InitialRouterStateParameters } from './router-reducer/create-initial-router-state'
......@@ -73,9 +74,9 @@ export function getServerActionDispatcher() {
return globalServerActionDispatcher
}
let globalMutable: Mutable['globalMutable'] = {
refresh: () => {}, // noop until the router is initialized
}
const globalMutable: {
pendingMpaPath?: string
} = {}
export function urlToUrlWithoutFlightMarker(url: string): URL {
const urlWithoutFlightParameters = new URL(url, location.origin)
......@@ -131,7 +132,7 @@ function HistoryUpdater({ tree, pushRef, canonicalUrl, sync }: any) {
return null
}
const createEmptyCacheNode = () => ({
export const createEmptyCacheNode = () => ({
status: CacheStates.LAZY_INITIALIZED,
data: null,
subTreeData: null,
......@@ -145,7 +146,7 @@ function useServerActionDispatcher(dispatch: React.Dispatch<ReducerActions>) {
dispatch({
...actionPayload,
type: ACTION_SERVER_ACTION,
mutable: { globalMutable },
mutable: {},
cache: createEmptyCacheNode(),
})
})
......@@ -174,7 +175,7 @@ function useChangeByServerResponse(
previousTree,
overrideCanonicalUrl,
cache: createEmptyCacheNode(),
mutable: { globalMutable },
mutable: {},
})
})
},
......@@ -186,7 +187,6 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
return useCallback(
(href, navigateType, forceOptimisticNavigation, shouldScroll) => {
const url = new URL(addBasePath(href), location.href)
globalMutable.pendingNavigatePath = createHrefFromUrl(url)
return dispatch({
type: ACTION_NAVIGATE,
......@@ -197,7 +197,7 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
shouldScroll: shouldScroll ?? true,
navigateType,
cache: createEmptyCacheNode(),
mutable: { globalMutable },
mutable: {},
})
},
[dispatch]
......@@ -229,25 +229,15 @@ function Router({
}),
[buildId, children, initialCanonicalUrl, initialTree, initialHead]
)
const [
{
tree,
cache,
prefetchCache,
pushRef,
focusAndScrollRef,
canonicalUrl,
nextUrl,
},
dispatch,
sync,
] = useReducerWithReduxDevtools(reducer, initialState)
const [reducerState, dispatch, sync] =
useReducerWithReduxDevtools(initialState)
useEffect(() => {
// Ensure initialParallelRoutes is cleaned up from memory once it's used.
initialParallelRoutes = null!
}, [])
const { canonicalUrl } = useUnwrapState(reducerState)
// Add memoized pathname/query for useSearchParams and usePathname.
const { searchParams, pathname } = useMemo(() => {
const url = new URL(
......@@ -322,7 +312,7 @@ function Router({
dispatch({
type: ACTION_REFRESH,
cache: createEmptyCacheNode(),
mutable: { globalMutable },
mutable: {},
origin: window.location.origin,
})
})
......@@ -338,7 +328,7 @@ function Router({
dispatch({
type: ACTION_FAST_REFRESH,
cache: createEmptyCacheNode(),
mutable: { globalMutable },
mutable: {},
origin: window.location.origin,
})
})
......@@ -356,11 +346,10 @@ function Router({
}
}, [appRouter])
useEffect(() => {
globalMutable.refresh = appRouter.refresh
}, [appRouter.refresh])
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
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
......@@ -408,6 +397,7 @@ function Router({
// 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,
// but that's... fine?)
const { pushRef } = useUnwrapState(reducerState)
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 (globalMutable.pendingMpaPath !== canonicalUrl) {
......@@ -466,6 +456,9 @@ function Router({
}
}, [onPopState])
const { cache, tree, nextUrl, focusAndScrollRef } =
useUnwrapState(reducerState)
const head = useMemo(() => {
return findHeadInCache(cache, tree[1])
}, [cache, tree])
......@@ -513,7 +506,7 @@ function Router({
<LayoutRouterContext.Provider
value={{
childNodes: cache.parallelRoutes,
tree: tree,
tree,
// Root node always has `url`
// Provided in AppTreeContext to ensure it can be overwritten in layout-router
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 { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
......@@ -40,8 +39,9 @@ function fastRefreshReducerImpl(
)
)
}
const [flightData, canonicalUrlOverride] = readRecordValue(cache.data!)
return cache.data.then(
([flightData, canonicalUrlOverride]) => {
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return handleExternalUrl(
......@@ -80,7 +80,12 @@ function fastRefreshReducerImpl(
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, state.pushRef.pendingPush)
return handleExternalUrl(
state,
mutable,
href,
state.pushRef.pendingPush
)
}
const canonicalUrlOverrideHref = canonicalUrlOverride
......@@ -104,6 +109,9 @@ function fastRefreshReducerImpl(
currentTree = newTree
}
return handleMutable(state, mutable)
},
() => state
)
}
function fastRefreshReducerNoop(
......
......@@ -102,10 +102,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [
true,
]
const globalMutable = {
refresh: () => {},
}
async function runPromiseThrowChain(fn: any): Promise<any> {
try {
return await fn()
......@@ -194,7 +190,7 @@ describe('navigateReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
const newState = await runPromiseThrowChain(() =>
......@@ -438,7 +434,7 @@ describe('navigateReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
await runPromiseThrowChain(() => navigateReducer(state, action))
......@@ -633,7 +629,7 @@ describe('navigateReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
await runPromiseThrowChain(() => navigateReducer(state, action))
......@@ -792,7 +788,7 @@ describe('navigateReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
await runPromiseThrowChain(() => navigateReducer(state, action))
......@@ -948,7 +944,7 @@ describe('navigateReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
await runPromiseThrowChain(() => navigateReducer(state, action))
......@@ -1147,7 +1143,7 @@ describe('navigateReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
await runPromiseThrowChain(() => navigateReducer(state, action))
......@@ -1317,7 +1313,7 @@ describe('navigateReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
await runPromiseThrowChain(() => navigateReducer(state, action))
......@@ -1630,7 +1626,7 @@ describe('navigateReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
await runPromiseThrowChain(() => navigateReducer(state, action))
......@@ -1841,7 +1837,6 @@ describe('navigateReducer', () => {
hashFragment: '#hash',
pendingPush: true,
shouldScroll: true,
globalMutable,
},
}
......@@ -1984,7 +1979,7 @@ describe('navigateReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
const newState = await runPromiseThrowChain(() =>
......
......@@ -7,7 +7,6 @@ import type {
import { fetchServerResponse } from '../fetch-server-response'
import type { FetchServerResponseResult } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url'
import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath'
import { fillCacheWithDataProperty } from '../fill-cache-with-data-property'
......@@ -248,11 +247,10 @@ export function navigateReducer(
prefetchQueue.bump(data!)
// Unwrap cache data with `use` to suspend here (in the reducer) until the fetch resolves.
const [flightData, canonicalUrlOverride, postponed] = readRecordValue(data!)
return data!.then(
([flightData, canonicalUrlOverride, postponed]) => {
// we only want to mark this once
if (!prefetchValues.lastUsedTime) {
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()
}
......@@ -300,21 +298,20 @@ export function navigateReducer(
return handleExternalUrl(state, mutable, href, pendingPush)
}
// TODO-APP: If the prefetch was postponed, we don't want to apply it
// until we land router changes to handle the postponed case.
let applied = postponed
? false
: applyFlightData(
let applied = applyFlightData(
currentCache,
cache,
flightDataPath,
prefetchValues.kind === 'auto' &&
prefetchValues?.kind === 'auto' &&
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.reusable
)
if (
!applied &&
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.stale
(!applied &&
prefetchEntryCacheStatus === PrefetchCacheEntryStatus.stale) ||
// TODO-APP: If the prefetch was postponed, we don't want to apply it
// until we land router changes to handle the postponed case.
postponed
) {
applied = addRefetchToLeafSegments(
cache,
......@@ -383,4 +380,7 @@ export function navigateReducer(
mutable.shouldScroll = shouldScroll
return handleMutable(state, mutable)
},
() => state
)
}
import type { ReducerState } from '../router-reducer-types'
import type { AppRouterState } from '../router-reducer-types'
import {
PrefetchCacheEntryStatus,
getPrefetchEntryCacheStatus,
} from '../get-prefetch-cache-entry-status'
export function prunePrefetchCache(
prefetchCache: ReducerState['prefetchCache']
prefetchCache: AppRouterState['prefetchCache']
) {
for (const [href, prefetchCacheEntry] of prefetchCache) {
if (
......
......@@ -64,10 +64,6 @@ const getInitialRouterStateTree = (): FlightRouterState => [
true,
]
const globalMutable = {
refresh: () => {},
}
async function runPromiseThrowChain(fn: any): Promise<any> {
try {
return await fn()
......@@ -141,7 +137,7 @@ describe('refreshReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
origin: new URL('/linking', 'https://localhost').origin,
}
......@@ -302,7 +298,7 @@ describe('refreshReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
origin: new URL('/linking', 'https://localhost').origin,
}
......@@ -489,7 +485,7 @@ describe('refreshReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
origin: new URL('/linking', 'https://localhost').origin,
}
......@@ -725,7 +721,7 @@ describe('refreshReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
origin: new URL('/linking', 'https://localhost').origin,
}
......
import { fetchServerResponse } from '../fetch-server-response'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
import { createHrefFromUrl } from '../create-href-from-url'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
......@@ -42,8 +41,9 @@ export function refreshReducer(
)
)
}
const [flightData, canonicalUrlOverride] = readRecordValue(cache.data!)
return cache.data.then(
([flightData, canonicalUrlOverride]) => {
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return handleExternalUrl(
......@@ -79,7 +79,12 @@ export function refreshReducer(
}
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, state.pushRef.pendingPush)
return handleExternalUrl(
state,
mutable,
href,
state.pushRef.pendingPush
)
}
const canonicalUrlOverrideHref = canonicalUrlOverride
......@@ -116,4 +121,7 @@ export function refreshReducer(
}
return handleMutable(state, mutable)
},
() => state
)
}
......@@ -11,7 +11,6 @@ import {
RSC_CONTENT_TYPE_HEADER,
} from '../../app-router-headers'
import { createRecordFromThenable } from '../create-record-from-thenable'
import { readRecordValue } from '../read-record-value'
// // eslint-disable-next-line import/no-extraneous-dependencies
// import { createFromFetch } from 'react-server-dom-webpack/client'
// // eslint-disable-next-line import/no-extraneous-dependencies
......@@ -159,48 +158,14 @@ export function serverActionReducer(
return handleMutable(state, mutable)
}
if (mutable.inFlightServerAction) {
// unblock if a navigation event comes through
// 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>
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) {
......@@ -306,7 +271,8 @@ export function serverActionReducer(
mutable.actionResultResolved = true
}
return handleMutable(state, mutable)
} catch (e: any) {
},
(e: any) => {
if (e.status === 'rejected') {
if (!mutable.actionResultResolved) {
reject(e.reason)
......@@ -319,4 +285,5 @@ export function serverActionReducer(
throw e
}
)
}
......@@ -13,10 +13,6 @@ import { navigateReducer } from './navigate-reducer'
import { serverPatchReducer } from './server-patch-reducer'
const buildId = 'development'
const globalMutable = {
refresh: () => {},
}
jest.mock('../fetch-server-response', () => {
const flightData: FlightData = [
[
......@@ -181,7 +177,7 @@ describe('serverPatchReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
const newState = await runPromiseThrowChain(() =>
......@@ -372,7 +368,7 @@ describe('serverPatchReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
await runPromiseThrowChain(() => serverPatchReducer(state, action))
......@@ -511,7 +507,7 @@ describe('serverPatchReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
const state = createInitialRouterState({
......@@ -553,7 +549,7 @@ describe('serverPatchReducer', () => {
subTreeData: null,
parallelRoutes: new Map(),
},
mutable: { globalMutable },
mutable: {},
}
const newState = await runPromiseThrowChain(() =>
......
......@@ -4,11 +4,6 @@ import type {
FlightData,
FlightSegmentPath,
} from '../../../server/app-render/types'
import type {
FulfilledThenable,
PendingThenable,
RejectedThenable,
} from 'react'
import type { FetchServerResponseResult } from './fetch-server-response'
export const ACTION_REFRESH = 'refresh'
......@@ -43,11 +38,6 @@ export interface Mutable {
prefetchCache?: AppRouterState['prefetchCache']
hashFragment?: string
shouldScroll?: boolean
globalMutable: {
pendingNavigatePath?: string
pendingMpaPath?: string
refresh: () => void
}
}
export interface ServerActionMutable extends Mutable {
......@@ -273,7 +263,7 @@ export type AppRouterState = {
}
export type ReadonlyReducerState = Readonly<AppRouterState>
export type ReducerState = AppRouterState
export type ReducerState = Promise<AppRouterState> | AppRouterState
export type ReducerActions = Readonly<
| RefreshAction
| NavigateAction
......@@ -284,7 +274,36 @@ export type ReducerActions = Readonly<
| 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> =
| PendingThenable<T>
| RejectedThenable<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 {
ReducerState,
ReducerAction,
MutableRefObject,
Dispatch,
} from 'react'
import { useRef, useReducer, useEffect, useCallback } from 'react'
import type { Dispatch } from 'react'
import React, { use, useContext } from 'react'
import { useRef, useEffect, useCallback } from 'react'
import {
isThenable,
type AppRouterState,
type ReducerActions,
type ReducerState,
} from './router-reducer/router-reducer-types'
import { ActionQueueContext } from '../../shared/lib/router/action-queue'
function normalizeRouterState(val: any): any {
if (val instanceof Map) {
......@@ -61,70 +63,44 @@ function normalizeRouterState(val: any): any {
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 {
interface Window {
__REDUX_DEVTOOLS_EXTENSION__: any
}
}
interface ReduxDevToolsInstance {
export interface ReduxDevToolsInstance {
send(action: any, state: any): void
init(initialState: any): void
}
function devToolReducer(
fn: typeof reducer,
ref: MutableRefObject<ReduxDevToolsInstance | undefined>
) {
return (
state: ReducerState<typeof reducer>,
action: ReducerAction<typeof reducer>
) => {
const res = fn(state, action)
if (ref.current) {
ref.current.send(action, normalizeRouterState(res))
}
return res
export function useUnwrapState(state: ReducerState) {
// reducer actions can be async, so sometimes we need to suspend until the state is resolved
if (isThenable(state)) {
const result = use(state)
return result
}
return state
}
function useReducerWithReduxDevtoolsNoop(
fn: typeof reducer,
initialState: ReturnType<typeof reducer>
): [
ReturnType<typeof reducer>,
Dispatch<ReducerAction<typeof reducer>>,
() => void
] {
const [state, dispatch] = useReducer(fn, initialState)
return [state, dispatch, () => {}]
initialState: AppRouterState
): [ReducerState, Dispatch<ReducerActions>, () => void] {
return [initialState, () => {}, () => {}]
}
function useReducerWithReduxDevtoolsImpl(
fn: typeof reducer,
initialState: ReturnType<typeof reducer>
): [
ReturnType<typeof reducer>,
Dispatch<ReducerAction<typeof reducer>>,
() => void
] {
initialState: AppRouterState
): [ReducerState, Dispatch<ReducerActions>, () => void] {
const [state, setState] = React.useState<ReducerState>(initialState)
const actionQueue = useContext(ActionQueueContext)
if (!actionQueue) {
throw new Error('Invariant: Missing ActionQueueContext')
}
const devtoolsConnectionRef = useRef<ReduxDevToolsInstance>()
const enabledRef = useRef<boolean>()
......@@ -149,16 +125,28 @@ function useReducerWithReduxDevtoolsImpl(
)
if (devtoolsConnectionRef.current) {
devtoolsConnectionRef.current.init(normalizeRouterState(initialState))
if (actionQueue) {
actionQueue.devToolsInstance = devtoolsConnectionRef.current
}
}
return () => {
devtoolsConnectionRef.current = undefined
}
}, [initialState])
}, [initialState, actionQueue])
const [state, dispatch] = useReducer(
devToolReducer(/* logReducer( */ fn /*)*/, devtoolsConnectionRef),
initialState
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
}
actionQueue.dispatch(action, setState)
},
[actionQueue, initialState]
)
const sync = useCallback(() => {
......@@ -169,6 +157,7 @@ function useReducerWithReduxDevtoolsImpl(
)
}
}, [state])
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(
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 () => {
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