File size: 12,211 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
  ACTION_BEFORE_REFRESH,
  ACTION_BUILD_ERROR,
  ACTION_BUILD_OK,
  ACTION_DEBUG_INFO,
  ACTION_DEV_INDICATOR,
  ACTION_REFRESH,
  ACTION_ERROR_OVERLAY_CLOSE,
  ACTION_ERROR_OVERLAY_OPEN,
  ACTION_ERROR_OVERLAY_TOGGLE,
  ACTION_STATIC_INDICATOR,
  ACTION_UNHANDLED_ERROR,
  ACTION_UNHANDLED_REJECTION,
  ACTION_VERSION_INFO,
  useErrorOverlayReducer,
  ACTION_BUILDING_INDICATOR_HIDE,
  ACTION_BUILDING_INDICATOR_SHOW,
  ACTION_RENDERING_INDICATOR_HIDE,
  ACTION_RENDERING_INDICATOR_SHOW,
  ACTION_DEVTOOL_UPDATE_ROUTE_STATE,
  ACTION_DEVTOOLS_CONFIG,
  type OverlayState,
  type DispatcherEvent,
} from './dev-overlay/shared'

import {
  createContext,
  startTransition,
  useContext,
  useInsertionEffect,
  type ActionDispatch,
} from 'react'
import { createRoot } from 'react-dom/client'
import { FontStyles } from './dev-overlay/font/font-styles'
import type { HydrationErrorState } from './shared/hydration-error'
import type { DebugInfo } from './shared/types'
import { DevOverlay } from './dev-overlay/dev-overlay'
import type { DevIndicatorServerState } from '../server/dev/dev-indicator-server-state'
import type { VersionInfo } from '../server/dev/parse-version-info'
import {
  insertSegmentNode,
  removeSegmentNode,
} from './dev-overlay/segment-explorer-trie'
import type { SegmentNodeState } from './userspace/app/segment-explorer-node'
import type { DevToolsConfig } from './dev-overlay/shared'

export interface Dispatcher {
  onBuildOk(): void
  onBuildError(message: string): void
  onVersionInfo(versionInfo: VersionInfo): void
  onDebugInfo(debugInfo: DebugInfo): void
  onBeforeRefresh(): void
  onRefresh(): void
  onStaticIndicator(status: boolean): void
  onDevIndicator(devIndicator: DevIndicatorServerState): void
  onDevToolsConfig(config: DevToolsConfig): void
  onUnhandledError(reason: Error): void
  onUnhandledRejection(reason: Error): void
  openErrorOverlay(): void
  closeErrorOverlay(): void
  toggleErrorOverlay(): void
  buildingIndicatorHide(): void
  buildingIndicatorShow(): void
  renderingIndicatorHide(): void
  renderingIndicatorShow(): void
  segmentExplorerNodeAdd(nodeState: SegmentNodeState): void
  segmentExplorerNodeRemove(nodeState: SegmentNodeState): void
  segmentExplorerUpdateRouteState(page: string): void
}

type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1]
let maybeDispatch: Dispatch | null = null
const queue: Array<(dispatch: Dispatch) => void> = []

// Events might be dispatched before we get a `dispatch` from React (e.g. console.error during module eval).
// We need to queue them until we have a `dispatch` function available.
function createQueuable<Args extends any[]>(
  queueableFunction: (dispatch: Dispatch, ...args: Args) => void
) {
  return (...args: Args) => {
    if (maybeDispatch) {
      queueableFunction(maybeDispatch, ...args)
    } else {
      queue.push((dispatch: Dispatch) => {
        queueableFunction(dispatch, ...args)
      })
    }
  }
}

