-
Notifications
You must be signed in to change notification settings - Fork 27.1k
/
app-router.tsx
787 lines (713 loc) · 24.7 KB
/
app-router.tsx
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
'use client'
import type { ReactNode } from 'react'
import React, {
use,
useEffect,
useMemo,
useCallback,
startTransition,
useInsertionEffect,
useDeferredValue,
} from 'react'
import {
AppRouterContext,
LayoutRouterContext,
GlobalLayoutRouterContext,
MissingSlotContext,
} from '../../shared/lib/app-router-context.shared-runtime'
import type {
CacheNode,
AppRouterInstance,
} from '../../shared/lib/app-router-context.shared-runtime'
import type { ErrorComponent } from './error-boundary'
import {
ACTION_FAST_REFRESH,
ACTION_NAVIGATE,
ACTION_PREFETCH,
ACTION_REFRESH,
ACTION_RESTORE,
ACTION_SERVER_ACTION,
ACTION_SERVER_PATCH,
PrefetchKind,
} from './router-reducer/router-reducer-types'
import type {
AppRouterState,
ReducerActions,
RouterChangeByServerResponse,
RouterNavigate,
ServerActionDispatcher,
} from './router-reducer/router-reducer-types'
import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import {
SearchParamsContext,
PathnameContext,
PathParamsContext,
} from '../../shared/lib/hooks-client-context.shared-runtime'
import {
useReducerWithReduxDevtools,
useUnwrapState,
type ReduxDevtoolsSyncFn,
} 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'
import { isBot } from '../../shared/lib/router/utils/is-bot'
import { addBasePath } from '../add-base-path'
import { AppRouterAnnouncer } from './app-router-announcer'
import { RedirectBoundary } from './redirect-boundary'
import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache'
import { unresolvedThenable } from './unresolved-thenable'
import { NEXT_RSC_UNION_QUERY } from './app-router-headers'
import { removeBasePath } from '../remove-base-path'
import { hasBasePath } from '../has-base-path'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import type { Params } from '../../shared/lib/router/utils/route-matcher'
import type { FlightRouterState } from '../../server/app-render/types'
const isServer = typeof window === 'undefined'
// Ensure the initialParallelRoutes are not combined because of double-rendering in the browser with Strict Mode.
let initialParallelRoutes: CacheNode['parallelRoutes'] = isServer
? null!
: new Map()
let globalServerActionDispatcher = null as ServerActionDispatcher | null
export function getServerActionDispatcher() {
return globalServerActionDispatcher
}
const globalMutable: {
pendingMpaPath?: string
} = {}
export function urlToUrlWithoutFlightMarker(url: string): URL {
const urlWithoutFlightParameters = new URL(url, location.origin)
urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY)
if (process.env.NODE_ENV === 'production') {
if (
process.env.__NEXT_CONFIG_OUTPUT === 'export' &&
urlWithoutFlightParameters.pathname.endsWith('.txt')
) {
const { pathname } = urlWithoutFlightParameters
const length = pathname.endsWith('/index.txt') ? 10 : 4
// Slice off `/index.txt` or `.txt` from the end of the pathname
urlWithoutFlightParameters.pathname = pathname.slice(0, -length)
}
}
return urlWithoutFlightParameters
}
// this function performs a depth-first search of the tree to find the selected
// params
function getSelectedParams(
currentTree: FlightRouterState,
params: Params = {}
): Params {
const parallelRoutes = currentTree[1]
for (const parallelRoute of Object.values(parallelRoutes)) {
const segment = parallelRoute[0]
const isDynamicParameter = Array.isArray(segment)
const segmentValue = isDynamicParameter ? segment[1] : segment
if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) continue
// Ensure catchAll and optional catchall are turned into an array
const isCatchAll =
isDynamicParameter && (segment[2] === 'c' || segment[2] === 'oc')
if (isCatchAll) {
params[segment[0]] = segment[1].split('/')
} else if (isDynamicParameter) {
params[segment[0]] = segment[1]
}
params = getSelectedParams(parallelRoute, params)
}
return params
}
type AppRouterProps = Omit<
Omit<InitialRouterStateParameters, 'isServer' | 'location'>,
'initialParallelRoutes'
> & {
buildId: string
initialHead: ReactNode
initialLayerAssets: ReactNode
assetPrefix: string
missingSlots: Set<string>
}
function isExternalURL(url: URL) {
return url.origin !== window.location.origin
}
function HistoryUpdater({
appRouterState,
sync,
}: {
appRouterState: AppRouterState
sync: ReduxDevtoolsSyncFn
}) {
useInsertionEffect(() => {
const { tree, pushRef, canonicalUrl } = appRouterState
const historyState = {
...(pushRef.preserveCustomHistoryState ? window.history.state : {}),
// Identifier is shortened intentionally.
// __NA is used to identify if the history entry can be handled by the app-router.
// __N is used to identify if the history entry can be handled by the old router.
__NA: true,
__PRIVATE_NEXTJS_INTERNALS_TREE: tree,
}
if (
pushRef.pendingPush &&
// Skip pushing an additional history entry if the canonicalUrl is the same as the current url.
// This mirrors the browser behavior for normal navigation.
createHrefFromUrl(new URL(window.location.href)) !== canonicalUrl
) {
// This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.
pushRef.pendingPush = false
window.history.pushState(historyState, '', canonicalUrl)
} else {
window.history.replaceState(historyState, '', canonicalUrl)
}
sync(appRouterState)
}, [appRouterState, sync])
return null
}
export function createEmptyCacheNode(): CacheNode {
return {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
layerAssets: null,
prefetchLayerAssets: null,
prefetchHead: null,
parallelRoutes: new Map(),
lazyDataResolved: false,
loading: null,
}
}
function useServerActionDispatcher(dispatch: React.Dispatch<ReducerActions>) {
const serverActionDispatcher: ServerActionDispatcher = useCallback(
(actionPayload) => {
startTransition(() => {
dispatch({
...actionPayload,
type: ACTION_SERVER_ACTION,
})
})
},
[dispatch]
)
globalServerActionDispatcher = serverActionDispatcher
}
/**
* Server response that only patches the cache and tree.
*/
function useChangeByServerResponse(
dispatch: React.Dispatch<ReducerActions>
): RouterChangeByServerResponse {
return useCallback(
({ previousTree, serverResponse }) => {
startTransition(() => {
dispatch({
type: ACTION_SERVER_PATCH,
previousTree,
serverResponse,
})
})
},
[dispatch]
)
}
function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
return useCallback(
(href, navigateType, shouldScroll) => {
const url = new URL(addBasePath(href), location.href)
return dispatch({
type: ACTION_NAVIGATE,
url,
isExternalUrl: isExternalURL(url),
locationSearch: location.search,
shouldScroll: shouldScroll ?? true,
navigateType,
})
},
[dispatch]
)
}
function copyNextJsInternalHistoryState(data: any) {
if (data == null) data = {}
const currentState = window.history.state
const __NA = currentState?.__NA
if (__NA) {
data.__NA = __NA
}
const __PRIVATE_NEXTJS_INTERNALS_TREE =
currentState?.__PRIVATE_NEXTJS_INTERNALS_TREE
if (__PRIVATE_NEXTJS_INTERNALS_TREE) {
data.__PRIVATE_NEXTJS_INTERNALS_TREE = __PRIVATE_NEXTJS_INTERNALS_TREE
}
return data
}
function Head({
headCacheNode,
}: {
headCacheNode: CacheNode | null
}): React.ReactNode {
// If this segment has a `prefetchHead`, it's the statically prefetched data.
// We should use that on initial render instead of `head`. Then we'll switch
// to `head` when the dynamic response streams in.
const head = headCacheNode !== null ? headCacheNode.head : null
const prefetchHead =
headCacheNode !== null ? headCacheNode.prefetchHead : null
// If no prefetch data is available, then we go straight to rendering `head`.
const resolvedPrefetchRsc = prefetchHead !== null ? prefetchHead : head
// We use `useDeferredValue` to handle switching between the prefetched and
// final values. The second argument is returned on initial render, then it
// re-renders with the first argument.
//
// @ts-expect-error The second argument to `useDeferredValue` is only
// available in the experimental builds. When its disabled, it will always
// return `head`.
return useDeferredValue(head, resolvedPrefetchRsc)
}
/**
* The global router that wraps the application components.
*/
function Router({
buildId,
initialHead,
initialLayerAssets,
initialTree,
initialCanonicalUrl,
initialSeedData,
couldBeIntercepted,
assetPrefix,
missingSlots,
}: AppRouterProps) {
const initialState = useMemo(
() =>
createInitialRouterState({
buildId,
initialSeedData,
initialCanonicalUrl,
initialTree,
initialParallelRoutes,
location: !isServer ? window.location : null,
initialHead,
initialLayerAssets,
couldBeIntercepted,
}),
[
buildId,
initialSeedData,
initialCanonicalUrl,
initialTree,
initialHead,
initialLayerAssets,
couldBeIntercepted,
]
)
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(
canonicalUrl,
typeof window === 'undefined' ? 'http://n' : window.location.href
)
return {
// This is turned into a readonly class in `useSearchParams`
searchParams: url.searchParams,
pathname: hasBasePath(url.pathname)
? removeBasePath(url.pathname)
: url.pathname,
}
}, [canonicalUrl])
const changeByServerResponse = useChangeByServerResponse(dispatch)
const navigate = useNavigate(dispatch)
useServerActionDispatcher(dispatch)
/**
* The app router that is exposed through `useRouter`. It's only concerned with dispatching actions to the reducer, does not hold state.
*/
const appRouter = useMemo<AppRouterInstance>(() => {
const routerInstance: AppRouterInstance = {
back: () => window.history.back(),
forward: () => window.history.forward(),
prefetch: (href, options) => {
// Don't prefetch for bots as they don't navigate.
// Don't prefetch during development (improves compilation performance)
if (
isBot(window.navigator.userAgent) ||
process.env.NODE_ENV === 'development'
) {
return
}
const url = new URL(addBasePath(href), window.location.href)
// External urls can't be prefetched in the same way.
if (isExternalURL(url)) {
return
}
startTransition(() => {
dispatch({
type: ACTION_PREFETCH,
url,
kind: options?.kind ?? PrefetchKind.FULL,
})
})
},
replace: (href, options = {}) => {
startTransition(() => {
navigate(href, 'replace', options.scroll ?? true)
})
},
push: (href, options = {}) => {
startTransition(() => {
navigate(href, 'push', options.scroll ?? true)
})
},
refresh: () => {
startTransition(() => {
dispatch({
type: ACTION_REFRESH,
origin: window.location.origin,
})
})
},
fastRefresh: () => {
if (process.env.NODE_ENV !== 'development') {
throw new Error(
'fastRefresh can only be used in development mode. Please use refresh instead.'
)
} else {
startTransition(() => {
dispatch({
type: ACTION_FAST_REFRESH,
origin: window.location.origin,
})
})
}
},
}
return routerInstance
}, [dispatch, navigate])
useEffect(() => {
// Exists for debugging purposes. Don't use in application code.
if (window.next) {
window.next.router = appRouter
}
}, [appRouter])
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(() => {
// Add `window.nd` for debugging purposes.
// This is not meant for use in applications as concurrent rendering will affect the cache/tree/router.
// @ts-ignore this is for debugging
window.nd = {
router: appRouter,
cache,
prefetchCache,
tree,
}
}, [appRouter, cache, prefetchCache, tree])
}
useEffect(() => {
// If the app is restored from bfcache, it's possible that
// pushRef.mpaNavigation is true, which would mean that any re-render of this component
// would trigger the mpa navigation logic again from the lines below.
// This will restore the router to the initial state in the event that the app is restored from bfcache.
function handlePageShow(event: PageTransitionEvent) {
if (
!event.persisted ||
!window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE
) {
return
}
// Clear the pendingMpaPath value so that a subsequent MPA navigation to the same URL can be triggered.
// This is necessary because if the browser restored from bfcache, the pendingMpaPath would still be set to the value
// of the last MPA navigation.
globalMutable.pendingMpaPath = undefined
dispatch({
type: ACTION_RESTORE,
url: new URL(window.location.href),
tree: window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE,
})
}
window.addEventListener('pageshow', handlePageShow)
return () => {
window.removeEventListener('pageshow', handlePageShow)
}
}, [dispatch])
// When mpaNavigation flag is set do a hard navigation to the new url.
// Infinitely suspend because we don't actually want to rerender any child
// components with the new URL and any entangled state updates shouldn't
// commit either (eg: useTransition isPending should stay true until the page
// unloads).
//
// This is a side effect in render. Don't try this at home, kids. It's
// 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) {
const location = window.location
if (pushRef.pendingPush) {
location.assign(canonicalUrl)
} else {
location.replace(canonicalUrl)
}
globalMutable.pendingMpaPath = canonicalUrl
}
// TODO-APP: Should we listen to navigateerror here to catch failed
// navigations somehow? And should we call window.stop() if a SPA navigation
// should interrupt an MPA one?
use(unresolvedThenable)
}
useEffect(() => {
const originalPushState = window.history.pushState.bind(window.history)
const originalReplaceState = window.history.replaceState.bind(
window.history
)
// Ensure the canonical URL in the Next.js Router is updated when the URL is changed so that `usePathname` and `useSearchParams` hold the pushed values.
const applyUrlFromHistoryPushReplace = (
url: string | URL | null | undefined
) => {
const href = window.location.href
const tree: FlightRouterState | undefined =
window.history.state?.__PRIVATE_NEXTJS_INTERNALS_TREE
startTransition(() => {
dispatch({
type: ACTION_RESTORE,
url: new URL(url ?? href, href),
tree,
})
})
}
/**
* Patch pushState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/
window.history.pushState = function pushState(
data: any,
_unused: string,
url?: string | URL | null
): void {
// Avoid a loop when Next.js internals trigger pushState/replaceState
if (data?.__NA || data?._N) {
return originalPushState(data, _unused, url)
}
data = copyNextJsInternalHistoryState(data)
if (url) {
applyUrlFromHistoryPushReplace(url)
}
return originalPushState(data, _unused, url)
}
/**
* Patch replaceState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/
window.history.replaceState = function replaceState(
data: any,
_unused: string,
url?: string | URL | null
): void {
// Avoid a loop when Next.js internals trigger pushState/replaceState
if (data?.__NA || data?._N) {
return originalReplaceState(data, _unused, url)
}
data = copyNextJsInternalHistoryState(data)
if (url) {
applyUrlFromHistoryPushReplace(url)
}
return originalReplaceState(data, _unused, url)
}
/**
* 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 = ({ state }: PopStateEvent) => {
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.
return
}
// This case happens when the history entry was pushed by the `pages` router.
if (!state.__NA) {
window.location.reload()
return
}
// TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously
// Without startTransition works if the cache is there for this path
startTransition(() => {
dispatch({
type: ACTION_RESTORE,
url: new URL(window.location.href),
tree: state.__PRIVATE_NEXTJS_INTERNALS_TREE,
})
})
}
// Register popstate event to call onPopstate.
window.addEventListener('popstate', onPopState)
return () => {
window.history.pushState = originalPushState
window.history.replaceState = originalReplaceState
window.removeEventListener('popstate', onPopState)
}
}, [dispatch])
const { cache, tree, nextUrl, focusAndScrollRef } =
useUnwrapState(reducerState)
const matchingHead = useMemo(() => {
return findHeadInCache(cache, tree[1])
}, [cache, tree])
// Add memoized pathParams for useParams.
const pathParams = useMemo(() => {
return getSelectedParams(tree)
}, [tree])
const layoutRouterContext = useMemo(() => {
return {
childNodes: cache.parallelRoutes,
tree,
// Root node always has `url`
// Provided in AppTreeContext to ensure it can be overwritten in layout-router
url: canonicalUrl,
loading: cache.loading,
}
}, [cache.parallelRoutes, tree, canonicalUrl, cache.loading])
const globalLayoutRouterContext = useMemo(() => {
return {
buildId,
changeByServerResponse,
tree,
focusAndScrollRef,
nextUrl,
}
}, [buildId, changeByServerResponse, tree, focusAndScrollRef, nextUrl])
let head
if (matchingHead !== null) {
// The head is wrapped in an extra component so we can use
// `useDeferredValue` to swap between the prefetched and final versions of
// the head. (This is what LayoutRouter does for segment data, too.)
//
// The `key` is used to remount the component whenever the head moves to
// a different segment.
const [headCacheNode, headKey] = matchingHead
head = <Head key={headKey} headCacheNode={headCacheNode} />
} else {
head = null
}
// We use `useDeferredValue` to handle switching between the prefetched and
// final values. The second argument is returned on initial render, then it
// re-renders with the first argument. We only use the prefetched layer assets
// if they are available. Otherwise, we use the non-prefetched version.
const resolvedPrefetchLayerAssets =
cache.prefetchLayerAssets !== null
? cache.prefetchLayerAssets
: cache.layerAssets
const layerAssets = useDeferredValue(
cache.layerAssets,
// @ts-expect-error The second argument to `useDeferredValue` is only
// available in the experimental builds. When its disabled, it will always
// return `cache.layerAssets`.
resolvedPrefetchLayerAssets
)
let content = (
<RedirectBoundary>
{head}
{layerAssets}
{cache.rsc}
<AppRouterAnnouncer tree={tree} />
</RedirectBoundary>
)
if (process.env.NODE_ENV !== 'production') {
if (typeof window !== 'undefined') {
const DevRootNotFoundBoundary: typeof import('./dev-root-not-found-boundary').DevRootNotFoundBoundary =
require('./dev-root-not-found-boundary').DevRootNotFoundBoundary
content = (
<DevRootNotFoundBoundary>
<MissingSlotContext.Provider value={missingSlots}>
{content}
</MissingSlotContext.Provider>
</DevRootNotFoundBoundary>
)
}
const HotReloader: typeof import('./react-dev-overlay/app/hot-reloader-client').default =
require('./react-dev-overlay/app/hot-reloader-client').default
content = <HotReloader assetPrefix={assetPrefix}>{content}</HotReloader>
}
return (
<>
<HistoryUpdater
appRouterState={useUnwrapState(reducerState)}
sync={sync}
/>
<RuntimeStyles />
<PathParamsContext.Provider value={pathParams}>
<PathnameContext.Provider value={pathname}>
<SearchParamsContext.Provider value={searchParams}>
<GlobalLayoutRouterContext.Provider
value={globalLayoutRouterContext}
>
<AppRouterContext.Provider value={appRouter}>
<LayoutRouterContext.Provider value={layoutRouterContext}>
{content}
</LayoutRouterContext.Provider>
</AppRouterContext.Provider>
</GlobalLayoutRouterContext.Provider>
</SearchParamsContext.Provider>
</PathnameContext.Provider>
</PathParamsContext.Provider>
</>
)
}
export default function AppRouter(
props: AppRouterProps & { globalErrorComponent: ErrorComponent }
) {
const { globalErrorComponent, ...rest } = props
return (
<ErrorBoundary errorComponent={globalErrorComponent}>
<Router {...rest} />
</ErrorBoundary>
)
}
const runtimeStyles = new Set<string>()
let runtimeStyleChanged = new Set<() => void>()
globalThis._N_E_STYLE_LOAD = function (href: string) {
let len = runtimeStyles.size
runtimeStyles.add(href)
if (runtimeStyles.size !== len) {
runtimeStyleChanged.forEach((cb) => cb())
}
// TODO figure out how to get a promise here
// But maybe it's not necessary as react would block rendering until it's loaded
return Promise.resolve()
}
function RuntimeStyles() {
const [, forceUpdate] = React.useState(0)
const renderedStylesSize = runtimeStyles.size
useEffect(() => {
const changed = () => forceUpdate((c) => c + 1)
runtimeStyleChanged.add(changed)
if (renderedStylesSize !== runtimeStyles.size) {
changed()
}
return () => {
runtimeStyleChanged.delete(changed)
}
}, [renderedStylesSize, forceUpdate])
const dplId = process.env.NEXT_DEPLOYMENT_ID
? `?dpl=${process.env.NEXT_DEPLOYMENT_ID}`
: ''
return [...runtimeStyles].map((href, i) => (
<link
key={i}
rel="stylesheet"
href={`${href}${dplId}`}
// @ts-ignore
precedence="next"
// TODO figure out crossOrigin and nonce
// crossOrigin={TODO}
// nonce={TODO}
/>
))
}