-
Notifications
You must be signed in to change notification settings - Fork 26.3k
/
navigate-reducer.ts
554 lines (486 loc) · 20.5 KB
/
navigate-reducer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime'
import type {
FlightRouterState,
FlightSegmentPath,
} from '../../../../server/app-render/types'
import { fetchServerResponse } from '../fetch-server-response'
import { createHrefFromUrl } from '../create-href-from-url'
import { invalidateCacheBelowFlightSegmentPath } from '../invalidate-cache-below-flight-segmentpath'
import { applyRouterStatePatchToTree } from '../apply-router-state-patch-to-tree'
import { shouldHardNavigate } from '../should-hard-navigate'
import { isNavigatingToNewRootLayout } from '../is-navigating-to-new-root-layout'
import {
PrefetchCacheEntryStatus,
type Mutable,
type NavigateAction,
type ReadonlyReducerState,
type ReducerState,
} from '../router-reducer-types'
import { handleMutable } from '../handle-mutable'
import { applyFlightData } from '../apply-flight-data'
import { prefetchQueue } from './prefetch-reducer'
import { createEmptyCacheNode } from '../../app-router'
import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/segment'
import {
listenForDynamicRequest,
updateCacheNodeOnNavigation,
} from '../ppr-navigations'
import {
getOrCreatePrefetchCacheEntry,
prunePrefetchCache,
} from '../prefetch-cache-utils'
import { clearCacheNodeDataForSegmentPath } from '../clear-cache-node-data-for-segment-path'
export function handleExternalUrl(
state: ReadonlyReducerState,
mutable: Mutable,
url: string,
pendingPush: boolean
) {
mutable.mpaNavigation = true
mutable.canonicalUrl = url
mutable.pendingPush = pendingPush
mutable.scrollableSegments = undefined
return handleMutable(state, mutable)
}
function generateSegmentsFromPatch(
flightRouterPatch: FlightRouterState
): FlightSegmentPath[] {
const segments: FlightSegmentPath[] = []
const [segment, parallelRoutes] = flightRouterPatch
if (Object.keys(parallelRoutes).length === 0) {
return [[segment]]
}
for (const [parallelRouteKey, parallelRoute] of Object.entries(
parallelRoutes
)) {
for (const childSegment of generateSegmentsFromPatch(parallelRoute)) {
// If the segment is empty, it means we are at the root of the tree
if (segment === '') {
segments.push([parallelRouteKey, ...childSegment])
} else {
segments.push([segment, parallelRouteKey, ...childSegment])
}
}
}
return segments
}
function triggerLazyFetchForLeafSegments(
newCache: CacheNode,
currentCache: CacheNode,
flightSegmentPath: FlightSegmentPath,
treePatch: FlightRouterState
) {
let appliedPatch = false
newCache.rsc = currentCache.rsc
newCache.prefetchRsc = currentCache.prefetchRsc
newCache.loading = currentCache.loading
newCache.parallelRoutes = new Map(currentCache.parallelRoutes)
const segmentPathsToFill = generateSegmentsFromPatch(treePatch).map(
(segment) => [...flightSegmentPath, ...segment]
)
for (const segmentPaths of segmentPathsToFill) {
clearCacheNodeDataForSegmentPath(newCache, currentCache, segmentPaths)
appliedPatch = true
}
return appliedPatch
}
// These implementations are expected to diverge significantly, so I've forked
// the entire function. The one that's disabled should be dead code eliminated
// because the check here is statically inlined at build time.
export const navigateReducer = process.env.__NEXT_PPR
? navigateReducer_PPR
: navigateReducer_noPPR
// This is the implementation when PPR is disabled. We can assume its behavior
// is relatively stable because it's been running in production for a while.
function navigateReducer_noPPR(
state: ReadonlyReducerState,
action: NavigateAction
): ReducerState {
const { url, isExternalUrl, navigateType, shouldScroll } = action
const mutable: Mutable = {}
const { hash } = url
const href = createHrefFromUrl(url)
const pendingPush = navigateType === 'push'
// we want to prune the prefetch cache on every navigation to avoid it growing too large
prunePrefetchCache(state.prefetchCache)
mutable.preserveCustomHistoryState = false
if (isExternalUrl) {
return handleExternalUrl(state, mutable, url.toString(), pendingPush)
}
const prefetchValues = getOrCreatePrefetchCacheEntry({
url,
nextUrl: state.nextUrl,
tree: state.tree,
buildId: state.buildId,
prefetchCache: state.prefetchCache,
})
const { treeAtTimeOfPrefetch, data } = prefetchValues
prefetchQueue.bump(data)
return data.then(
([flightData, canonicalUrlOverride]) => {
let isFirstRead = false
// we only want to mark this once
if (!prefetchValues.lastUsedTime) {
// important: we should only mark the cache node as dirty after we unsuspend from the call above
prefetchValues.lastUsedTime = Date.now()
isFirstRead = true
}
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return handleExternalUrl(state, mutable, flightData, pendingPush)
}
// Handles case where `<meta http-equiv="refresh">` tag is present,
// which will trigger an MPA navigation.
if (document.getElementById('__next-page-redirect')) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
const updatedCanonicalUrl = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride)
: href
// Track if the navigation was only an update to the hash fragment
mutable.onlyHashChange =
!!hash &&
state.canonicalUrl.split('#', 1)[0] ===
updatedCanonicalUrl.split('#', 1)[0]
let currentTree = state.tree
const currentCache = state.cache
let scrollableSegments: FlightSegmentPath[] = []
for (const flightDataPath of flightData) {
const flightSegmentPath = flightDataPath.slice(
0,
-5
) as unknown as FlightSegmentPath
// The one before last item is the router state tree patch
const treePatch = flightDataPath.slice(-4)[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,
href
)
// 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 ''
flightSegmentPathWithLeadingEmpty,
treeAtTimeOfPrefetch,
treePatch,
href
)
}
if (newTree !== null) {
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
const cache: CacheNode = createEmptyCacheNode()
let applied = false
if (
prefetchValues.status === PrefetchCacheEntryStatus.stale &&
!mutable.onlyHashChange &&
!isFirstRead
) {
// When we have a stale prefetch entry, we only want to re-use the loading state of the route we're navigating to, to support instant loading navigations
// this will trigger a lazy fetch for the actual page data by nulling the `rsc` and `prefetchRsc` values for page data,
// while copying over the `loading` for the segment that contains the page data.
// We only do this on subsequent reads, as otherwise there'd be no loading data to re-use.
// We skip this branch if only the hash fragment has changed, as we don't want to trigger a lazy fetch in that case
applied = triggerLazyFetchForLeafSegments(
cache,
currentCache,
flightSegmentPath,
treePatch
)
// since we re-used the stale cache's loading state & refreshed the data,
// update the `lastUsedTime` so that it can continue to be re-used for the next 30s
prefetchValues.lastUsedTime = Date.now()
} else {
applied = applyFlightData(
currentCache,
cache,
flightDataPath,
prefetchValues
)
}
const hardNavigate = shouldHardNavigate(
// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty,
currentTree
)
if (hardNavigate) {
// Copy rsc for the root node of the cache.
cache.rsc = currentCache.rsc
cache.prefetchRsc = currentCache.prefetchRsc
invalidateCacheBelowFlightSegmentPath(
cache,
currentCache,
flightSegmentPath
)
// Ensure the existing cache value is used when the cache was not invalidated.
mutable.cache = cache
} else if (applied) {
mutable.cache = 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_SEGMENT_KEY
) {
scrollableSegments.push(scrollableSegmentPath)
}
}
}
}
mutable.patchedTree = currentTree
mutable.canonicalUrl = updatedCanonicalUrl
mutable.pendingPush = pendingPush
mutable.scrollableSegments = scrollableSegments
mutable.hashFragment = hash
mutable.shouldScroll = shouldScroll
return handleMutable(state, mutable)
},
() => state
)
}
// This is the experimental PPR implementation. It's closer to the behavior we
// want, but is likelier to include accidental regressions because it rewrites
// existing functionality.
function navigateReducer_PPR(
state: ReadonlyReducerState,
action: NavigateAction
): ReducerState {
const { url, isExternalUrl, navigateType, shouldScroll } = action
const mutable: Mutable = {}
const { hash } = url
const href = createHrefFromUrl(url)
const pendingPush = navigateType === 'push'
// we want to prune the prefetch cache on every navigation to avoid it growing too large
prunePrefetchCache(state.prefetchCache)
mutable.preserveCustomHistoryState = false
if (isExternalUrl) {
return handleExternalUrl(state, mutable, url.toString(), pendingPush)
}
const prefetchValues = getOrCreatePrefetchCacheEntry({
url,
nextUrl: state.nextUrl,
tree: state.tree,
buildId: state.buildId,
prefetchCache: state.prefetchCache,
})
const { treeAtTimeOfPrefetch, data } = prefetchValues
prefetchQueue.bump(data)
return data.then(
([flightData, canonicalUrlOverride, _postponed]) => {
let isFirstRead = false
// we only want to mark this once
if (!prefetchValues.lastUsedTime) {
// important: we should only mark the cache node as dirty after we unsuspend from the call above
prefetchValues.lastUsedTime = Date.now()
isFirstRead = true
}
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return handleExternalUrl(state, mutable, flightData, pendingPush)
}
// Handles case where `<meta http-equiv="refresh">` tag is present,
// which will trigger an MPA navigation.
if (document.getElementById('__next-page-redirect')) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
const updatedCanonicalUrl = canonicalUrlOverride
? createHrefFromUrl(canonicalUrlOverride)
: href
// Track if the navigation was only an update to the hash fragment
mutable.onlyHashChange =
!!hash &&
state.canonicalUrl.split('#', 1)[0] ===
updatedCanonicalUrl.split('#', 1)[0]
let currentTree = state.tree
const currentCache = state.cache
let scrollableSegments: FlightSegmentPath[] = []
// TODO: In practice, this is always a single item array. We probably
// aren't going to every send multiple segments, at least not in this
// format. So we could remove the extra wrapper for now until
// that settles.
for (const flightDataPath of flightData) {
const flightSegmentPath = flightDataPath.slice(
0,
-5
) as unknown as FlightSegmentPath
// The one before last item is the router state tree patch
const treePatch = flightDataPath.slice(-4)[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,
href
)
// 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 ''
flightSegmentPathWithLeadingEmpty,
treeAtTimeOfPrefetch,
treePatch,
href
)
}
if (newTree !== null) {
if (isNavigatingToNewRootLayout(currentTree, newTree)) {
return handleExternalUrl(state, mutable, href, pendingPush)
}
if (
// This is just a paranoid check. When PPR is enabled, the server
// will always send back a static response that's rendered from
// the root. If for some reason it doesn't, we fall back to the
// non-PPR implementation.
// TODO: We should get rid of the else branch and do all navigations
// via updateCacheNodeOnNavigation. The current structure is just
// an incremental step.
flightDataPath.length === 4
) {
const prefetchedTree: FlightRouterState = flightDataPath[0]
const seedData = flightDataPath[1]
const head = flightDataPath[2]
const layerAssets = flightDataPath[3]
const task = updateCacheNodeOnNavigation(
currentCache,
currentTree,
prefetchedTree,
seedData,
head,
layerAssets
)
if (task !== null && task.node !== null) {
// We've created a new Cache Node tree that contains a prefetched
// version of the next page. This can be rendered instantly.
// Use the tree computed by updateCacheNodeOnNavigation instead
// of the one computed by applyRouterStatePatchToTree.
// TODO: We should remove applyRouterStatePatchToTree
// from the PPR path entirely.
const patchedRouterState: FlightRouterState = task.route
newTree = patchedRouterState
const newCache = task.node
// The prefetched tree has dynamic holes in it. We initiate a
// dynamic request to fill them in.
//
// Do not block on the result. We'll immediately render the Cache
// Node tree and suspend on the dynamic parts. When the request
// comes in, we'll fill in missing data and ping React to
// re-render. Unlike the lazy fetching model in the non-PPR
// implementation, this is modeled as a single React update +
// streaming, rather than multiple top-level updates. (However,
// even in the new model, we'll still need to sometimes update the
// root multiple times per navigation, like if the server sends us
// a different response than we expected. For now, we revert back
// to the lazy fetching mechanism in that case.)
listenForDynamicRequest(
task,
fetchServerResponse(
url,
currentTree,
state.nextUrl,
state.buildId
)
)
mutable.cache = newCache
} else {
// Nothing changed, so reuse the old cache.
// TODO: What if the head changed but not any of the segment data?
// Is that possible? If so, we should clone the whole tree and
// update the head.
newTree = prefetchedTree
}
} else {
// The static response does not include any dynamic holes, so
// there's no need to do a second request.
// TODO: As an incremental step this just reverts back to the
// non-PPR implementation. We can simplify this branch further,
// given that PPR prefetches are always static and return the whole
// tree. Or in the meantime we could factor it out into a
// separate function.
const cache: CacheNode = createEmptyCacheNode()
let applied = false
if (
prefetchValues.status === PrefetchCacheEntryStatus.stale &&
!mutable.onlyHashChange &&
!isFirstRead
) {
// When we have a stale prefetch entry, we only want to re-use the loading state of the route we're navigating to, to support instant loading navigations
// this will trigger a lazy fetch for the actual page data by nulling the `rsc` and `prefetchRsc` values for page data,
// while copying over the `loading` for the segment that contains the page data.
// We only do this on subsequent reads, as otherwise there'd be no loading data to re-use.
// We skip this branch if only the hash fragment has changed, as we don't want to trigger a lazy fetch in that case
applied = triggerLazyFetchForLeafSegments(
cache,
currentCache,
flightSegmentPath,
treePatch
)
// since we re-used the stale cache's loading state & refreshed the data,
// update the `lastUsedTime` so that it can continue to be re-used for the next 30s
prefetchValues.lastUsedTime = Date.now()
} else {
applied = applyFlightData(
currentCache,
cache,
flightDataPath,
prefetchValues
)
}
const hardNavigate = shouldHardNavigate(
// TODO-APP: remove ''
flightSegmentPathWithLeadingEmpty,
currentTree
)
if (hardNavigate) {
// Copy rsc for the root node of the cache.
cache.rsc = currentCache.rsc
cache.prefetchRsc = currentCache.prefetchRsc
invalidateCacheBelowFlightSegmentPath(
cache,
currentCache,
flightSegmentPath
)
// Ensure the existing cache value is used when the cache was not invalidated.
mutable.cache = cache
} else if (applied) {
mutable.cache = 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_SEGMENT_KEY
) {
scrollableSegments.push(scrollableSegmentPath)
}
}
}
}
mutable.patchedTree = currentTree
mutable.canonicalUrl = updatedCanonicalUrl
mutable.pendingPush = pendingPush
mutable.scrollableSegments = scrollableSegments
mutable.hashFragment = hash
mutable.shouldScroll = shouldScroll
return handleMutable(state, mutable)
},
() => state
)
}