// TODO: Extract into separate functions that are imported
export const dispatcher: Dispatcher = {
  onBuildOk: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_BUILD_OK })
  }),
  onBuildError: createQueuable((dispatch: Dispatch, message: string) => {
    dispatch({ type: ACTION_BUILD_ERROR, message })
  }),
  onBeforeRefresh: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_BEFORE_REFRESH })
  }),
  onRefresh: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_REFRESH })
  }),
  onVersionInfo: createQueuable(
    (dispatch: Dispatch, versionInfo: VersionInfo) => {
      dispatch({ type: ACTION_VERSION_INFO, versionInfo })
    }
  ),
  onStaticIndicator: createQueuable((dispatch: Dispatch, status: boolean) => {
    dispatch({ type: ACTION_STATIC_INDICATOR, staticIndicator: status })
  }),
  onDebugInfo: createQueuable((dispatch: Dispatch, debugInfo: DebugInfo) => {
    dispatch({ type: ACTION_DEBUG_INFO, debugInfo })
  }),
  onDevIndicator: createQueuable(
    (dispatch: Dispatch, devIndicator: DevIndicatorServerState) => {
      dispatch({ type: ACTION_DEV_INDICATOR, devIndicator })
    }
  ),
  onDevToolsConfig: createQueuable(
    (dispatch: Dispatch, devToolsConfig: DevToolsConfig) => {
      dispatch({ type: ACTION_DEVTOOLS_CONFIG, devToolsConfig })
    }
  ),
  onUnhandledError: createQueuable((dispatch: Dispatch, error: Error) => {
    dispatch({
      type: ACTION_UNHANDLED_ERROR,
      reason: error,
    })
  }),
  onUnhandledRejection: createQueuable((dispatch: Dispatch, error: Error) => {
    dispatch({
      type: ACTION_UNHANDLED_REJECTION,
      reason: error,
    })
  }),
  openErrorOverlay: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
  }),
  closeErrorOverlay: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_ERROR_OVERLAY_CLOSE })
  }),
  toggleErrorOverlay: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_ERROR_OVERLAY_TOGGLE })
  }),
  buildingIndicatorHide: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_BUILDING_INDICATOR_HIDE })
  }),
  buildingIndicatorShow: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_BUILDING_INDICATOR_SHOW })
  }),
  renderingIndicatorHide: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_RENDERING_INDICATOR_HIDE })
  }),
  renderingIndicatorShow: createQueuable((dispatch: Dispatch) => {
    dispatch({ type: ACTION_RENDERING_INDICATOR_SHOW })
  }),
  segmentExplorerNodeAdd: createQueuable(
    (_: Dispatch, nodeState: SegmentNodeState) => {
      insertSegmentNode(nodeState)
    }
  ),
  segmentExplorerNodeRemove: createQueuable(
    (_: Dispatch, nodeState: SegmentNodeState) => {
      removeSegmentNode(nodeState)
    }
  ),
  segmentExplorerUpdateRouteState: createQueuable(
    (dispatch: Dispatch, page: string) => {
      dispatch({ type: ACTION_DEVTOOL_UPDATE_ROUTE_STATE, page })
    }
  ),
}

function replayQueuedEvents(dispatch: NonNullable<typeof maybeDispatch>) {
  try {
    for (const queuedFunction of queue) {
      queuedFunction(dispatch)
    }
  } finally {
    // TODO: What to do with failed events?
    queue.length = 0
  }
}

function DevOverlayRoot({
  getComponentStack,
  getOwnerStack,
  getSquashedHydrationErrorDetails,
  isRecoverableError,
  routerType,
}: {
  getComponentStack: (error: Error) => string | undefined
  getOwnerStack: (error: Error) => string | null | undefined
  getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
  isRecoverableError: (error: Error) => boolean
  routerType: 'app' | 'pages'
}) {
  const [state, dispatch] = useErrorOverlayReducer(
    routerType,
    getComponentStack,
    getOwnerStack,
    isRecoverableError
  )

  useInsertionEffect(() => {
    maybeDispatch = dispatch

    // Can't schedule updates from useInsertionEffect, so we need to defer.
    // Could move this into a passive Effect but we don't want replaying when
    // we reconnect.
    const replayTimeout = setTimeout(() => {
      replayQueuedEvents(dispatch)
    })

    return () => {
      maybeDispatch = null
      clearTimeout(replayTimeout)
    }
  }, [])

  return (
    <>
      {/* Fonts can only be loaded outside the Shadow DOM. */}
      <FontStyles />
      <DevOverlayContext
        value={{
          dispatch,
          getSquashedHydrationErrorDetails,
          state,
        }}
      >
        <DevOverlay />
      </DevOverlayContext>
    </>
  )
}
export const DevOverlayContext = createContext<{
  state: OverlayState & {
    routerType: 'pages' | 'app'
  }
  dispatch: ActionDispatch<[action: DispatcherEvent]>
  getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
}>(null!)
export const useDevOverlayContext = () => useContext(DevOverlayContext)

