Unverified Commit bf630e8e authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Refactor error overlay for new router (#41343)

Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent e0bb2580
...@@ -36,11 +36,13 @@ function urlToUrlWithoutFlightMarker(url: string): URL { ...@@ -36,11 +36,13 @@ function urlToUrlWithoutFlightMarker(url: string): URL {
return urlWithoutFlightParameters return urlWithoutFlightParameters
} }
const HotReloader: typeof import('./hot-reloader').default | null = const HotReloader:
| typeof import('./react-dev-overlay/hot-reloader').default
| null =
process.env.NODE_ENV === 'production' process.env.NODE_ENV === 'production'
? null ? null
: (require('./hot-reloader') : (require('./react-dev-overlay/hot-reloader')
.default as typeof import('./hot-reloader').default) .default as typeof import('./react-dev-overlay/hot-reloader').default)
/** /**
* Fetch the flight data for the provided url. Takes in the current router state to decide what to render server-side. * Fetch the flight data for the provided url. Takes in the current router state to decide what to render server-side.
......
import * as Bus from './internal/bus' import { Dispatch, ReducerAction } from 'react'
import type { errorOverlayReducer } from './internal/error-overlay-reducer'
import {
ACTION_BUILD_OK,
ACTION_BUILD_ERROR,
ACTION_REFRESH,
ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION,
} from './internal/error-overlay-reducer'
import { parseStack } from './internal/helpers/parseStack' import { parseStack } from './internal/helpers/parseStack'
let isRegistered = false export type DispatchFn = Dispatch<ReducerAction<typeof errorOverlayReducer>>
let stackTraceLimit: number | undefined = undefined
function onUnhandledError(ev: ErrorEvent) { export function onUnhandledError(dispatch: DispatchFn, ev: ErrorEvent) {
const error = ev?.error const error = ev?.error
if (!error || !(error instanceof Error) || typeof error.stack !== 'string') { if (!error || !(error instanceof Error) || typeof error.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-( // A non-error was thrown, we don't have anything to show. :-(
...@@ -18,14 +25,17 @@ function onUnhandledError(ev: ErrorEvent) { ...@@ -18,14 +25,17 @@ function onUnhandledError(ev: ErrorEvent) {
} }
const e = error const e = error
Bus.emit({ dispatch({
type: Bus.TYPE_UNHANDLED_ERROR, type: ACTION_UNHANDLED_ERROR,
reason: error, reason: error,
frames: parseStack(e.stack!), frames: parseStack(e.stack!),
}) })
} }
function onUnhandledRejection(ev: PromiseRejectionEvent) { export function onUnhandledRejection(
dispatch: DispatchFn,
ev: PromiseRejectionEvent
) {
const reason = ev?.reason const reason = ev?.reason
if ( if (
!reason || !reason ||
...@@ -37,59 +47,25 @@ function onUnhandledRejection(ev: PromiseRejectionEvent) { ...@@ -37,59 +47,25 @@ function onUnhandledRejection(ev: PromiseRejectionEvent) {
} }
const e = reason const e = reason
Bus.emit({ dispatch({
type: Bus.TYPE_UNHANDLED_REJECTION, type: ACTION_UNHANDLED_REJECTION,
reason: reason, reason: reason,
frames: parseStack(e.stack!), frames: parseStack(e.stack!),
}) })
} }
function register() { export function onBuildOk(dispatch: DispatchFn) {
if (isRegistered) { dispatch({ type: ACTION_BUILD_OK })
return
}
isRegistered = true
try {
const limit = Error.stackTraceLimit
Error.stackTraceLimit = 50
stackTraceLimit = limit
} catch {}
window.addEventListener('error', onUnhandledError)
window.addEventListener('unhandledrejection', onUnhandledRejection)
}
function unregister() {
if (!isRegistered) {
return
}
isRegistered = false
if (stackTraceLimit !== undefined) {
try {
Error.stackTraceLimit = stackTraceLimit
} catch {}
stackTraceLimit = undefined
}
window.removeEventListener('error', onUnhandledError)
window.removeEventListener('unhandledrejection', onUnhandledRejection)
}
function onBuildOk() {
Bus.emit({ type: Bus.TYPE_BUILD_OK })
} }
function onBuildError(message: string) { export function onBuildError(dispatch: DispatchFn, message: string) {
Bus.emit({ type: Bus.TYPE_BUILD_ERROR, message }) dispatch({ type: ACTION_BUILD_ERROR, message })
} }
function onRefresh() { export function onRefresh(dispatch: DispatchFn) {
Bus.emit({ type: Bus.TYPE_REFRESH }) dispatch({ type: ACTION_REFRESH })
} }
export { getErrorByType } from './internal/helpers/getErrorByType' export { getErrorByType } from './internal/helpers/getErrorByType'
export { getServerError } from './internal/helpers/nodeStackFrames' export { getServerError } from './internal/helpers/nodeStackFrames'
export { default as ReactDevOverlay } from './internal/ReactDevOverlay' export { default as ReactDevOverlay } from './internal/ReactDevOverlay'
export { onBuildOk, onBuildError, register, unregister, onRefresh }
...@@ -7,18 +7,20 @@ import React, { ...@@ -7,18 +7,20 @@ import React, {
// @ts-expect-error TODO-APP: startTransition exists // @ts-expect-error TODO-APP: startTransition exists
startTransition, startTransition,
} from 'react' } from 'react'
import { GlobalLayoutRouterContext } from '../../shared/lib/app-router-context' import { GlobalLayoutRouterContext } from '../../../shared/lib/app-router-context'
import { import {
register,
unregister,
onBuildError, onBuildError,
onBuildOk, onBuildOk,
onRefresh, onRefresh,
onUnhandledError,
onUnhandledRejection,
ReactDevOverlay, ReactDevOverlay,
} from './react-dev-overlay/src/client' } from './client'
import type { DispatchFn } from './client'
import stripAnsi from 'next/dist/compiled/strip-ansi' import stripAnsi from 'next/dist/compiled/strip-ansi'
import formatWebpackMessages from '../dev/error-overlay/format-webpack-messages' import formatWebpackMessages from '../../dev/error-overlay/format-webpack-messages'
import { useRouter } from './hooks-client' import { useRouter } from '../hooks-client'
import { errorOverlayReducer } from './internal/error-overlay-reducer'
function getSocketProtocol(assetPrefix: string): string { function getSocketProtocol(assetPrefix: string): string {
let protocol = window.location.protocol let protocol = window.location.protocol
...@@ -42,10 +44,10 @@ let hadRuntimeError = false ...@@ -42,10 +44,10 @@ let hadRuntimeError = false
// let startLatency = undefined // let startLatency = undefined
function onFastRefresh(hasUpdates: boolean) { function onFastRefresh(dispatch: DispatchFn, hasUpdates: boolean) {
onBuildOk() onBuildOk(dispatch)
if (hasUpdates) { if (hasUpdates) {
onRefresh() onRefresh(dispatch)
} }
// if (startLatency) { // if (startLatency) {
...@@ -120,7 +122,11 @@ function performFullReload(err: any, sendMessage: any) { ...@@ -120,7 +122,11 @@ function performFullReload(err: any, sendMessage: any) {
} }
// Attempt to update code on the fly, fall back to a hard reload. // Attempt to update code on the fly, fall back to a hard reload.
function tryApplyUpdates(onHotUpdateSuccess: any, sendMessage: any) { function tryApplyUpdates(
onHotUpdateSuccess: any,
sendMessage: any,
dispatch: DispatchFn
) {
// @ts-expect-error module.hot exists // @ts-expect-error module.hot exists
if (!module.hot) { if (!module.hot) {
// HotModuleReplacementPlugin is not in Webpack configuration. // HotModuleReplacementPlugin is not in Webpack configuration.
...@@ -130,7 +136,7 @@ function tryApplyUpdates(onHotUpdateSuccess: any, sendMessage: any) { ...@@ -130,7 +136,7 @@ function tryApplyUpdates(onHotUpdateSuccess: any, sendMessage: any) {
} }
if (!isUpdateAvailable() || !canApplyUpdates()) { if (!isUpdateAvailable() || !canApplyUpdates()) {
onBuildOk() onBuildOk(dispatch)
return return
} }
...@@ -162,9 +168,13 @@ function tryApplyUpdates(onHotUpdateSuccess: any, sendMessage: any) { ...@@ -162,9 +168,13 @@ function tryApplyUpdates(onHotUpdateSuccess: any, sendMessage: any) {
if (isUpdateAvailable()) { if (isUpdateAvailable()) {
// While we were updating, there was a new update! Do it again. // While we were updating, there was a new update! Do it again.
tryApplyUpdates(hasUpdates ? onBuildOk : onHotUpdateSuccess, sendMessage) tryApplyUpdates(
hasUpdates ? onBuildOk : onHotUpdateSuccess,
sendMessage,
dispatch
)
} else { } else {
onBuildOk() onBuildOk(dispatch)
// if (process.env.__NEXT_TEST_MODE) { // if (process.env.__NEXT_TEST_MODE) {
// afterApplyUpdates(() => { // afterApplyUpdates(() => {
// if (self.__NEXT_HMR_CB) { // if (self.__NEXT_HMR_CB) {
...@@ -191,7 +201,8 @@ function tryApplyUpdates(onHotUpdateSuccess: any, sendMessage: any) { ...@@ -191,7 +201,8 @@ function tryApplyUpdates(onHotUpdateSuccess: any, sendMessage: any) {
function processMessage( function processMessage(
e: any, e: any,
sendMessage: any, sendMessage: any,
router: ReturnType<typeof useRouter> router: ReturnType<typeof useRouter>,
dispatch: DispatchFn
) { ) {
const obj = JSON.parse(e.data) const obj = JSON.parse(e.data)
...@@ -226,7 +237,7 @@ function processMessage( ...@@ -226,7 +237,7 @@ function processMessage(
}) })
// Only show the first error. // Only show the first error.
onBuildError(formatted.errors[0]) onBuildError(dispatch, formatted.errors[0])
// Also log them to the console. // Also log them to the console.
for (let i = 0; i < formatted.errors.length; i++) { for (let i = 0; i < formatted.errors.length; i++) {
...@@ -276,11 +287,15 @@ function processMessage( ...@@ -276,11 +287,15 @@ function processMessage(
// Attempt to apply hot updates or reload. // Attempt to apply hot updates or reload.
if (isHotUpdate) { if (isHotUpdate) {
tryApplyUpdates(function onSuccessfulHotUpdate(hasUpdates: any) { tryApplyUpdates(
// Only dismiss it when we're sure it's a hot update. function onSuccessfulHotUpdate(hasUpdates: any) {
// Otherwise it would flicker right before the reload. // Only dismiss it when we're sure it's a hot update.
onFastRefresh(hasUpdates) // Otherwise it would flicker right before the reload.
}, sendMessage) onFastRefresh(dispatch, hasUpdates)
},
sendMessage,
dispatch
)
} }
return return
} }
...@@ -299,11 +314,15 @@ function processMessage( ...@@ -299,11 +314,15 @@ function processMessage(
// Attempt to apply hot updates or reload. // Attempt to apply hot updates or reload.
if (isHotUpdate) { if (isHotUpdate) {
tryApplyUpdates(function onSuccessfulHotUpdate(hasUpdates: any) { tryApplyUpdates(
// Only dismiss it when we're sure it's a hot update. function onSuccessfulHotUpdate(hasUpdates: any) {
// Otherwise it would flicker right before the reload. // Only dismiss it when we're sure it's a hot update.
onFastRefresh(hasUpdates) // Otherwise it would flicker right before the reload.
}, sendMessage) onFastRefresh(dispatch, hasUpdates)
},
sendMessage,
dispatch
)
} }
return return
} }
...@@ -320,7 +339,7 @@ function processMessage( ...@@ -320,7 +339,7 @@ function processMessage(
} }
startTransition(() => { startTransition(() => {
router.reload() router.reload()
onRefresh() onRefresh(dispatch)
}) })
return return
...@@ -405,6 +424,22 @@ export default function HotReload({ ...@@ -405,6 +424,22 @@ export default function HotReload({
assetPrefix: string assetPrefix: string
children?: ReactNode children?: ReactNode
}) { }) {
const stacktraceLimitRef = useRef<undefined | number>()
const [state, dispatch] = React.useReducer(errorOverlayReducer, {
nextId: 1,
buildError: null,
errors: [],
})
const handleOnUnhandledError = useCallback((ev) => {
hadRuntimeError = true
onUnhandledError(dispatch, ev)
}, [])
const handleOnUnhandledRejection = useCallback((ev) => {
hadRuntimeError = true
onUnhandledRejection(dispatch, ev)
}, [])
const { tree } = useContext(GlobalLayoutRouterContext) const { tree } = useContext(GlobalLayoutRouterContext)
const router = useRouter() const router = useRouter()
...@@ -416,18 +451,29 @@ export default function HotReload({ ...@@ -416,18 +451,29 @@ export default function HotReload({
}, []) }, [])
useEffect(() => { useEffect(() => {
register() try {
const onError = () => { const limit = Error.stackTraceLimit
hadRuntimeError = true Error.stackTraceLimit = 50
} stacktraceLimitRef.current = limit
window.addEventListener('error', onError) } catch {}
window.addEventListener('unhandledrejection', onError)
window.addEventListener('error', handleOnUnhandledError)
window.addEventListener('unhandledrejection', handleOnUnhandledRejection)
return () => { return () => {
unregister() if (stacktraceLimitRef.current !== undefined) {
window.removeEventListener('error', onError) try {
window.removeEventListener('unhandledrejection', onError) Error.stackTraceLimit = stacktraceLimitRef.current
} catch {}
stacktraceLimitRef.current = undefined
}
window.removeEventListener('error', handleOnUnhandledError)
window.removeEventListener(
'unhandledrejection',
handleOnUnhandledRejection
)
} }
}, []) }, [handleOnUnhandledError, handleOnUnhandledRejection])
useEffect(() => { useEffect(() => {
if (webSocketRef.current) { if (webSocketRef.current) {
...@@ -474,7 +520,7 @@ export default function HotReload({ ...@@ -474,7 +520,7 @@ export default function HotReload({
} }
try { try {
processMessage(event, sendMessage, router) processMessage(event, sendMessage, router, dispatch)
} catch (ex) { } catch (ex) {
console.warn('Invalid HMR message: ' + event.data + '\n', ex) console.warn('Invalid HMR message: ' + event.data + '\n', ex)
} }
...@@ -501,5 +547,5 @@ export default function HotReload({ ...@@ -501,5 +547,5 @@ export default function HotReload({
// return () => clearInterval(interval) // return () => clearInterval(interval)
// }) // })
return <ReactDevOverlay globalOverlay>{children}</ReactDevOverlay> return <ReactDevOverlay state={state}>{children}</ReactDevOverlay>
} }
import React from 'react' import React from 'react'
type ErrorBoundaryProps = { type ErrorBoundaryProps = {
onError: (error: Error, componentStack: string | null) => void
globalOverlay?: boolean
isMounted?: boolean isMounted?: boolean
} }
type ErrorBoundaryState = { error: Error | null } type ErrorBoundaryState = { error: Error | null }
...@@ -17,30 +15,15 @@ class ErrorBoundary extends React.PureComponent< ...@@ -17,30 +15,15 @@ class ErrorBoundary extends React.PureComponent<
return { error } return { error }
} }
componentDidCatch(
error: Error,
// Loosely typed because it depends on the React version and was
// accidentally excluded in some versions.
errorInfo?: { componentStack?: string | null }
) {
this.props.onError(error, errorInfo?.componentStack || null)
if (!this.props.globalOverlay) {
this.setState({ error })
}
}
render() { render() {
// The component has to be unmounted or else it would continue to error // The component has to be unmounted or else it would continue to error
return this.state.error || return this.state.error || this.props.isMounted ? (
(this.props.globalOverlay && this.props.isMounted) ? (
// When the overlay is global for the application and it wraps a component rendering `<html>` // When the overlay is global for the application and it wraps a component rendering `<html>`
// we have to render the html shell otherwise the shadow root will not be able to attach // we have to render the html shell otherwise the shadow root will not be able to attach
this.props.globalOverlay ? ( <html>
<html> <head></head>
<head></head> <body></body>
<body></body> </html>
</html>
) : null
) : ( ) : (
this.props.children this.props.children
) )
......
import * as React from 'react'
import type { OverlayState } from './error-overlay-reducer'
import { ShadowPortal } from './components/ShadowPortal'
import { BuildError } from './container/BuildError'
import { Errors } from './container/Errors'
import { ErrorBoundary } from './ErrorBoundary'
import { Base } from './styles/Base'
import { ComponentStyles } from './styles/ComponentStyles'
import { CssReset } from './styles/CssReset'
type ErrorType = 'runtime' | 'build'
const shouldPreventDisplay = (
errorType?: ErrorType | null,
preventType?: ErrorType[] | null
) => {
if (!preventType || !errorType) {
return false
}
return preventType.includes(errorType)
}
function ReactDevOverlay({
state,
children,
preventDisplay,
}: {
state: OverlayState
children?: React.ReactNode
preventDisplay?: ErrorType[]
}) {
const hasBuildError = state.buildError != null
const hasRuntimeErrors = Boolean(state.errors.length)
const isMounted = hasBuildError || hasRuntimeErrors
return (
<>
<ErrorBoundary isMounted={isMounted}>{children}</ErrorBoundary>
{isMounted ? (
<ShadowPortal>
<CssReset />
<Base />
<ComponentStyles />
{shouldPreventDisplay(
hasBuildError ? 'build' : hasRuntimeErrors ? 'runtime' : null,
preventDisplay
) ? null : hasBuildError ? (
<BuildError message={state.buildError!} />
) : hasRuntimeErrors ? (
<Errors errors={state.errors} />
) : undefined}
</ShadowPortal>
) : undefined}
</>
)
}
export default ReactDevOverlay
import * as React from 'react' import * as React from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
export type ShadowPortalProps = { export function ShadowPortal({ children }: { children: React.ReactNode }) {
children: React.ReactNode
globalOverlay?: boolean
}
export const ShadowPortal: React.FC<ShadowPortalProps> = function Portal({
children,
globalOverlay,
}) {
let mountNode = React.useRef<HTMLDivElement | null>(null)
let portalNode = React.useRef<HTMLElement | null>(null) let portalNode = React.useRef<HTMLElement | null>(null)
let shadowNode = React.useRef<ShadowRoot | null>(null) let shadowNode = React.useRef<ShadowRoot | null>(null)
let [, forceUpdate] = React.useState<{} | undefined>() let [, forceUpdate] = React.useState<{} | undefined>()
React.useLayoutEffect(() => { React.useLayoutEffect(() => {
const ownerDocument = globalOverlay const ownerDocument = document
? document
: mountNode.current!.ownerDocument!
portalNode.current = ownerDocument.createElement('nextjs-portal') portalNode.current = ownerDocument.createElement('nextjs-portal')
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' }) shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
ownerDocument.body.appendChild(portalNode.current) ownerDocument.body.appendChild(portalNode.current)
...@@ -28,11 +17,9 @@ export const ShadowPortal: React.FC<ShadowPortalProps> = function Portal({ ...@@ -28,11 +17,9 @@ export const ShadowPortal: React.FC<ShadowPortalProps> = function Portal({
portalNode.current.ownerDocument.body.removeChild(portalNode.current) portalNode.current.ownerDocument.body.removeChild(portalNode.current)
} }
} }
}, [globalOverlay]) }, [])
return shadowNode.current ? ( return shadowNode.current
createPortal(children, shadowNode.current as any) ? createPortal(children, shadowNode.current as any)
) : globalOverlay ? null : ( : null
<span ref={mountNode} />
)
} }
import * as React from 'react' import * as React from 'react'
import { import {
TYPE_UNHANDLED_ERROR, ACTION_UNHANDLED_ERROR,
TYPE_UNHANDLED_REJECTION, ACTION_UNHANDLED_REJECTION,
UnhandledError, UnhandledErrorAction,
UnhandledRejection, UnhandledRejectionAction,
} from '../bus' } from '../error-overlay-reducer'
import { import {
Dialog, Dialog,
DialogBody, DialogBody,
...@@ -22,7 +22,7 @@ import { RuntimeError } from './RuntimeError' ...@@ -22,7 +22,7 @@ import { RuntimeError } from './RuntimeError'
export type SupportedErrorEvent = { export type SupportedErrorEvent = {
id: number id: number
event: UnhandledError | UnhandledRejection event: UnhandledErrorAction | UnhandledRejectionAction
} }
export type ErrorsProps = { errors: SupportedErrorEvent[] } export type ErrorsProps = { errors: SupportedErrorEvent[] }
...@@ -31,8 +31,8 @@ type ReadyErrorEvent = ReadyRuntimeError ...@@ -31,8 +31,8 @@ type ReadyErrorEvent = ReadyRuntimeError
function getErrorSignature(ev: SupportedErrorEvent): string { function getErrorSignature(ev: SupportedErrorEvent): string {
const { event } = ev const { event } = ev
switch (event.type) { switch (event.type) {
case TYPE_UNHANDLED_ERROR: case ACTION_UNHANDLED_ERROR:
case TYPE_UNHANDLED_REJECTION: { case ACTION_UNHANDLED_REJECTION: {
return `${event.reason.name}::${event.reason.message}::${event.reason.stack}` return `${event.reason.name}::${event.reason.message}::${event.reason.stack}`
} }
default: { default: {
......
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser'
import { SupportedErrorEvent } from './container/Errors'
export const ACTION_BUILD_OK = 'build-ok'
export const ACTION_BUILD_ERROR = 'build-error'
export const ACTION_REFRESH = 'fast-refresh'
export const ACTION_UNHANDLED_ERROR = 'unhandled-error'
export const ACTION_UNHANDLED_REJECTION = 'unhandled-rejection'
interface BuildOkAction {
type: typeof ACTION_BUILD_OK
}
interface BuildErrorAction {
type: typeof ACTION_BUILD_ERROR
message: string
}
interface FastRefreshAction {
type: typeof ACTION_REFRESH
}
export interface UnhandledErrorAction {
type: typeof ACTION_UNHANDLED_ERROR
reason: Error
frames: StackFrame[]
}
export interface UnhandledRejectionAction {
type: typeof ACTION_UNHANDLED_REJECTION
reason: Error
frames: StackFrame[]
}
export interface OverlayState {
nextId: number
buildError: string | null
errors: SupportedErrorEvent[]
}
export function errorOverlayReducer(
state: Readonly<OverlayState>,
action: Readonly<
| BuildOkAction
| BuildErrorAction
| FastRefreshAction
| UnhandledErrorAction
| UnhandledRejectionAction
>
): OverlayState {
switch (action.type) {
case ACTION_BUILD_OK: {
return { ...state, buildError: null }
}
case ACTION_BUILD_ERROR: {
return { ...state, buildError: action.message }
}
case ACTION_REFRESH: {
return { ...state, buildError: null, errors: [] }
}
case ACTION_UNHANDLED_ERROR:
case ACTION_UNHANDLED_REJECTION: {
return {
...state,
nextId: state.nextId + 1,
errors: [
...state.errors.filter((err) => {
// Filter out duplicate errors
return err.event.reason !== action.reason
}),
{ id: state.nextId, event: action },
],
}
}
default: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = action
return state
}
}
}
import { TYPE_UNHANDLED_ERROR, TYPE_UNHANDLED_REJECTION } from '../bus' import {
ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION,
} from '../error-overlay-reducer'
import { SupportedErrorEvent } from '../container/Errors' import { SupportedErrorEvent } from '../container/Errors'
import { getErrorSource } from './nodeStackFrames' import { getErrorSource } from './nodeStackFrames'
import { getOriginalStackFrames, OriginalStackFrame } from './stack-frame' import { getOriginalStackFrames, OriginalStackFrame } from './stack-frame'
...@@ -15,8 +18,8 @@ export async function getErrorByType( ...@@ -15,8 +18,8 @@ export async function getErrorByType(
): Promise<ReadyRuntimeError> { ): Promise<ReadyRuntimeError> {
const { id, event } = ev const { id, event } = ev
switch (event.type) { switch (event.type) {
case TYPE_UNHANDLED_ERROR: case ACTION_UNHANDLED_ERROR:
case TYPE_UNHANDLED_REJECTION: { case ACTION_UNHANDLED_REJECTION: {
return { return {
id, id,
runtime: true, runtime: true,
......
import * as React from 'react'
import * as Bus from './bus'
import { ShadowPortal } from './components/ShadowPortal'
import { BuildError } from './container/BuildError'
import { Errors, SupportedErrorEvent } from './container/Errors'
import { ErrorBoundary } from './ErrorBoundary'
import { Base } from './styles/Base'
import { ComponentStyles } from './styles/ComponentStyles'
import { CssReset } from './styles/CssReset'
type OverlayState = {
nextId: number
buildError: string | null
errors: SupportedErrorEvent[]
}
function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
switch (ev.type) {
case Bus.TYPE_BUILD_OK: {
return { ...state, buildError: null }
}
case Bus.TYPE_BUILD_ERROR: {
return { ...state, buildError: ev.message }
}
case Bus.TYPE_REFRESH: {
return { ...state, buildError: null, errors: [] }
}
case Bus.TYPE_UNHANDLED_ERROR:
case Bus.TYPE_UNHANDLED_REJECTION: {
return {
...state,
nextId: state.nextId + 1,
errors: [
...state.errors.filter((err) => {
// Filter out duplicate errors
return err.event.reason !== ev.reason
}),
{ id: state.nextId, event: ev },
],
}
}
default: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = ev
return state
}
}
}
type ErrorType = 'runtime' | 'build'
const shouldPreventDisplay = (
errorType?: ErrorType | null,
preventType?: ErrorType[] | null
) => {
if (!preventType || !errorType) {
return false
}
return preventType.includes(errorType)
}
type ReactDevOverlayProps = {
children?: React.ReactNode
preventDisplay?: ErrorType[]
globalOverlay?: boolean
}
const ReactDevOverlay: React.FunctionComponent<ReactDevOverlayProps> =
function ReactDevOverlay({ children, preventDisplay, globalOverlay }) {
const [state, dispatch] = React.useReducer<
React.Reducer<OverlayState, Bus.BusEvent>
>(reducer, {
nextId: 1,
buildError: null,
errors: [],
})
React.useEffect(() => {
Bus.on(dispatch)
return function () {
Bus.off(dispatch)
}
}, [dispatch])
const onComponentError = React.useCallback(
(_error: Error, _componentStack: string | null) => {
// TODO: special handling
},
[]
)
const hasBuildError = state.buildError != null
const hasRuntimeErrors = Boolean(state.errors.length)
const isMounted = hasBuildError || hasRuntimeErrors
return (
<React.Fragment>
<ErrorBoundary
globalOverlay={globalOverlay}
isMounted={isMounted}
onError={onComponentError}
>
{children ?? null}
</ErrorBoundary>
{isMounted ? (
<ShadowPortal globalOverlay={globalOverlay}>
<CssReset />
<Base />
<ComponentStyles />
{shouldPreventDisplay(
hasBuildError ? 'build' : hasRuntimeErrors ? 'runtime' : null,
preventDisplay
) ? null : hasBuildError ? (
<BuildError message={state.buildError!} />
) : hasRuntimeErrors ? (
<Errors errors={state.errors} />
) : undefined}
</ShadowPortal>
) : undefined}
</React.Fragment>
)
}
export default ReactDevOverlay
import type { StackFrame } from 'next/dist/compiled/stacktrace-parser'
export const TYPE_BUILD_OK = 'build-ok'
export const TYPE_BUILD_ERROR = 'build-error'
export const TYPE_REFRESH = 'fast-refresh'
export const TYPE_UNHANDLED_ERROR = 'unhandled-error'
export const TYPE_UNHANDLED_REJECTION = 'unhandled-rejection'
export type BuildOk = { type: typeof TYPE_BUILD_OK }
export type BuildError = {
type: typeof TYPE_BUILD_ERROR
message: string
}
export type FastRefresh = { type: typeof TYPE_REFRESH }
export type UnhandledError = {
type: typeof TYPE_UNHANDLED_ERROR
reason: Error
frames: StackFrame[]
}
export type UnhandledRejection = {
type: typeof TYPE_UNHANDLED_REJECTION
reason: Error
frames: StackFrame[]
}
export type BusEvent =
| BuildOk
| BuildError
| FastRefresh
| UnhandledError
| UnhandledRejection
export type BusEventHandler = (ev: BusEvent) => void
let handlers: Set<BusEventHandler> = new Set()
let queue: BusEvent[] = []
function drain() {
// Draining should never happen synchronously in case multiple handlers are
// registered.
setTimeout(function () {
while (
// Until we are out of events:
Boolean(queue.length) &&
// Or, if all handlers removed themselves as a result of handling the
// event(s)
Boolean(handlers.size)
) {
const ev = queue.shift()!
handlers.forEach((handler) => handler(ev))
}
}, 1)
}
export function emit(ev: BusEvent): void {
queue.push(Object.freeze({ ...ev }))
drain()
}
export function on(fn: BusEventHandler): boolean {
if (handlers.has(fn)) {
return false
}
handlers.add(fn)
drain()
return true
}
export function off(fn: BusEventHandler): boolean {
if (handlers.has(fn)) {
handlers.delete(fn)
return true
}
return false
}
...@@ -92,8 +92,12 @@ const ReactDevOverlay: React.FunctionComponent<ReactDevOverlayProps> = ...@@ -92,8 +92,12 @@ const ReactDevOverlay: React.FunctionComponent<ReactDevOverlayProps> =
const hasBuildError = state.buildError != null const hasBuildError = state.buildError != null
const hasRuntimeErrors = Boolean(state.errors.length) const hasRuntimeErrors = Boolean(state.errors.length)
const errorType = hasBuildError
const isMounted = hasBuildError || hasRuntimeErrors ? 'build'
: hasRuntimeErrors
? 'runtime'
: null
const isMounted = errorType !== null
return ( return (
<React.Fragment> <React.Fragment>
...@@ -111,7 +115,7 @@ const ReactDevOverlay: React.FunctionComponent<ReactDevOverlayProps> = ...@@ -111,7 +115,7 @@ const ReactDevOverlay: React.FunctionComponent<ReactDevOverlayProps> =
<ComponentStyles /> <ComponentStyles />
{shouldPreventDisplay( {shouldPreventDisplay(
hasBuildError ? 'build' : hasRuntimeErrors ? 'runtime' : null, errorType,
preventDisplay preventDisplay
) ? null : hasBuildError ? ( ) ? null : hasBuildError ? (
<BuildError message={state.buildError!} /> <BuildError message={state.buildError!} />
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment