-
Notifications
You must be signed in to change notification settings - Fork 26.1k
/
reducer.ts
633 lines (543 loc) · 17.1 KB
/
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
import type { CacheNode } from '../../shared/lib/app-router-context'
import type {
FlightRouterState,
FlightData,
FlightDataPath,
} from '../../server/app-render'
import { matchSegment } from './match-segments'
import { fetchServerResponse } from './app-router.client'
const fillCacheWithNewSubTreeData = (
newCache: CacheNode,
existingCache: CacheNode,
flightDataPath: FlightDataPath
) => {
const isLastEntry = flightDataPath.length <= 4
const [parallelRouteKey, segment] = flightDataPath
const segmentForCache = Array.isArray(segment) ? segment[1] : segment
const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey)
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return
}
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap)
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)
}
const existingChildCacheNode = existingChildSegmentMap.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.
if (isLastEntry) {
if (
!childCacheNode ||
!childCacheNode.data ||
childCacheNode === existingChildCacheNode
) {
childSegmentMap.set(segmentForCache, {
data: null,
subTreeData: flightDataPath[3],
parallelRoutes: new Map(),
})
}
return
}
if (!childCacheNode || !existingChildCacheNode) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
data: childCacheNode.data,
subTreeData: childCacheNode.subTreeData,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
}
childSegmentMap.set(segmentForCache, childCacheNode)
}
fillCacheWithNewSubTreeData(
childCacheNode,
existingChildCacheNode,
flightDataPath.slice(2)
)
}
const fillCacheWithDataProperty = (
newCache: CacheNode,
existingCache: CacheNode,
segments: string[],
fetchResponse: any
): { bailOptimistic: boolean } | undefined => {
const isLastEntry = segments.length === 1
const parallelRouteKey = 'children'
const [segment] = segments
const existingChildSegmentMap =
existingCache.parallelRoutes.get(parallelRouteKey)
if (!existingChildSegmentMap) {
// Bailout because the existing cache does not have the path to the leaf node
// Will trigger lazy fetch in layout-router because of missing segment
return { bailOptimistic: true }
}
let childSegmentMap = newCache.parallelRoutes.get(parallelRouteKey)
if (!childSegmentMap || childSegmentMap === existingChildSegmentMap) {
childSegmentMap = new Map(existingChildSegmentMap)
newCache.parallelRoutes.set(parallelRouteKey, childSegmentMap)
}
const existingChildCacheNode = existingChildSegmentMap.get(segment)
let childCacheNode = childSegmentMap.get(segment)
// In case of last segment start off the fetch at this level and don't copy further down.
if (isLastEntry) {
if (
!childCacheNode ||
!childCacheNode.data ||
childCacheNode === existingChildCacheNode
) {
childSegmentMap.set(segment, {
data: fetchResponse(),
subTreeData: null,
parallelRoutes: new Map(),
})
}
return
}
if (!childCacheNode || !existingChildCacheNode) {
// Start fetch in the place where the existing cache doesn't have the data yet.
if (!childCacheNode) {
childSegmentMap.set(segment, {
data: fetchResponse(),
subTreeData: null,
parallelRoutes: new Map(),
})
}
return
}
if (childCacheNode === existingChildCacheNode) {
childCacheNode = {
data: childCacheNode.data,
subTreeData: childCacheNode.subTreeData,
parallelRoutes: new Map(childCacheNode.parallelRoutes),
}
childSegmentMap.set(segment, childCacheNode)
}
return fillCacheWithDataProperty(
childCacheNode,
existingChildCacheNode,
segments.slice(1),
fetchResponse
)
}
const canOptimisticallyRender = (
segments: string[],
flightRouterState: FlightRouterState
): boolean => {
const segment = segments[0]
const isLastSegment = segments.length === 1
const [existingSegment, existingParallelRoutes, , , loadingMarker] =
flightRouterState
// If the segments mismatch we can't resolve deeper into the tree
const segmentMatches = matchSegment(existingSegment, segment)
// If the segment mismatches we can't assume this level has loading
if (!segmentMatches) {
return false
}
const hasLoading = loadingMarker === 'loading'
// If the tree path holds at least one loading.js it will be optimistic
if (hasLoading) {
return true
}
// Above already catches the last segment case where `hasLoading` is true, so in this case it would always be `false`.
if (isLastSegment) {
return false
}
// If the existingParallelRoutes does not have a `children` parallelRouteKey we can't resolve deeper into the tree
if (!existingParallelRoutes.children) {
return hasLoading
}
// Resolve deeper in the tree as the current level did not have a loading marker
return canOptimisticallyRender(
segments.slice(1),
existingParallelRoutes.children
)
}
const createOptimisticTree = (
segments: string[],
flightRouterState: FlightRouterState | null,
_isFirstSegment: boolean,
parentRefetch: boolean,
_href?: string
): FlightRouterState => {
const [existingSegment, existingParallelRoutes] = flightRouterState || [
null,
{},
]
const segment = segments[0]
const isLastSegment = segments.length === 1
const segmentMatches =
existingSegment !== null && matchSegment(existingSegment, segment)
const shouldRefetchThisLevel = !flightRouterState || !segmentMatches
let parallelRoutes: FlightRouterState[1] = {}
if (existingSegment !== null && segmentMatches) {
parallelRoutes = existingParallelRoutes
}
let childTree
if (!isLastSegment) {
const childItem = createOptimisticTree(
segments.slice(1),
parallelRoutes ? parallelRoutes.children : null,
false,
parentRefetch || shouldRefetchThisLevel
)
childTree = childItem
}
const result: FlightRouterState = [
segment,
{
...parallelRoutes,
...(childTree ? { children: childTree } : {}),
},
]
if (!parentRefetch && shouldRefetchThisLevel) {
result[3] = 'refetch'
}
// TODO-APP: Revisit
// Add url into the tree
// if (isFirstSegment) {
// result[2] = href
// }
// Copy the loading flag from existing tree
if (flightRouterState && flightRouterState[4]) {
result[4] = flightRouterState[4]
}
return result
}
const walkTreeWithFlightDataPath = (
flightSegmentPath: FlightData[0],
flightRouterState: FlightRouterState,
treePatch: FlightRouterState
): FlightRouterState => {
const [segment, parallelRoutes /* , url */] = flightRouterState
// Root refresh
if (flightSegmentPath.length === 1) {
const tree: FlightRouterState = [...treePatch]
// TODO-APP: revisit
// if (url) {
// tree[2] = url
// }
return tree
}
const [currentSegment, parallelRouteKey] = flightSegmentPath
// Tree path returned from the server should always match up with the current tree in the browser
if (!matchSegment(currentSegment, segment)) {
throw new Error('SEGMENT MISMATCH')
}
const lastSegment = flightSegmentPath.length === 2
const tree: FlightRouterState = [
flightSegmentPath[0],
{
...parallelRoutes,
[parallelRouteKey]: lastSegment
? treePatch
: walkTreeWithFlightDataPath(
flightSegmentPath.slice(2),
parallelRoutes[parallelRouteKey],
treePatch
),
},
]
// TODO-APP: Revisit
// if (url) {
// tree[2] = url
// }
// Copy loading flag
if (flightRouterState[4]) {
tree[4] = flightRouterState[4]
}
return tree
}
type PushRef = {
pendingPush: boolean
mpaNavigation: boolean
}
export type FocusRef = {
focus: boolean
}
type AppRouterState = {
tree: FlightRouterState
cache: CacheNode
pushRef: PushRef
focusRef: FocusRef
canonicalUrl: string
}
export function reducer(
state: AppRouterState,
action:
| {
type: 'reload'
payload: {
url: URL
cache: CacheNode
mutable: {
previousTree?: FlightRouterState
patchedTree?: FlightRouterState
}
}
}
| {
type: 'navigate'
payload: {
url: URL
cacheType: 'soft' | 'hard'
navigateType: 'push' | 'replace'
cache: CacheNode
mutable: {
previousTree?: FlightRouterState
patchedTree?: FlightRouterState
}
}
}
| { type: 'restore'; payload: { url: URL; tree: FlightRouterState } }
| {
type: 'server-patch'
payload: {
flightData: FlightData
previousTree: FlightRouterState
cache: CacheNode
}
}
): AppRouterState {
if (action.type === 'restore') {
const { url, tree } = action.payload
const href = url.pathname + url.search + url.hash
return {
canonicalUrl: href,
pushRef: state.pushRef,
focusRef: state.focusRef,
cache: state.cache,
tree: tree,
}
}
if (action.type === 'navigate') {
const { url, cacheType, navigateType, cache, mutable } = action.payload
const pendingPush = navigateType === 'push' ? true : false
const { pathname } = url
const href = url.pathname + url.search + url.hash
const segments = pathname.split('/')
// TODO-APP: figure out something better for index pages
segments.push('')
// In case of soft push data fetching happens in layout-router if a segment is missing
if (cacheType === 'soft') {
const optimisticTree = createOptimisticTree(
segments,
state.tree,
true,
false,
href
)
return {
canonicalUrl: href,
pushRef: { pendingPush, mpaNavigation: false },
focusRef: { focus: true },
cache: state.cache,
tree: optimisticTree,
}
}
// When doing a hard push there can be two cases: with optimistic tree and without
// The with optimistic tree case only happens when the layouts have a loading state (loading.js)
// The without optimistic tree case happens when there is no loading state, in that case we suspend in this reducer
if (cacheType === 'hard') {
if (
mutable.patchedTree &&
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
) {
return {
canonicalUrl: href,
pushRef: { pendingPush, mpaNavigation: false },
focusRef: { focus: true },
cache: cache,
tree: mutable.patchedTree,
}
}
// TODO-APP: flag on the tree of which part of the tree for if there is a loading boundary
const isOptimistic = canOptimisticallyRender(segments, state.tree)
if (isOptimistic) {
// Build optimistic tree
// If the optimistic tree is deeper than the current state leave that deeper part out of the fetch
const optimisticTree = createOptimisticTree(
segments,
state.tree,
true,
false,
href
)
// Fill in the cache with blank that holds the `data` field.
// TODO-APP: segments.slice(1) strips '', we can get rid of '' altogether.
cache.subTreeData = state.cache.subTreeData
const res = fillCacheWithDataProperty(
cache,
state.cache,
segments.slice(1),
() => {
return fetchServerResponse(url, optimisticTree)
}
)
if (!res?.bailOptimistic) {
mutable.previousTree = state.tree
mutable.patchedTree = optimisticTree
return {
canonicalUrl: href,
pushRef: { pendingPush, mpaNavigation: false },
focusRef: { focus: true },
cache: cache,
tree: optimisticTree,
}
}
}
if (!cache.data) {
cache.data = fetchServerResponse(url, state.tree)
}
const flightData = cache.data.readRoot()
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return {
canonicalUrl: flightData,
pushRef: { pendingPush: true, mpaNavigation: true },
focusRef: { focus: false },
cache: state.cache,
tree: state.tree,
}
}
cache.data = null
// TODO-APP: ensure flightDataPath does not have "" as first item
const flightDataPath = flightData[0]
const [treePatch] = flightDataPath.slice(-2)
const treePath = flightDataPath.slice(0, -3)
const newTree = walkTreeWithFlightDataPath(
// TODO-APP: remove ''
['', ...treePath],
state.tree,
treePatch
)
mutable.previousTree = state.tree
mutable.patchedTree = newTree
cache.subTreeData = state.cache.subTreeData
fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath)
return {
canonicalUrl: href,
pushRef: { pendingPush, mpaNavigation: false },
focusRef: { focus: true },
cache: cache,
tree: newTree,
}
}
return state
}
if (action.type === 'server-patch') {
const { flightData, previousTree, cache } = action.payload
if (JSON.stringify(previousTree) !== JSON.stringify(state.tree)) {
// TODO-APP: Handle tree mismatch
console.log('TREE MISMATCH')
return {
canonicalUrl: state.canonicalUrl,
pushRef: state.pushRef,
focusRef: state.focusRef,
tree: state.tree,
cache: state.cache,
}
}
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return {
canonicalUrl: flightData,
pushRef: { pendingPush: true, mpaNavigation: true },
focusRef: { focus: false },
cache: state.cache,
tree: state.tree,
}
}
// TODO-APP: flightData could hold multiple paths
const flightDataPath = flightData[0]
// Slices off the last segment (which is at -3) as it doesn't exist in the tree yet
const treePath = flightDataPath.slice(0, -3)
const [treePatch] = flightDataPath.slice(-2)
const newTree = walkTreeWithFlightDataPath(
// TODO-APP: remove ''
['', ...treePath],
state.tree,
treePatch
)
cache.subTreeData = state.cache.subTreeData
fillCacheWithNewSubTreeData(cache, state.cache, flightDataPath)
return {
canonicalUrl: state.canonicalUrl,
pushRef: state.pushRef,
focusRef: state.focusRef,
tree: newTree,
cache: cache,
}
}
if (action.type === 'reload') {
const { url, cache, mutable } = action.payload
const href = url.pathname + url.search + url.hash
const pendingPush = false
// When doing a hard push there can be two cases: with optimistic tree and without
// The with optimistic tree case only happens when the layouts have a loading state (loading.js)
// The without optimistic tree case happens when there is no loading state, in that case we suspend in this reducer
if (
mutable.patchedTree &&
JSON.stringify(mutable.previousTree) === JSON.stringify(state.tree)
) {
return {
canonicalUrl: href,
pushRef: { pendingPush, mpaNavigation: false },
focusRef: { focus: true },
cache: cache,
tree: mutable.patchedTree,
}
}
if (!cache.data) {
cache.data = fetchServerResponse(url, [
state.tree[0],
state.tree[1],
state.tree[2],
'refetch',
])
}
const flightData = cache.data.readRoot()
// Handle case when navigating to page in `pages` from `app`
if (typeof flightData === 'string') {
return {
canonicalUrl: flightData,
pushRef: { pendingPush: true, mpaNavigation: true },
focusRef: { focus: false },
cache: state.cache,
tree: state.tree,
}
}
cache.data = null
const flightDataPath = flightData[0]
if (flightDataPath.length !== 2) {
// TODO-APP: handle this case better
console.log('RELOAD FAILED')
return state
}
const [treePatch, subTreeData] = flightDataPath.slice(-2)
const newTree = walkTreeWithFlightDataPath(
// TODO-APP: remove ''
[''],
state.tree,
treePatch
)
mutable.previousTree = state.tree
mutable.patchedTree = newTree
cache.subTreeData = subTreeData
return {
canonicalUrl: href,
pushRef: { pendingPush, mpaNavigation: false },
// TODO-APP: Revisit if this needs to be true in certain cases
focusRef: { focus: false },
cache: cache,
tree: newTree,
}
}
return state
}