let isPagesMounted = false
let isAppMounted = false

function getSquashedHydrationErrorDetailsApp() {
  // We don't squash hydration errors in the App Router.
  return null
}

export function renderAppDevOverlay(
  getComponentStack: (error: Error) => string | undefined,
  getOwnerStack: (error: Error) => string | null | undefined,
  isRecoverableError: (error: Error) => boolean
): void {
  if (isPagesMounted) {
    // Switching between App and Pages Router is always a hard navigation
    // TODO: Support soft navigation between App and Pages Router
    throw new Error(
      'Next DevTools: Pages Dev Overlay is already mounted. This is a bug in Next.js'
    )
  }

  if (!isAppMounted) {
    // React 19 will not throw away `<script>` elements in a container it owns.
    // This ensures the actual user-space React does not unmount the Dev Overlay.
    const script = document.createElement('script')
    script.style.display = 'block'
    // Although the style applied to the shadow host is isolated,
    // the element that attached the shadow host (i.e. "script")
    // is still affected by the parent's style (e.g. "body"). This may
    // occur style conflicts like "display: flex", with other children
    // elements therefore give the shadow host an absolute position.
    script.style.position = 'absolute'
    script.setAttribute('data-nextjs-dev-overlay', 'true')

    const container = document.createElement('nextjs-portal')

    script.appendChild(container)
    document.body.appendChild(script)

    const root = createRoot(container, {
      identifierPrefix: 'ndt-',
    })

    startTransition(() => {
      // TODO: Dedicated error boundary or root error callbacks?
      // At least it won't unmount any user code if it errors.
      root.render(
        <DevOverlayRoot
          getComponentStack={getComponentStack}
          getOwnerStack={getOwnerStack}
          getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetailsApp}
          isRecoverableError={isRecoverableError}
          routerType="app"
        />
      )
    })

    isAppMounted = true
  }
}

export function renderPagesDevOverlay(
  getComponentStack: (error: Error) => string | undefined,
  getOwnerStack: (error: Error) => string | null | undefined,
  getSquashedHydrationErrorDetails: (
    error: Error
  ) => HydrationErrorState | null,
  isRecoverableError: (error: Error) => boolean
): void {
  if (isAppMounted) {
    // Switching between App and Pages Router is always a hard navigation
    // TODO: Support soft navigation between App and Pages Router
    throw new Error(
      'Next DevTools: App Dev Overlay is already mounted. This is a bug in Next.js'
    )
  }

  if (!isPagesMounted) {
    const container = document.createElement('nextjs-portal')
    // Although the style applied to the shadow host is isolated,
    // the element that attached the shadow host (i.e. "script")
    // is still affected by the parent's style (e.g. "body"). This may
    // occur style conflicts like "display: flex", with other children
    // elements therefore give the shadow host an absolute position.
    container.style.position = 'absolute'

    // Pages Router runs with React 18 or 19 so we can't use the same trick as with
    // App Router. We just reconnect the container if React wipes it e.g. when
    // we recover from a shell error via createRoot()
    new MutationObserver((records) => {
      for (const record of records) {
        if (record.type === 'childList') {
          for (const node of record.removedNodes) {
            if (node === container) {
              // Reconnect the container to the body
              document.body.appendChild(container)
            }
          }
        }
      }
    }).observe(document.body, {
      childList: true,
    })
    document.body.appendChild(container)

    const root = createRoot(container)

    startTransition(() => {
      // TODO: Dedicated error boundary or root error callbacks?
      // At least it won't unmount any user code if it errors.
      root.render(
        <DevOverlayRoot
          getComponentStack={getComponentStack}
          getOwnerStack={getOwnerStack}
          getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
          isRecoverableError={isRecoverableError}
          routerType="pages"
        />
      )
    })

    isPagesMounted = true
  }
}