Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
N
next.js
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Alex
next.js
Commits
07c3464a
Unverified
Commit
07c3464a
authored
Jul 25, 2022
by
Tim Neutkens
Committed by
GitHub
Jul 25, 2022
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Refactor router reducer (#38983)
parent
c3fd9e4e
Show whitespace changes
Inline
Side-by-side
Showing
9 changed files
with
392 additions
and
326 deletions
+392
-326
next-app-loader.ts
packages/next/build/webpack/loaders/next-app-loader.ts
+0
-1
app-router.client.tsx
packages/next/client/components/app-router.client.tsx
+102
-55
hooks-client-context.ts
packages/next/client/components/hooks-client-context.ts
+4
-2
hooks-client.ts
packages/next/client/components/hooks-client.ts
+3
-3
hot-reloader.client.tsx
packages/next/client/components/hot-reloader.client.tsx
+2
-2
layout-router.client.tsx
packages/next/client/components/layout-router.client.tsx
+2
-2
reducer.ts
packages/next/client/components/reducer.ts
+247
-239
app-render.tsx
packages/next/server/app-render.tsx
+8
-20
app-router-context.ts
packages/next/shared/lib/app-router-context.ts
+24
-2
No files found.
packages/next/build/webpack/loaders/next-app-loader.ts
View file @
07c3464a
...
@@ -130,7 +130,6 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
...
@@ -130,7 +130,6 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
?
`require('next/dist/client/components/hot-reloader.client.js').default`
?
`require('next/dist/client/components/hot-reloader.client.js').default`
:
'null'
:
'null'
}
}
export const hooksClientContext = require('next/dist/client/components/hooks-client-context.js')
export const __next_app_webpack_require__ = __webpack_require__
export const __next_app_webpack_require__ = __webpack_require__
`
`
...
...
packages/next/client/components/app-router.client.tsx
View file @
07c3464a
...
@@ -3,26 +3,43 @@ import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-we
...
@@ -3,26 +3,43 @@ import { createFromReadableStream } from 'next/dist/compiled/react-server-dom-we
import
{
import
{
AppRouterContext
,
AppRouterContext
,
AppTreeContext
,
AppTreeContext
,
FullAppTree
Context
,
GlobalLayoutRouter
Context
,
}
from
'../../shared/lib/app-router-context'
}
from
'../../shared/lib/app-router-context'
import
type
{
import
type
{
CacheNode
,
CacheNode
,
AppRouterInstance
,
AppRouterInstance
,
}
from
'../../shared/lib/app-router-context'
}
from
'../../shared/lib/app-router-context'
import
type
{
FlightRouterState
,
FlightData
}
from
'../../server/app-render'
import
type
{
FlightRouterState
,
FlightData
}
from
'../../server/app-render'
import
{
reducer
}
from
'./reducer'
import
{
import
{
QueryContext
,
ACTION_NAVIGATE
,
ACTION_RELOAD
,
ACTION_RESTORE
,
ACTION_SERVER_PATCH
,
reducer
,
}
from
'./reducer'
import
{
SearchParamsContext
,
// ParamsContext,
// ParamsContext,
PathnameContext
,
PathnameContext
,
// LayoutSegmentsContext,
// LayoutSegmentsContext,
}
from
'./hooks-client-context'
}
from
'./hooks-client-context'
function
fetchFlight
(
url
:
URL
,
flightRouterStateData
:
string
):
ReadableStream
{
/**
* Fetch the flight data for the provided url. Takes in the current router state to decide what to render server-side.
*/
function
fetchFlight
(
url
:
URL
,
flightRouterState
:
FlightRouterState
):
ReadableStream
{
const
flightUrl
=
new
URL
(
url
)
const
flightUrl
=
new
URL
(
url
)
const
searchParams
=
flightUrl
.
searchParams
const
searchParams
=
flightUrl
.
searchParams
// Enable flight response
searchParams
.
append
(
'__flight__'
,
'1'
)
searchParams
.
append
(
'__flight__'
,
'1'
)
searchParams
.
append
(
'__flight_router_state_tree__'
,
flightRouterStateData
)
// Provide the current router state
searchParams
.
append
(
'__flight_router_state_tree__'
,
JSON
.
stringify
(
flightRouterState
)
)
const
{
readable
,
writable
}
=
new
TransformStream
()
const
{
readable
,
writable
}
=
new
TransformStream
()
...
@@ -33,14 +50,20 @@ function fetchFlight(url: URL, flightRouterStateData: string): ReadableStream {
...
@@ -33,14 +50,20 @@ function fetchFlight(url: URL, flightRouterStateData: string): ReadableStream {
return
readable
return
readable
}
}
/**
* Fetch the flight data for the provided url. Takes in the current router state to decide what to render server-side.
*/
export
function
fetchServerResponse
(
export
function
fetchServerResponse
(
url
:
URL
,
url
:
URL
,
flightRouterState
:
FlightRouterState
flightRouterState
:
FlightRouterState
):
{
readRoot
:
()
=>
FlightData
}
{
):
{
readRoot
:
()
=>
FlightData
}
{
const
flightRouterStateData
=
JSON
.
stringify
(
flightRouterState
)
// Handle the `fetch` readable stream that can be read using `readRoot`.
return
createFromReadableStream
(
fetchFlight
(
url
,
flightRouterState
Data
))
return
createFromReadableStream
(
fetchFlight
(
url
,
flightRouterState
))
}
}
/**
* Renders development error overlay when NODE_ENV is development.
*/
function
ErrorOverlay
({
function
ErrorOverlay
({
children
,
children
,
}:
React
.
PropsWithChildren
<
{}
>
):
React
.
ReactElement
{
}:
React
.
PropsWithChildren
<
{}
>
):
React
.
ReactElement
{
...
@@ -54,10 +77,14 @@ function ErrorOverlay({
...
@@ -54,10 +77,14 @@ function ErrorOverlay({
}
}
}
}
// Ensure the initialParallelRoutes are not combined because of double-rendering in the browser with Strict Mode.
// TODO-APP: move this back into AppRouter
// TODO-APP: move this back into AppRouter
let
initialParallelRoutes
:
CacheNode
[
'parallelRoutes'
]
=
let
initialParallelRoutes
:
CacheNode
[
'parallelRoutes'
]
=
typeof
window
===
'undefined'
?
null
!
:
new
Map
()
typeof
window
===
'undefined'
?
null
!
:
new
Map
()
/**
* The global router that wraps the application components.
*/
export
default
function
AppRouter
({
export
default
function
AppRouter
({
initialTree
,
initialTree
,
initialCanonicalUrl
,
initialCanonicalUrl
,
...
@@ -72,7 +99,7 @@ export default function AppRouter({
...
@@ -72,7 +99,7 @@ export default function AppRouter({
hotReloader
?:
React
.
ReactNode
hotReloader
?:
React
.
ReactNode
})
{
})
{
const
[{
tree
,
cache
,
pushRef
,
focusRef
,
canonicalUrl
},
dispatch
]
=
const
[{
tree
,
cache
,
pushRef
,
focusRef
,
canonicalUrl
},
dispatch
]
=
React
.
useReducer
<
typeof
reducer
>
(
reducer
,
{
React
.
useReducer
(
reducer
,
{
tree
:
initialTree
,
tree
:
initialTree
,
cache
:
{
cache
:
{
data
:
null
,
data
:
null
,
...
@@ -90,27 +117,32 @@ export default function AppRouter({
...
@@ -90,27 +117,32 @@ export default function AppRouter({
})
})
useEffect
(()
=>
{
useEffect
(()
=>
{
// Ensure initialParallelRoutes is cleaned up from memory once it's used.
initialParallelRoutes
=
null
!
initialParallelRoutes
=
null
!
},
[])
},
[])
const
{
query
,
pathname
}
=
React
.
useMemo
(()
=>
{
// Add memoized pathname/query for useSearchParams and usePathname.
const
{
searchParams
,
pathname
}
=
React
.
useMemo
(()
=>
{
const
url
=
new
URL
(
const
url
=
new
URL
(
canonicalUrl
,
canonicalUrl
,
typeof
window
===
'undefined'
?
'http://n'
:
window
.
location
.
href
typeof
window
===
'undefined'
?
'http://n'
:
window
.
location
.
href
)
)
const
queryObj
:
{
[
key
:
string
]:
string
}
=
{}
// Convert searchParams to a plain object to match server-side.
const
searchParamsObj
:
{
[
key
:
string
]:
string
}
=
{}
url
.
searchParams
.
forEach
((
value
,
key
)
=>
{
url
.
searchParams
.
forEach
((
value
,
key
)
=>
{
query
Obj
[
key
]
=
value
searchParams
Obj
[
key
]
=
value
})
})
return
{
query
:
query
Obj
,
pathname
:
url
.
pathname
}
return
{
searchParams
:
searchParams
Obj
,
pathname
:
url
.
pathname
}
},
[
canonicalUrl
])
},
[
canonicalUrl
])
// Server response only patches the tree
/**
* Server response that only patches the cache and tree.
*/
const
changeByServerResponse
=
React
.
useCallback
(
const
changeByServerResponse
=
React
.
useCallback
(
(
previousTree
:
FlightRouterState
,
flightData
:
FlightData
)
=>
{
(
previousTree
:
FlightRouterState
,
flightData
:
FlightData
)
=>
{
dispatch
({
dispatch
({
type
:
'server-patch'
,
type
:
ACTION_SERVER_PATCH
,
payload
:
{
flightData
,
flightData
,
previousTree
,
previousTree
,
cache
:
{
cache
:
{
...
@@ -118,12 +150,14 @@ export default function AppRouter({
...
@@ -118,12 +150,14 @@ export default function AppRouter({
subTreeData
:
null
,
subTreeData
:
null
,
parallelRoutes
:
new
Map
(),
parallelRoutes
:
new
Map
(),
},
},
},
})
})
},
},
[]
[]
)
)
/**
* The app router that is exposed through `useRouter`. It's only concerned with dispatching actions to the reducer, does not hold state.
*/
const
appRouter
=
React
.
useMemo
<
AppRouterInstance
>
(()
=>
{
const
appRouter
=
React
.
useMemo
<
AppRouterInstance
>
(()
=>
{
const
navigate
=
(
const
navigate
=
(
href
:
string
,
href
:
string
,
...
@@ -131,8 +165,7 @@ export default function AppRouter({
...
@@ -131,8 +165,7 @@ export default function AppRouter({
navigateType
:
'push'
|
'replace'
navigateType
:
'push'
|
'replace'
)
=>
{
)
=>
{
return
dispatch
({
return
dispatch
({
type
:
'navigate'
,
type
:
ACTION_NAVIGATE
,
payload
:
{
url
:
new
URL
(
href
,
location
.
origin
),
url
:
new
URL
(
href
,
location
.
origin
),
cacheType
,
cacheType
,
navigateType
,
navigateType
,
...
@@ -142,12 +175,11 @@ export default function AppRouter({
...
@@ -142,12 +175,11 @@ export default function AppRouter({
parallelRoutes
:
new
Map
(),
parallelRoutes
:
new
Map
(),
},
},
mutable
:
{},
mutable
:
{},
},
})
})
}
}
const
routerInstance
:
AppRouterInstance
=
{
const
routerInstance
:
AppRouterInstance
=
{
// TODO-APP: implement prefetching of
loading /
flight
// TODO-APP: implement prefetching of flight
prefetch
:
(
_href
)
=>
Promise
.
resolve
(),
prefetch
:
(
_href
)
=>
Promise
.
resolve
(),
replace
:
(
href
)
=>
{
replace
:
(
href
)
=>
{
// @ts-ignore startTransition exists
// @ts-ignore startTransition exists
...
@@ -177,8 +209,8 @@ export default function AppRouter({
...
@@ -177,8 +209,8 @@ export default function AppRouter({
// @ts-ignore startTransition exists
// @ts-ignore startTransition exists
React
.
startTransition
(()
=>
{
React
.
startTransition
(()
=>
{
dispatch
({
dispatch
({
type
:
'reload'
,
type
:
ACTION_RELOAD
,
payload
:
{
// TODO-APP: revisit if this needs to be passed.
// TODO-APP: revisit if this needs to be passed.
url
:
new
URL
(
window
.
location
.
href
),
url
:
new
URL
(
window
.
location
.
href
),
cache
:
{
cache
:
{
...
@@ -187,7 +219,6 @@ export default function AppRouter({
...
@@ -187,7 +219,6 @@ export default function AppRouter({
parallelRoutes
:
new
Map
(),
parallelRoutes
:
new
Map
(),
},
},
mutable
:
{},
mutable
:
{},
},
})
})
})
})
},
},
...
@@ -197,6 +228,7 @@ export default function AppRouter({
...
@@ -197,6 +228,7 @@ export default function AppRouter({
},
[])
},
[])
useEffect
(()
=>
{
useEffect
(()
=>
{
// When mpaNavigation flag is set do a hard navigation to the new url.
if
(
pushRef
.
mpaNavigation
)
{
if
(
pushRef
.
mpaNavigation
)
{
window
.
location
.
href
=
canonicalUrl
window
.
location
.
href
=
canonicalUrl
return
return
...
@@ -207,6 +239,7 @@ export default function AppRouter({
...
@@ -207,6 +239,7 @@ export default function AppRouter({
// __N is used to identify if the history entry can be handled by the old router.
// __N is used to identify if the history entry can be handled by the old router.
const
historyState
=
{
__NA
:
true
,
tree
}
const
historyState
=
{
__NA
:
true
,
tree
}
if
(
pushRef
.
pendingPush
)
{
if
(
pushRef
.
pendingPush
)
{
// This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.
pushRef
.
pendingPush
=
false
pushRef
.
pendingPush
=
false
window
.
history
.
pushState
(
historyState
,
''
,
canonicalUrl
)
window
.
history
.
pushState
(
historyState
,
''
,
canonicalUrl
)
...
@@ -215,11 +248,18 @@ export default function AppRouter({
...
@@ -215,11 +248,18 @@ export default function AppRouter({
}
}
},
[
tree
,
pushRef
,
canonicalUrl
])
},
[
tree
,
pushRef
,
canonicalUrl
])
// Add `window.nd` for debugging purposes.
// This is not meant for use in applications as concurrent rendering will affect the cache/tree/router.
if
(
typeof
window
!==
'undefined'
)
{
if
(
typeof
window
!==
'undefined'
)
{
// @ts-ignore this is for debugging
// @ts-ignore this is for debugging
window
.
nd
=
{
router
:
appRouter
,
cache
,
tree
}
window
.
nd
=
{
router
:
appRouter
,
cache
,
tree
}
}
}
/**
* Handle popstate event, this is used to handle back/forward in the browser.
* By default dispatches ACTION_RESTORE, however if the history entry was not pushed/replaced by app-router it will reload the page.
* That case can happen when the old router injected the history entry.
*/
const
onPopState
=
React
.
useCallback
(({
state
}:
PopStateEvent
)
=>
{
const
onPopState
=
React
.
useCallback
(({
state
}:
PopStateEvent
)
=>
{
if
(
!
state
)
{
if
(
!
state
)
{
// TODO-APP: this case only happens when pushState/replaceState was called outside of Next.js. It should probably reload the page in this case.
// TODO-APP: this case only happens when pushState/replaceState was called outside of Next.js. It should probably reload the page in this case.
...
@@ -238,15 +278,14 @@ export default function AppRouter({
...
@@ -238,15 +278,14 @@ export default function AppRouter({
// Without startTransition works if the cache is there for this path
// Without startTransition works if the cache is there for this path
React
.
startTransition
(()
=>
{
React
.
startTransition
(()
=>
{
dispatch
({
dispatch
({
type
:
'restore'
,
type
:
ACTION_RESTORE
,
payload
:
{
url
:
new
URL
(
window
.
location
.
href
),
url
:
new
URL
(
window
.
location
.
href
),
tree
:
state
.
tree
,
tree
:
state
.
tree
,
},
})
})
})
})
},
[])
},
[])
// Register popstate event to call onPopstate.
React
.
useEffect
(()
=>
{
React
.
useEffect
(()
=>
{
window
.
addEventListener
(
'popstate'
,
onPopState
)
window
.
addEventListener
(
'popstate'
,
onPopState
)
return
()
=>
{
return
()
=>
{
...
@@ -255,8 +294,8 @@ export default function AppRouter({
...
@@ -255,8 +294,8 @@ export default function AppRouter({
},
[
onPopState
])
},
[
onPopState
])
return
(
return
(
<
PathnameContext
.
Provider
value=
{
pathname
}
>
<
PathnameContext
.
Provider
value=
{
pathname
}
>
<
QueryContext
.
Provider
value=
{
query
}
>
<
SearchParamsContext
.
Provider
value=
{
searchParams
}
>
<
FullAppTree
Context
.
Provider
<
GlobalLayoutRouter
Context
.
Provider
value=
{
{
value=
{
{
changeByServerResponse
,
changeByServerResponse
,
tree
,
tree
,
...
@@ -274,12 +313,20 @@ export default function AppRouter({
...
@@ -274,12 +313,20 @@ export default function AppRouter({
stylesheets
:
initialStylesheets
,
stylesheets
:
initialStylesheets
,
}
}
}
}
>
>
<
ErrorOverlay
>
{
cache
.
subTreeData
}
</
ErrorOverlay
>
<
ErrorOverlay
>
{
hotReloader
}
{
// ErrorOverlay intentionally only wraps the children of app-router.
cache
.
subTreeData
}
</
ErrorOverlay
>
{
// HotReloader uses the router tree and router.reload() in order to apply Server Component changes.
hotReloader
}
</
AppTreeContext
.
Provider
>
</
AppTreeContext
.
Provider
>
</
AppRouterContext
.
Provider
>
</
AppRouterContext
.
Provider
>
</
FullAppTree
Context
.
Provider
>
</
GlobalLayoutRouter
Context
.
Provider
>
</
Query
Context
.
Provider
>
</
SearchParams
Context
.
Provider
>
</
PathnameContext
.
Provider
>
</
PathnameContext
.
Provider
>
)
)
}
}
packages/next/client/components/hooks-client-context.ts
View file @
07c3464a
import
{
createContext
}
from
'react'
import
{
createContext
}
from
'react'
import
{
NextParsedUrlQuery
}
from
'../../server/request-meta'
import
{
NextParsedUrlQuery
}
from
'../../server/request-meta'
export
const
QueryContext
=
createContext
<
NextParsedUrlQuery
>
(
null
as
any
)
export
const
SearchParamsContext
=
createContext
<
NextParsedUrlQuery
>
(
null
as
any
)
export
const
PathnameContext
=
createContext
<
string
>
(
null
as
any
)
export
const
PathnameContext
=
createContext
<
string
>
(
null
as
any
)
export
const
ParamsContext
=
createContext
(
null
as
any
)
export
const
ParamsContext
=
createContext
(
null
as
any
)
export
const
LayoutSegmentsContext
=
createContext
(
null
as
any
)
export
const
LayoutSegmentsContext
=
createContext
(
null
as
any
)
if
(
process
.
env
.
NODE_ENV
!==
'production'
)
{
if
(
process
.
env
.
NODE_ENV
!==
'production'
)
{
QueryContext
.
displayName
=
'Query
Context'
SearchParamsContext
.
displayName
=
'SearchParams
Context'
PathnameContext
.
displayName
=
'PathnameContext'
PathnameContext
.
displayName
=
'PathnameContext'
ParamsContext
.
displayName
=
'ParamsContext'
ParamsContext
.
displayName
=
'ParamsContext'
LayoutSegmentsContext
.
displayName
=
'LayoutSegmentsContext'
LayoutSegmentsContext
.
displayName
=
'LayoutSegmentsContext'
...
...
packages/next/client/components/hooks-client.ts
View file @
07c3464a
...
@@ -2,7 +2,7 @@
...
@@ -2,7 +2,7 @@
import
{
useContext
}
from
'react'
import
{
useContext
}
from
'react'
import
{
import
{
Query
Context
,
SearchParams
Context
,
// ParamsContext,
// ParamsContext,
PathnameContext
,
PathnameContext
,
// LayoutSegmentsContext,
// LayoutSegmentsContext,
...
@@ -13,11 +13,11 @@ import {
...
@@ -13,11 +13,11 @@ import {
}
from
'../../shared/lib/app-router-context'
}
from
'../../shared/lib/app-router-context'
export
function
useSearchParams
()
{
export
function
useSearchParams
()
{
return
useContext
(
Query
Context
)
return
useContext
(
SearchParams
Context
)
}
}
export
function
useSearchParam
(
key
:
string
):
string
|
string
[]
{
export
function
useSearchParam
(
key
:
string
):
string
|
string
[]
{
const
params
=
useContext
(
Query
Context
)
const
params
=
useContext
(
SearchParams
Context
)
return
params
[
key
]
return
params
[
key
]
}
}
...
...
packages/next/client/components/hot-reloader.client.tsx
View file @
07c3464a
...
@@ -6,7 +6,7 @@ import {
...
@@ -6,7 +6,7 @@ import {
// @ts-expect-error TODO-APP: startTransition exists
// @ts-expect-error TODO-APP: startTransition exists
startTransition
,
startTransition
,
}
from
'react'
}
from
'react'
import
{
FullAppTree
Context
}
from
'../../shared/lib/app-router-context'
import
{
GlobalLayoutRouter
Context
}
from
'../../shared/lib/app-router-context'
import
{
import
{
register
,
register
,
unregister
,
unregister
,
...
@@ -397,7 +397,7 @@ function processMessage(
...
@@ -397,7 +397,7 @@ function processMessage(
}
}
export
default
function
HotReload
({
assetPrefix
}:
{
assetPrefix
:
string
})
{
export
default
function
HotReload
({
assetPrefix
}:
{
assetPrefix
:
string
})
{
const
{
tree
}
=
useContext
(
FullAppTree
Context
)
const
{
tree
}
=
useContext
(
GlobalLayoutRouter
Context
)
const
router
=
useRouter
()
const
router
=
useRouter
()
const
webSocketRef
=
useRef
<
WebSocket
>
()
const
webSocketRef
=
useRef
<
WebSocket
>
()
...
...
packages/next/client/components/layout-router.client.tsx
View file @
07c3464a
...
@@ -8,7 +8,7 @@ import type {
...
@@ -8,7 +8,7 @@ import type {
}
from
'../../server/app-render'
}
from
'../../server/app-render'
import
{
import
{
AppTreeContext
,
AppTreeContext
,
FullAppTree
Context
,
GlobalLayoutRouter
Context
,
}
from
'../../shared/lib/app-router-context'
}
from
'../../shared/lib/app-router-context'
import
{
fetchServerResponse
}
from
'./app-router.client'
import
{
fetchServerResponse
}
from
'./app-router.client'
import
{
matchSegment
}
from
'./match-segments'
import
{
matchSegment
}
from
'./match-segments'
...
@@ -72,7 +72,7 @@ export function InnerLayoutRouter({
...
@@ -72,7 +72,7 @@ export function InnerLayoutRouter({
changeByServerResponse
,
changeByServerResponse
,
tree
:
fullTree
,
tree
:
fullTree
,
focusRef
,
focusRef
,
}
=
useContext
(
FullAppTree
Context
)
}
=
useContext
(
GlobalLayoutRouter
Context
)
const
focusAndScrollRef
=
useRef
<
HTMLDivElement
>
(
null
)
const
focusAndScrollRef
=
useRef
<
HTMLDivElement
>
(
null
)
useEffect
(()
=>
{
useEffect
(()
=>
{
...
...
packages/next/client/components/reducer.ts
View file @
07c3464a
...
@@ -7,11 +7,11 @@ import type {
...
@@ -7,11 +7,11 @@ import type {
import
{
matchSegment
}
from
'./match-segments'
import
{
matchSegment
}
from
'./match-segments'
import
{
fetchServerResponse
}
from
'./app-router.client'
import
{
fetchServerResponse
}
from
'./app-router.client'
const
fillCacheWithNewSubTreeData
=
(
function
fillCacheWithNewSubTreeData
(
newCache
:
CacheNode
,
newCache
:
CacheNode
,
existingCache
:
CacheNode
,
existingCache
:
CacheNode
,
flightDataPath
:
FlightDataPath
flightDataPath
:
FlightDataPath
)
=>
{
)
:
void
{
const
isLastEntry
=
flightDataPath
.
length
<=
4
const
isLastEntry
=
flightDataPath
.
length
<=
4
const
[
parallelRouteKey
,
segment
]
=
flightDataPath
const
[
parallelRouteKey
,
segment
]
=
flightDataPath
...
@@ -35,7 +35,7 @@ const fillCacheWithNewSubTreeData = (
...
@@ -35,7 +35,7 @@ const fillCacheWithNewSubTreeData = (
const
existingChildCacheNode
=
existingChildSegmentMap
.
get
(
segmentForCache
)
const
existingChildCacheNode
=
existingChildSegmentMap
.
get
(
segmentForCache
)
let
childCacheNode
=
childSegmentMap
.
get
(
segmentForCache
)
let
childCacheNode
=
childSegmentMap
.
get
(
segmentForCache
)
// In case of last segment start
off
the fetch at this level and don't copy further down.
// In case of last segment start the fetch at this level and don't copy further down.
if
(
isLastEntry
)
{
if
(
isLastEntry
)
{
if
(
if
(
!
childCacheNode
||
!
childCacheNode
||
...
@@ -73,12 +73,12 @@ const fillCacheWithNewSubTreeData = (
...
@@ -73,12 +73,12 @@ const fillCacheWithNewSubTreeData = (
)
)
}
}
const
fillCacheWithDataProperty
=
(
function
fillCacheWithDataProperty
(
newCache
:
CacheNode
,
newCache
:
CacheNode
,
existingCache
:
CacheNode
,
existingCache
:
CacheNode
,
segments
:
string
[],
segments
:
string
[],
fetchResponse
:
any
fetchResponse
:
any
):
{
bailOptimistic
:
boolean
}
|
undefined
=>
{
):
{
bailOptimistic
:
boolean
}
|
undefined
{
const
isLastEntry
=
segments
.
length
===
1
const
isLastEntry
=
segments
.
length
===
1
const
parallelRouteKey
=
'children'
const
parallelRouteKey
=
'children'
...
@@ -148,10 +148,10 @@ const fillCacheWithDataProperty = (
...
@@ -148,10 +148,10 @@ const fillCacheWithDataProperty = (
)
)
}
}
const
canOptimisticallyRender
=
(
function
canOptimisticallyRender
(
segments
:
string
[],
segments
:
string
[],
flightRouterState
:
FlightRouterState
flightRouterState
:
FlightRouterState
):
boolean
=>
{
):
boolean
{
const
segment
=
segments
[
0
]
const
segment
=
segments
[
0
]
const
isLastSegment
=
segments
.
length
===
1
const
isLastSegment
=
segments
.
length
===
1
const
[
existingSegment
,
existingParallelRoutes
,
,
,
loadingMarker
]
=
const
[
existingSegment
,
existingParallelRoutes
,
,
,
loadingMarker
]
=
...
@@ -186,13 +186,13 @@ const canOptimisticallyRender = (
...
@@ -186,13 +186,13 @@ const canOptimisticallyRender = (
)
)
}
}
const
createOptimisticTree
=
(
function
createOptimisticTree
(
segments
:
string
[],
segments
:
string
[],
flightRouterState
:
FlightRouterState
|
null
,
flightRouterState
:
FlightRouterState
|
null
,
_isFirstSegment
:
boolean
,
_isFirstSegment
:
boolean
,
parentRefetch
:
boolean
,
parentRefetch
:
boolean
,
_href
?:
string
_href
?:
string
):
FlightRouterState
=>
{
):
FlightRouterState
{
const
[
existingSegment
,
existingParallelRoutes
]
=
flightRouterState
||
[
const
[
existingSegment
,
existingParallelRoutes
]
=
flightRouterState
||
[
null
,
null
,
{},
{},
...
@@ -238,7 +238,6 @@ const createOptimisticTree = (
...
@@ -238,7 +238,6 @@ const createOptimisticTree = (
// if (isFirstSegment) {
// if (isFirstSegment) {
// result[2] = href
// result[2] = href
// }
// }
// Copy the loading flag from existing tree
// Copy the loading flag from existing tree
if
(
flightRouterState
&&
flightRouterState
[
4
])
{
if
(
flightRouterState
&&
flightRouterState
[
4
])
{
result
[
4
]
=
flightRouterState
[
4
]
result
[
4
]
=
flightRouterState
[
4
]
...
@@ -247,11 +246,11 @@ const createOptimisticTree = (
...
@@ -247,11 +246,11 @@ const createOptimisticTree = (
return
result
return
result
}
}
const
walkTreeWithFlightDataPath
=
(
function
walkTreeWithFlightDataPath
(
flightSegmentPath
:
FlightData
[
0
],
flightSegmentPath
:
FlightData
[
0
],
flightRouterState
:
FlightRouterState
,
flightRouterState
:
FlightRouterState
,
treePatch
:
FlightRouterState
treePatch
:
FlightRouterState
):
FlightRouterState
=>
{
):
FlightRouterState
{
const
[
segment
,
parallelRoutes
/* , url */
]
=
flightRouterState
const
[
segment
,
parallelRoutes
/* , url */
]
=
flightRouterState
// Root refresh
// Root refresh
...
@@ -262,7 +261,6 @@ const walkTreeWithFlightDataPath = (
...
@@ -262,7 +261,6 @@ const walkTreeWithFlightDataPath = (
// if (url) {
// if (url) {
// tree[2] = url
// tree[2] = url
// }
// }
return
tree
return
tree
}
}
...
@@ -293,7 +291,6 @@ const walkTreeWithFlightDataPath = (
...
@@ -293,7 +291,6 @@ const walkTreeWithFlightDataPath = (
// if (url) {
// if (url) {
// tree[2] = url
// tree[2] = url
// }
// }
// Copy loading flag
// Copy loading flag
if
(
flightRouterState
[
4
])
{
if
(
flightRouterState
[
4
])
{
tree
[
4
]
=
flightRouterState
[
4
]
tree
[
4
]
=
flightRouterState
[
4
]
...
@@ -303,11 +300,20 @@ const walkTreeWithFlightDataPath = (
...
@@ -303,11 +300,20 @@ const walkTreeWithFlightDataPath = (
}
}
type
PushRef
=
{
type
PushRef
=
{
/**
* If the app-router should push a new history entry in useEffect()
*/
pendingPush
:
boolean
pendingPush
:
boolean
/**
* Multi-page navigation through location.href.
*/
mpaNavigation
:
boolean
mpaNavigation
:
boolean
}
}
export
type
FocusRef
=
{
export
type
FocusRef
=
{
/**
* If focus should be set in the layout-router's useEffect()
*/
focus
:
boolean
focus
:
boolean
}
}
...
@@ -319,12 +325,16 @@ type AppRouterState = {
...
@@ -319,12 +325,16 @@ type AppRouterState = {
canonicalUrl
:
string
canonicalUrl
:
string
}
}
export
const
ACTION_RELOAD
=
'reload'
export
const
ACTION_NAVIGATE
=
'navigate'
export
const
ACTION_RESTORE
=
'restore'
export
const
ACTION_SERVER_PATCH
=
'server-patch'
export
function
reducer
(
export
function
reducer
(
state
:
AppRouterState
,
state
:
AppRouterState
,
action
:
action
:
|
{
|
{
type
:
'reload'
type
:
typeof
ACTION_RELOAD
payload
:
{
url
:
URL
url
:
URL
cache
:
CacheNode
cache
:
CacheNode
mutable
:
{
mutable
:
{
...
@@ -332,10 +342,9 @@ export function reducer(
...
@@ -332,10 +342,9 @@ export function reducer(
patchedTree
?:
FlightRouterState
patchedTree
?:
FlightRouterState
}
}
}
}
}
|
{
|
{
type
:
'navigate'
type
:
typeof
ACTION_NAVIGATE
payload
:
{
url
:
URL
url
:
URL
cacheType
:
'soft'
|
'hard'
cacheType
:
'soft'
|
'hard'
navigateType
:
'push'
|
'replace'
navigateType
:
'push'
|
'replace'
...
@@ -345,19 +354,21 @@ export function reducer(
...
@@ -345,19 +354,21 @@ export function reducer(
patchedTree
?:
FlightRouterState
patchedTree
?:
FlightRouterState
}
}
}
}
|
{
type
:
typeof
ACTION_RESTORE
url
:
URL
tree
:
FlightRouterState
}
}
|
{
type
:
'restore'
;
payload
:
{
url
:
URL
;
tree
:
FlightRouterState
}
}
|
{
|
{
type
:
'server-patch'
type
:
typeof
ACTION_SERVER_PATCH
payload
:
{
flightData
:
FlightData
flightData
:
FlightData
previousTree
:
FlightRouterState
previousTree
:
FlightRouterState
cache
:
CacheNode
cache
:
CacheNode
}
}
}
):
AppRouterState
{
):
AppRouterState
{
if
(
action
.
type
===
'restore'
)
{
switch
(
action
.
type
)
{
const
{
url
,
tree
}
=
action
.
payload
case
ACTION_RESTORE
:
{
const
{
url
,
tree
}
=
action
const
href
=
url
.
pathname
+
url
.
search
+
url
.
hash
const
href
=
url
.
pathname
+
url
.
search
+
url
.
hash
return
{
return
{
...
@@ -368,9 +379,8 @@ export function reducer(
...
@@ -368,9 +379,8 @@ export function reducer(
tree
:
tree
,
tree
:
tree
,
}
}
}
}
case
ACTION_NAVIGATE
:
{
if
(
action
.
type
===
'navigate'
)
{
const
{
url
,
cacheType
,
navigateType
,
cache
,
mutable
}
=
action
const
{
url
,
cacheType
,
navigateType
,
cache
,
mutable
}
=
action
.
payload
const
pendingPush
=
navigateType
===
'push'
?
true
:
false
const
pendingPush
=
navigateType
===
'push'
?
true
:
false
const
{
pathname
}
=
url
const
{
pathname
}
=
url
const
href
=
url
.
pathname
+
url
.
search
+
url
.
hash
const
href
=
url
.
pathname
+
url
.
search
+
url
.
hash
...
@@ -472,7 +482,6 @@ export function reducer(
...
@@ -472,7 +482,6 @@ export function reducer(
cache
.
data
=
null
cache
.
data
=
null
// TODO-APP: ensure flightDataPath does not have "" as first item
const
flightDataPath
=
flightData
[
0
]
const
flightDataPath
=
flightData
[
0
]
const
[
treePatch
]
=
flightDataPath
.
slice
(
-
2
)
const
[
treePatch
]
=
flightDataPath
.
slice
(
-
2
)
...
@@ -501,9 +510,8 @@ export function reducer(
...
@@ -501,9 +510,8 @@ export function reducer(
return
state
return
state
}
}
case
ACTION_SERVER_PATCH
:
{
if
(
action
.
type
===
'server-patch'
)
{
const
{
flightData
,
previousTree
,
cache
}
=
action
const
{
flightData
,
previousTree
,
cache
}
=
action
.
payload
if
(
JSON
.
stringify
(
previousTree
)
!==
JSON
.
stringify
(
state
.
tree
))
{
if
(
JSON
.
stringify
(
previousTree
)
!==
JSON
.
stringify
(
state
.
tree
))
{
// TODO-APP: Handle tree mismatch
// TODO-APP: Handle tree mismatch
console
.
log
(
'TREE MISMATCH'
)
console
.
log
(
'TREE MISMATCH'
)
...
@@ -552,9 +560,8 @@ export function reducer(
...
@@ -552,9 +560,8 @@ export function reducer(
cache
:
cache
,
cache
:
cache
,
}
}
}
}
case
ACTION_RELOAD
:
{
if
(
action
.
type
===
'reload'
)
{
const
{
url
,
cache
,
mutable
}
=
action
const
{
url
,
cache
,
mutable
}
=
action
.
payload
const
href
=
url
.
pathname
+
url
.
search
+
url
.
hash
const
href
=
url
.
pathname
+
url
.
search
+
url
.
hash
const
pendingPush
=
false
const
pendingPush
=
false
...
@@ -628,6 +635,7 @@ export function reducer(
...
@@ -628,6 +635,7 @@ export function reducer(
tree
:
newTree
,
tree
:
newTree
,
}
}
}
}
default
:
return
state
throw
new
Error
(
'Unknown action'
)
}
}
}
packages/next/server/app-render.tsx
View file @
07c3464a
...
@@ -830,18 +830,9 @@ export async function renderToHTML(
...
@@ -830,18 +830,9 @@ export async function renderToHTML(
const
AppRouter
=
const
AppRouter
=
ComponentMod
.
AppRouter
as
typeof
import
(
'../client/components/app-router.client'
).
default
ComponentMod
.
AppRouter
as
typeof
import
(
'../client/components/app-router.client'
).
default
const
{
QueryContext
,
PathnameContext
,
// ParamsContext,
// LayoutSegmentsContext,
}
=
ComponentMod
.
hooksClientContext
as
typeof
import
(
'../client/components/hooks-client-context'
)
const
WrappedComponentTreeWithRouter
=
()
=>
{
const
WrappedComponentTreeWithRouter
=
()
=>
{
return
(
return
(
<
QueryContext
.
Provider
value=
{
query
}
>
<
PathnameContext
.
Provider
value=
{
pathname
}
>
{
/* <ParamsContext.Provider value={pathParams}> */
}
<
AppRouter
<
AppRouter
hotReloader=
{
HotReloader
&&
<
HotReloader
assetPrefix=
""
/>
}
hotReloader=
{
HotReloader
&&
<
HotReloader
assetPrefix=
""
/>
}
initialCanonicalUrl=
{
initialCanonicalUrl
}
initialCanonicalUrl=
{
initialCanonicalUrl
}
...
@@ -850,9 +841,6 @@ export async function renderToHTML(
...
@@ -850,9 +841,6 @@ export async function renderToHTML(
>
>
<
ComponentTree
/>
<
ComponentTree
/>
</
AppRouter
>
</
AppRouter
>
{
/* </ParamsContext.Provider> */
}
</
PathnameContext
.
Provider
>
</
QueryContext
.
Provider
>
)
)
}
}
...
...
packages/next/shared/lib/app-router-context.ts
View file @
07c3464a
...
@@ -14,11 +14,33 @@ export type CacheNode = {
...
@@ -14,11 +14,33 @@ export type CacheNode = {
}
}
export
type
AppRouterInstance
=
{
export
type
AppRouterInstance
=
{
/**
* Reload the current page. Fetches new data from the server.
*/
reload
():
void
reload
():
void
/**
* Hard navigate to the provided href. Fetches new data from the server.
* Pushes a new history entry.
*/
push
(
href
:
string
):
void
push
(
href
:
string
):
void
/**
* Soft navigate to the provided href. Does not fetch data from the server if it was already fetched.
* Pushes a new history entry.
*/
softPush
(
href
:
string
):
void
softPush
(
href
:
string
):
void
/**
* Hard navigate to the provided href. Does not fetch data from the server if it was already fetched.
* Replaces the current history entry.
*/
replace
(
href
:
string
):
void
replace
(
href
:
string
):
void
/**
* Soft navigate to the provided href. Does not fetch data from the server if it was already fetched.
* Replaces the current history entry.
*/
softReplace
(
href
:
string
):
void
softReplace
(
href
:
string
):
void
/**
* Soft prefetch the provided href. Does not fetch data from the server if it was already fetched.
*/
prefetch
(
href
:
string
):
Promise
<
void
>
prefetch
(
href
:
string
):
Promise
<
void
>
}
}
...
@@ -31,7 +53,7 @@ export const AppTreeContext = React.createContext<{
...
@@ -31,7 +53,7 @@ export const AppTreeContext = React.createContext<{
url
:
string
url
:
string
stylesheets
?:
string
[]
stylesheets
?:
string
[]
}
>
(
null
as
any
)
}
>
(
null
as
any
)
export
const
FullAppTree
Context
=
React
.
createContext
<
{
export
const
GlobalLayoutRouter
Context
=
React
.
createContext
<
{
tree
:
FlightRouterState
tree
:
FlightRouterState
changeByServerResponse
:
(
changeByServerResponse
:
(
previousTree
:
FlightRouterState
,
previousTree
:
FlightRouterState
,
...
@@ -43,5 +65,5 @@ export const FullAppTreeContext = React.createContext<{
...
@@ -43,5 +65,5 @@ export const FullAppTreeContext = React.createContext<{
if
(
process
.
env
.
NODE_ENV
!==
'production'
)
{
if
(
process
.
env
.
NODE_ENV
!==
'production'
)
{
AppRouterContext
.
displayName
=
'AppRouterContext'
AppRouterContext
.
displayName
=
'AppRouterContext'
AppTreeContext
.
displayName
=
'AppTreeContext'
AppTreeContext
.
displayName
=
'AppTreeContext'
FullAppTreeContext
.
displayName
=
'FullAppTree
Context'
GlobalLayoutRouterContext
.
displayName
=
'GlobalLayoutRouter
Context'
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment