Unverified Commit 85c718fd authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[dev-overlay] Render /app Dev Overlay with a separate React instance (#79699)

parent 9155c8ac
......@@ -168,6 +168,7 @@
"files": ["packages/**"],
"excludedFiles": [
"packages/next/taskfile*.js",
"packages/next/next-devtools.webpack-config.js",
"packages/next/next-runtime.webpack-config.js"
],
"rules": {
......
......@@ -693,5 +693,7 @@
"692": "Expected clientReferenceManifest to be defined.",
"693": "%s must not be used within a client component. Next.js should be preventing %s from being included in client components statically, but did not in this case.",
"694": "createPrerenderPathname was called inside a client component scope.",
"695": "Expected workUnitAsyncStorage to have a store."
"695": "Expected workUnitAsyncStorage to have a store.",
"696": "Next DevTools: Can't dispatch %s in this environment. This is a bug in Next.js",
"697": "Next DevTools: Can't render in this environment. This is a bug in Next.js"
}
const path = require('path')
const webpack = require('@rspack/core')
const MODERN_BROWSERSLIST_TARGET = require('./src/shared/lib/modern-browserslist-target')
const DevToolsIgnoreListPlugin = require('./webpack-plugins/devtools-ignore-list-plugin')
function shouldIgnorePath(modulePath) {
// For consumers, everything will be considered 3rd party dependency if they use
// the bundles we produce here.
// In other words, this is all library code and should therefore be ignored.
return true
}
/**
* @param {Object} options
* @param {boolean} options.dev
* @param {Partial<webpack.Configuration>} options.rest
* @returns {webpack.Configuration}
*/
module.exports = ({ dev, ...rest }) => {
const experimental = false
const turbo = false
const bundledReactChannel = experimental ? '-experimental' : ''
const target = `browserslist:${MODERN_BROWSERSLIST_TARGET.join(', ')}`
return {
entry: path.join(
__dirname,
'src/client/components/react-dev-overlay/app/entrypoint.js'
),
target,
mode: dev ? 'development' : 'production',
output: {
path: path.join(__dirname, 'dist/compiled/next-devtools'),
filename: `index.js`,
iife: false,
library: {
type: 'commonjs-static',
},
},
devtool: 'source-map',
optimization: {
moduleIds: 'named',
minimize: true,
concatenateModules: true,
minimizer: [
new webpack.SwcJsMinimizerRspackPlugin({
minimizerOptions: {
mangle: dev || process.env.NEXT_SERVER_NO_MANGLE ? false : true,
},
}),
],
},
plugins: [
// TODO: React Compiler
new DevToolsIgnoreListPlugin({ shouldIgnorePath }),
new webpack.DefinePlugin({
// TODO: Hardcode it and ensure module resolution resolves to .node entrypoint in Node.js
// 'typeof window': JSON.stringify('object'),
'process.env.NEXT_MINIMAL': JSON.stringify('true'),
'this.serverOptions.experimentalTestProxy': JSON.stringify(false),
'this.minimalMode': JSON.stringify(true),
'this.renderOpts.dev': JSON.stringify(dev),
'renderOpts.dev': JSON.stringify(dev),
'process.env.NODE_ENV': JSON.stringify(
dev ? 'development' : 'production'
),
'process.env.__NEXT_EXPERIMENTAL_REACT': JSON.stringify(
experimental ? true : false
),
'process.env.NEXT_RUNTIME': JSON.stringify('nodejs'),
'process.turbopack': JSON.stringify(turbo),
'process.env.TURBOPACK': JSON.stringify(turbo),
}),
].filter(Boolean),
stats: {
optimizationBailout: true,
},
resolve: {
alias: {
// TODO: Get dedicated React version for NDT to uncouple development.
react: `next/dist/compiled/react${bundledReactChannel}`,
'react-dom$': `next/dist/compiled/react-dom${bundledReactChannel}`,
'react-dom/client$': `next/dist/compiled/react-dom${bundledReactChannel}/client`,
'react-is$': `next/dist/compiled/react-is${bundledReactChannel}`,
scheduler$: `next/dist/compiled/scheduler${bundledReactChannel}`,
},
extensions: ['.ts', '.tsx', '.js', '.json'],
},
module: {
rules: [
{ test: /\.m?js$/, loader: `source-map-loader`, enforce: `pre` },
{
test: /\.(ts|tsx)$/,
exclude: [/node_modules/],
loader: 'builtin:swc-loader',
options: {
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
transform: {
react: {
development: dev,
runtime: 'automatic',
// TODO: Fast Refresh
// refresh: dev,
},
},
},
},
type: 'javascript/auto',
},
],
},
externals: [],
experiments: {},
...rest,
}
}
......@@ -92,6 +92,8 @@ const sharedExternals = [
const externalsMap = {
'./web/sandbox': 'next/dist/server/web/sandbox',
'next/dist/compiled/next-devtools':
'commonjs next/dist/client/components/react-dev-overlay/app/app-dev-overlay.shim.js',
}
const externalsRegexMap = {
......
......@@ -2,12 +2,22 @@
import './app-webpack'
import { renderAppDevOverlay } from 'next/dist/compiled/next-devtools'
import { appBootstrap } from './app-bootstrap'
import {
getComponentStack,
getOwnerStack,
} from './components/errors/stitched-error'
import { isRecoverableError } from './react-client-callbacks/on-recoverable-error'
// eslint-disable-next-line @next/internal/typechecked-require
const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap(() => {
const { hydrate } = require('./app-index') as typeof import('./app-index')
hydrate(instrumentationHooks)
try {
hydrate(instrumentationHooks)
} finally {
renderAppDevOverlay(getComponentStack, getOwnerStack, isRecoverableError)
}
})
// TODO-APP: hydration warning
import { appBootstrap } from './app-bootstrap'
import {
getComponentStack,
getOwnerStack,
} from './components/errors/stitched-error'
import { isRecoverableError } from './react-client-callbacks/on-recoverable-error'
window.next.version += '-turbo'
;(self as any).__webpack_hash__ = ''
......@@ -10,5 +13,13 @@ const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap(() => {
const { hydrate } = require('./app-index') as typeof import('./app-index')
hydrate(instrumentationHooks)
try {
hydrate(instrumentationHooks)
} finally {
if (process.env.NODE_ENV !== 'production') {
const { renderAppDevOverlay } =
require('next/dist/compiled/next-devtools') as typeof import('next/dist/compiled/next-devtools')
renderAppDevOverlay(getComponentStack, getOwnerStack, isRecoverableError)
}
}
})
import { PureComponent } from 'react'
import { dispatcher } from 'next/dist/compiled/next-devtools'
import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
import { ErrorBoundary } from '../../error-boundary'
import DefaultGlobalError, {
......@@ -8,7 +9,6 @@ import DefaultGlobalError, {
type AppDevOverlayErrorBoundaryProps = {
children: React.ReactNode
globalError: [GlobalErrorComponent, React.ReactNode]
onError: () => void
}
type AppDevOverlayErrorBoundaryState = {
......@@ -53,7 +53,7 @@ export class AppDevOverlayErrorBoundary extends PureComponent<
}
componentDidCatch() {
this.props.onError()
dispatcher.openErrorOverlay()
}
render() {
......
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,
} from '../shared'
import { startTransition, useInsertionEffect } from 'react'
import { createRoot } from 'react-dom/client'
import { FontStyles } from '../font/font-styles'
import type { DebugInfo } from '../types'
import { DevOverlay } from '../ui/dev-overlay'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
import type { VersionInfo } from '../../../../server/dev/parse-version-info'
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
onUnhandledError(reason: Error): void
onUnhandledRejection(reason: Error): void
openErrorOverlay(): void
closeErrorOverlay(): void
toggleErrorOverlay(): void
buildingIndicatorHide(): void
buildingIndicatorShow(): void
renderingIndicatorHide(): void
renderingIndicatorShow(): 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 })
}
),
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 })
}),
}
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 getSquashedHydrationErrorDetails() {
// We don't squash hydration errors in the App Router.
return null
}
function AppDevOverlay({
getComponentStack,
getOwnerStack,
isRecoverableError,
}: {
getComponentStack: (error: Error) => string | undefined
getOwnerStack: (error: Error) => string | null | undefined
isRecoverableError: (error: Error) => boolean
}) {
const [state, dispatch] = useErrorOverlayReducer(
'app',
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 />
<DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
/>
</>
)
}
let isMounted = false
export function renderAppDevOverlay(
getComponentStack: (error: Error) => string | undefined,
getOwnerStack: (error: Error) => string | null | undefined,
isRecoverableError: (error: Error) => boolean
): void {
if (!isMounted) {
// 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(
<AppDevOverlay
getComponentStack={getComponentStack}
getOwnerStack={getOwnerStack}
isRecoverableError={isRecoverableError}
/>
)
})
isMounted = true
}
}
export function renderAppDevOverlay() {
throw new Error(
"Next DevTools: Can't render in this environment. This is a bug in Next.js"
)
}
// TODO: Extract into separate functions that are imported
export const dispatcher = new Proxy(
{},
{
get: (_, prop) => {
return () => {
throw new Error(
`Next DevTools: Can't dispatch ${String(prop)} in this environment. This is a bug in Next.js`
)
}
},
}
)
import {
ACTION_ERROR_OVERLAY_OPEN,
type OverlayDispatch,
type OverlayState,
} from '../shared'
import type { GlobalErrorComponent } from '../../global-error'
import { useCallback } from 'react'
import { AppDevOverlayErrorBoundary } from './app-dev-overlay-error-boundary'
import { FontStyles } from '../font/font-styles'
import { DevOverlay } from '../ui/dev-overlay'
function getSquashedHydrationErrorDetails() {
// We don't squash hydration errors in the App Router.
return null
}
export function AppDevOverlay({
state,
dispatch,
globalError,
children,
}: {
state: OverlayState
dispatch: OverlayDispatch
globalError: [GlobalErrorComponent, React.ReactNode]
children: React.ReactNode
}) {
const openOverlay = useCallback(() => {
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
}, [dispatch])
return (
<>
<AppDevOverlayErrorBoundary
globalError={globalError}
onError={openOverlay}
>
{children}
</AppDevOverlayErrorBoundary>
<>
{/* Fonts can only be loaded outside the Shadow DOM. */}
<FontStyles />
<DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
/>
</>
</>
)
}
......@@ -4,8 +4,6 @@ import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader
import GlobalError from '../../global-error'
import { AppDevOverlayErrorBoundary } from './app-dev-overlay-error-boundary'
const noop = () => {}
// if an error is thrown while rendering an RSC stream, this will catch it in dev
// and show the error overlay
export function createRootLevelDevOverlayElement(reactEl: React.ReactElement) {
......@@ -31,10 +29,7 @@ export function createRootLevelDevOverlayElement(reactEl: React.ReactElement) {
socket.addEventListener('message', handler)
return (
<AppDevOverlayErrorBoundary
globalError={[GlobalError, null]}
onError={noop}
>
<AppDevOverlayErrorBoundary globalError={[GlobalError, null]}>
{reactEl}
</AppDevOverlayErrorBoundary>
)
......
/// <reference types="webpack/module.d.ts" />
import type { ReactNode } from 'react'
import { useEffect, startTransition, useMemo, useRef } from 'react'
import { useEffect, startTransition, useRef } from 'react'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import formatWebpackMessages from '../utils/format-webpack-messages'
import { useRouter } from '../../navigation'
import {
ACTION_BEFORE_REFRESH,
ACTION_BUILDING_INDICATOR_HIDE,
ACTION_BUILD_ERROR,
ACTION_BUILD_OK,
ACTION_BUILDING_INDICATOR_SHOW,
ACTION_DEBUG_INFO,
ACTION_DEV_INDICATOR,
ACTION_ERROR_OVERLAY_OPEN,
ACTION_REFRESH,
ACTION_STATIC_INDICATOR,
ACTION_UNHANDLED_ERROR,
ACTION_UNHANDLED_REJECTION,
ACTION_VERSION_INFO,
REACT_REFRESH_FULL_RELOAD,
reportInvalidHmrMessage,
useErrorOverlayReducer,
} from '../shared'
import { AppDevOverlay } from './app-dev-overlay'
import { REACT_REFRESH_FULL_RELOAD, reportInvalidHmrMessage } from '../shared'
import { dispatcher } from 'next/dist/compiled/next-devtools'
import { ReplaySsrOnlyErrors } from './replay-ssr-only-errors'
import { AppDevOverlayErrorBoundary } from './app-dev-overlay-error-boundary'
import { useErrorHandler } from '../../errors/use-error-handler'
import { RuntimeErrorHandler } from '../../errors/runtime-error-handler'
import {
......@@ -33,38 +17,17 @@ import {
useWebsocket,
useWebsocketPing,
} from '../utils/use-websocket'
import type { VersionInfo } from '../../../../server/dev/parse-version-info'
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader-types'
import type {
HMR_ACTION_TYPES,
TurbopackMsgToBrowser,
} from '../../../../server/dev/hot-reloader-types'
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared'
import type { DebugInfo } from '../types'
import { useUntrackedPathname } from '../../navigation-untracked'
import type { GlobalErrorComponent } from '../../global-error'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
import reportHmrLatency from '../utils/report-hmr-latency'
import { TurbopackHmr } from '../utils/turbopack-hot-reloader-common'
import { NEXT_HMR_REFRESH_HASH_COOKIE } from '../../app-router-headers'
import { getComponentStack, getOwnerStack } from '../../errors/stitched-error'
import { isRecoverableError } from '../../../react-client-callbacks/on-recoverable-error'
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
onUnhandledError(error: Error): void
onUnhandledRejection(error: Error): void
openErrorOverlay(): void
buildingIndicatorHide(): void
buildingIndicatorShow(): void
}
let mostRecentCompilationHash: any = null
let __nextDevClientId = Math.round(Math.random() * 100 + Date.now())
......@@ -150,10 +113,7 @@ function performFullReload(err: any, sendMessage: any) {
}
// Attempt to update code on the fly, fall back to a hard reload.
function tryApplyUpdatesWebpack(
sendMessage: (message: string) => void,
dispatcher: Dispatcher
) {
function tryApplyUpdatesWebpack(sendMessage: (message: string) => void) {
if (!isUpdateAvailable() || !canApplyUpdates()) {
resolvePendingHotUpdateWebpack()
dispatcher.onBuildOk()
......@@ -179,7 +139,7 @@ function tryApplyUpdatesWebpack(
if (isUpdateAvailable()) {
// While we were updating, there was a new update! Do it again.
tryApplyUpdatesWebpack(sendMessage, dispatcher)
tryApplyUpdatesWebpack(sendMessage)
return
}
......@@ -233,7 +193,6 @@ function processMessage(
sendMessage: (message: string) => void,
processTurbopackMessage: (msg: TurbopackMsgToBrowser) => void,
router: ReturnType<typeof useRouter>,
dispatcher: Dispatcher,
appIsrManifestRef: ReturnType<typeof useRef>,
pathnameRef: ReturnType<typeof useRef>
) {
......@@ -281,7 +240,7 @@ function processMessage(
}
dispatcher.onBuildOk()
} else {
tryApplyUpdatesWebpack(sendMessage, dispatcher)
tryApplyUpdatesWebpack(sendMessage)
}
}
......@@ -491,66 +450,6 @@ export default function HotReload({
children: ReactNode
globalError: [GlobalErrorComponent, React.ReactNode]
}) {
const [state, dispatch] = useErrorOverlayReducer(
'app',
getComponentStack,
getOwnerStack,
isRecoverableError
)
const dispatcher = useMemo<Dispatcher>(() => {
return {
onBuildOk() {
dispatch({ type: ACTION_BUILD_OK })
},
onBuildError(message) {
dispatch({ type: ACTION_BUILD_ERROR, message })
},
onBeforeRefresh() {
dispatch({ type: ACTION_BEFORE_REFRESH })
},
onRefresh() {
dispatch({ type: ACTION_REFRESH })
},
onVersionInfo(versionInfo) {
dispatch({ type: ACTION_VERSION_INFO, versionInfo })
},
onStaticIndicator(status: boolean) {
dispatch({ type: ACTION_STATIC_INDICATOR, staticIndicator: status })
},
onDebugInfo(debugInfo) {
dispatch({ type: ACTION_DEBUG_INFO, debugInfo })
},
onDevIndicator(devIndicator) {
dispatch({
type: ACTION_DEV_INDICATOR,
devIndicator,
})
},
onUnhandledError(error) {
dispatch({
type: ACTION_UNHANDLED_ERROR,
reason: error,
})
},
onUnhandledRejection(error) {
dispatch({
type: ACTION_UNHANDLED_REJECTION,
reason: error,
})
},
openErrorOverlay() {
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
},
buildingIndicatorHide() {
dispatch({ type: ACTION_BUILDING_INDICATOR_HIDE })
},
buildingIndicatorShow() {
dispatch({ type: ACTION_BUILDING_INDICATOR_SHOW })
},
}
}, [dispatch])
useErrorHandler(dispatcher.onUnhandledError, dispatcher.onUnhandledRejection)
const webSocketRef = useWebsocket(assetPrefix)
......@@ -599,7 +498,7 @@ export default function HotReload({
dispatcher.onStaticIndicator(false)
}
}
}, [pathname, dispatcher])
}, [pathname])
}
useEffect(() => {
......@@ -614,7 +513,6 @@ export default function HotReload({
sendMessage,
processTurbopackMessage,
router,
dispatcher,
appIsrManifestRef,
pathnameRef
)
......@@ -629,15 +527,14 @@ export default function HotReload({
sendMessage,
router,
webSocketRef,
dispatcher,
processTurbopackMessage,
appIsrManifestRef,
])
return (
<AppDevOverlay state={state} dispatch={dispatch} globalError={globalError}>
<AppDevOverlayErrorBoundary globalError={globalError}>
<ReplaySsrOnlyErrors onBlockingError={dispatcher.openErrorOverlay} />
{children}
</AppDevOverlay>
</AppDevOverlayErrorBoundary>
)
}
import { useInsertionEffect } from 'react'
import { PagesDevOverlayErrorBoundary } from './pages-dev-overlay-error-boundary'
import { usePagesDevOverlay } from './hooks'
import { FontStyles } from '../font/font-styles'
......@@ -15,6 +16,12 @@ interface PagesDevOverlayProps {
export function PagesDevOverlay({ children }: PagesDevOverlayProps) {
const { state, dispatch } = usePagesDevOverlay()
// TODO: Remove once Root initializer creates this element
useInsertionEffect(() => {
const container = document.createElement('nextjs-portal')
document.body.appendChild(container)
}, [])
return (
<>
<PagesDevOverlayErrorBoundary>{children}</PagesDevOverlayErrorBoundary>
......
......@@ -23,6 +23,7 @@ export interface OverlayState {
versionInfo: VersionInfo
notFound: boolean
buildingIndicator: boolean
renderingIndicator: boolean
staticIndicator: boolean
showIndicator: boolean
disableDevIndicator: boolean
......@@ -47,6 +48,8 @@ export const ACTION_ERROR_OVERLAY_CLOSE = 'error-overlay-close'
export const ACTION_ERROR_OVERLAY_TOGGLE = 'error-overlay-toggle'
export const ACTION_BUILDING_INDICATOR_SHOW = 'building-indicator-show'
export const ACTION_BUILDING_INDICATOR_HIDE = 'building-indicator-hide'
export const ACTION_RENDERING_INDICATOR_SHOW = 'rendering-indicator-show'
export const ACTION_RENDERING_INDICATOR_HIDE = 'rendering-indicator-hide'
export const STORAGE_KEY_THEME = '__nextjs-dev-tools-theme'
export const STORAGE_KEY_POSITION = '__nextjs-dev-tools-position'
......@@ -112,6 +115,13 @@ export interface BuildingIndicatorHideAction {
type: typeof ACTION_BUILDING_INDICATOR_HIDE
}
export interface RenderingIndicatorShowAction {
type: typeof ACTION_RENDERING_INDICATOR_SHOW
}
export interface RenderingIndicatorHideAction {
type: typeof ACTION_RENDERING_INDICATOR_HIDE
}
export type BusEvent =
| BuildOkAction
| BuildErrorAction
......@@ -128,6 +138,8 @@ export type BusEvent =
| ErrorOverlayToggleAction
| BuildingIndicatorShowAction
| BuildingIndicatorHideAction
| RenderingIndicatorShowAction
| RenderingIndicatorHideAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: v8
......@@ -153,6 +165,7 @@ export const INITIAL_OVERLAY_STATE: Omit<
buildError: null,
errors: [],
notFound: false,
renderingIndicator: false,
staticIndicator: false,
/*
This is set to `true` when we can reliably know
......@@ -315,6 +328,12 @@ export function useErrorOverlayReducer(
case ACTION_BUILDING_INDICATOR_HIDE: {
return { ...state, buildingIndicator: false }
}
case ACTION_RENDERING_INDICATOR_SHOW: {
return { ...state, renderingIndicator: true }
}
case ACTION_RENDERING_INDICATOR_HIDE: {
return { ...state, renderingIndicator: false }
}
default: {
return state
}
......
......@@ -55,6 +55,7 @@ const state: OverlayState = {
versionInfo: mockVersionInfo,
notFound: false,
buildingIndicator: false,
renderingIndicator: false,
staticIndicator: true,
debugInfo: { devtoolsFrontendUrl: undefined },
isErrorOverlayOpen: false,
......
......@@ -10,7 +10,6 @@ import {
import { useState, useEffect, useRef, createContext, useContext } from 'react'
import { Toast } from '../../toast'
import { NextLogo } from './next-logo'
import { useIsDevRendering } from '../../../../utils/dev-indicator/dev-render-indicator'
import { useDelayedRender } from '../../../hooks/use-delayed-render'
import { TurbopackInfo } from './dev-tools-info/turbopack-info'
import { RouteInfo } from './dev-tools-info/route-info'
......@@ -54,6 +53,7 @@ export function DevToolsIndicator({
semver={state.versionInfo.installed}
issueCount={errorCount}
isDevBuilding={state.buildingIndicator}
isDevRendering={state.renderingIndicator}
isStaticRoute={state.staticIndicator}
hide={() => {
setIsDevToolsIndicatorVisible(false)
......@@ -96,6 +96,7 @@ function DevToolsPopover({
disabled,
issueCount,
isDevBuilding,
isDevRendering,
isStaticRoute,
isTurbopack,
isBuildError,
......@@ -110,6 +111,7 @@ function DevToolsPopover({
isStaticRoute: boolean
semver: string | undefined
isDevBuilding: boolean
isDevRendering: boolean
isTurbopack: boolean
isBuildError: boolean
hide: () => void
......@@ -297,7 +299,7 @@ function DevToolsPopover({
onTriggerClick={onTriggerClick}
toggleErrorOverlay={toggleErrorOverlay}
isDevBuilding={isDevBuilding}
isDevRendering={useIsDevRendering()}
isDevRendering={isDevRendering}
isBuildError={isBuildError}
scale={scale}
/>
......
......@@ -13,7 +13,7 @@ export function ShadowPortal({ children }: { children: React.ReactNode }) {
// we can assure the root render is not a Transition.
React.useEffect(() => {
const ownerDocument = document
portalNode.current = ownerDocument.createElement('nextjs-portal')
portalNode.current = ownerDocument.querySelector('nextjs-portal')!
// load default color preference from localstorage
if (typeof localStorage !== 'undefined') {
const theme = localStorage.getItem(STORAGE_KEY_THEME)
......@@ -26,14 +26,15 @@ export function ShadowPortal({ children }: { children: React.ReactNode }) {
}
}
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
ownerDocument.body.appendChild(portalNode.current)
forceUpdate({})
return () => {
if (portalNode.current && portalNode.current.ownerDocument) {
portalNode.current.ownerDocument.body.removeChild(portalNode.current)
}
// We can only attach but never detach a shadow root.
// So if this is a remount, we don't need to attach a shadow root. Only
// on the very first, DOM-wide mount.
// This is mostly guarding against faulty _app implementations that
// createa React Root in getInitialProps but don't clean it up like test/integration/app-tree/pages/_app.tsx
if (portalNode.current.shadowRoot === null) {
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
}
forceUpdate({})
}, [])
return shadowNode.current
......
......@@ -74,6 +74,7 @@ const initialState: OverlayState = {
refreshState: { type: 'idle' },
notFound: false,
buildingIndicator: false,
renderingIndicator: false,
staticIndicator: false,
debugInfo: { devtoolsFrontendUrl: undefined },
versionInfo: {
......
/*
* Singleton store to track whether the app is currently being rendered
* Used by the dev tools indicator to show render status
*/
import { useSyncExternalStore } from 'react'
let isVisible = false
let listeners: Array<() => void> = []
const subscribe = (listener: () => void) => {
listeners.push(listener)
return () => {
listeners = listeners.filter((l) => l !== listener)
}
}
const getSnapshot = () => isVisible
const show = () => {
isVisible = true
listeners.forEach((listener) => listener())
}
const hide = () => {
isVisible = false
listeners.forEach((listener) => listener())
}
export function useIsDevRendering() {
return useSyncExternalStore(subscribe, getSnapshot)
}
export const devRenderIndicator = {
show,
hide,
}
import { useEffect, useTransition } from 'react'
import { devRenderIndicator } from './dev-render-indicator'
import { dispatcher } from 'next/dist/compiled/next-devtools'
export const useSyncDevRenderIndicator = () => {
export const useAppDevRenderingIndicator = () => {
const [isPending, startTransition] = useTransition()
useEffect(() => {
if (isPending) {
devRenderIndicator.show()
dispatcher.renderingIndicatorShow()
} else {
devRenderIndicator.hide()
dispatcher.renderingIndicatorHide()
}
}, [isPending])
......
......@@ -35,14 +35,13 @@ export function useActionQueue(
// this is conceptually how we're modeling the app router state, despite the
// weird implementation details.
if (process.env.NODE_ENV !== 'production') {
const useSyncDevRenderIndicator = (
require('./react-dev-overlay/utils/dev-indicator/use-sync-dev-render-indicator') as typeof import('./react-dev-overlay/utils/dev-indicator/use-sync-dev-render-indicator')
).useSyncDevRenderIndicator
const { useAppDevRenderingIndicator } =
require('./react-dev-overlay/utils/dev-indicator/use-app-dev-rendering-indicator') as typeof import('./react-dev-overlay/utils/dev-indicator/use-app-dev-rendering-indicator')
// eslint-disable-next-line react-hooks/rules-of-hooks
const syncDevRenderIndicator = useSyncDevRenderIndicator()
const appDevRenderingIndicator = useAppDevRenderingIndicator()
dispatch = (action: ReducerActions) => {
syncDevRenderIndicator(() => {
appDevRenderingIndicator(() => {
actionQueue.dispatch(action, setState)
})
}
......
......@@ -179,9 +179,7 @@ class Container extends React.Component<{
if (process.env.NODE_ENV === 'production') {
return this.props.children
} else {
const {
PagesDevOverlay,
}: typeof import('./components/react-dev-overlay/pages/pages-dev-overlay') =
const { PagesDevOverlay } =
require('./components/react-dev-overlay/pages/pages-dev-overlay') as typeof import('./components/react-dev-overlay/pages/pages-dev-overlay')
return <PagesDevOverlay>{this.props.children}</PagesDevOverlay>
}
......
......@@ -3132,6 +3132,17 @@ export async function next_bundle_server(task, opts) {
})
}
export async function next_bundle_devtools(task, opts) {
await task.source('dist').webpack({
watch: opts.dev,
config: require('./next-devtools.webpack-config')({
// TODO: Use prod variant
dev: true,
}),
name: 'next-bundle-devtools-dev',
})
}
export async function next_bundle(task, opts) {
await task.parallel(
[
......@@ -3152,6 +3163,8 @@ export async function next_bundle(task, opts) {
'next_bundle_pages_dev_turbo',
// builds the minimal server
'next_bundle_server',
// devtools
'next_bundle_devtools',
],
opts
)
......
......@@ -24,6 +24,11 @@
"next/dist/compiled/@vercel/og/satori": [
"./src/compiled/@vercel/og/satori"
],
// TODO: Enable types by telling Turbopack to ignore this alias.
// tsconfig#paths are for type locations not source locations.
// "next/dist/compiled/next-devtools": [
// "./src/client/components/react-dev-overlay/app/entrypoint.d.ts"
// ],
"next/dist/shared/lib/image-loader": ["./src/shared/lib/image-loader.ts"]
}
},
......
......@@ -364,6 +364,9 @@ declare module 'next/dist/compiled/jest-worker' {
export * from 'jest-worker'
}
// TODO: Use tsconfig#paths instead
declare module 'next/dist/compiled/next-devtools'
declare module 'next/dist/compiled/react-is' {
export * from 'react-is'
}
......
......@@ -2,6 +2,9 @@
// it is not meant to be used with local type checking and is ignored in our
// local tsconfig.json
// TODO: Use tsconfig#paths instead
declare module 'next/dist/compiled/next-devtools'
declare module 'next/dist/compiled/webpack/webpack' {
export function init(): void
export let BasicEvaluatedExpression: any
......
......@@ -553,7 +553,7 @@ describe('ReactRefreshLogBox app', () => {
await session.evaluate(
() =>
document
.querySelector('body > nextjs-portal')
.querySelector('body nextjs-portal')
.shadowRoot.querySelectorAll('#nextjs__container_errors_desc a')
.length
)
......@@ -563,7 +563,7 @@ describe('ReactRefreshLogBox app', () => {
() =>
(
document
.querySelector('body > nextjs-portal')
.querySelector('body nextjs-portal')
.shadowRoot.querySelector(
'#nextjs__container_errors_desc a:nth-of-type(1)'
) as any
......@@ -635,7 +635,7 @@ describe('ReactRefreshLogBox app', () => {
await session.evaluate(
() =>
document
.querySelector('body > nextjs-portal')
.querySelector('body nextjs-portal')
.shadowRoot.querySelectorAll('#nextjs__container_errors_desc a')
.length
)
......@@ -645,7 +645,7 @@ describe('ReactRefreshLogBox app', () => {
() =>
(
document
.querySelector('body > nextjs-portal')
.querySelector('body nextjs-portal')
.shadowRoot.querySelector(
'#nextjs__container_errors_desc a:nth-of-type(1)'
) as any
......@@ -717,7 +717,7 @@ describe('ReactRefreshLogBox app', () => {
await session.evaluate(
() =>
document
.querySelector('body > nextjs-portal')
.querySelector('body nextjs-portal')
.shadowRoot.querySelectorAll('#nextjs__container_errors_desc a')
.length
)
......@@ -727,7 +727,7 @@ describe('ReactRefreshLogBox app', () => {
() =>
(
document
.querySelector('body > nextjs-portal')
.querySelector('body nextjs-portal')
.shadowRoot.querySelector(
'#nextjs__container_errors_desc a:nth-of-type(1)'
) as any
......@@ -800,7 +800,7 @@ describe('ReactRefreshLogBox app', () => {
await session.evaluate(
() =>
document
.querySelector('body > nextjs-portal')
.querySelector('body nextjs-portal')
.shadowRoot.querySelectorAll('#nextjs__container_errors_desc a')
.length
)
......@@ -810,7 +810,7 @@ describe('ReactRefreshLogBox app', () => {
() =>
(
document
.querySelector('body > nextjs-portal')
.querySelector('body nextjs-portal')
.shadowRoot.querySelector(
'#nextjs__container_errors_desc a:nth-of-type(1)'
) as any
......@@ -822,7 +822,7 @@ describe('ReactRefreshLogBox app', () => {
() =>
(
document
.querySelector('body > nextjs-portal')
.querySelector('body nextjs-portal')
.shadowRoot.querySelector(
'#nextjs__container_errors_desc a:nth-of-type(2)'
) as any
......
......@@ -209,25 +209,23 @@ describe('Error overlay for hydration errors in App router', () => {
{
"componentStack": "...
<HotReload assetPrefix="" globalError={[...]}>
<AppDevOverlay state={{nextId:1, ...}} dispatch={function bound dispatchReducerAction} globalError={[...]}>
<AppDevOverlayErrorBoundary globalError={[...]} onError={function}>
<ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary>
<HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={<NotAllowedRootHTTPFallbackError>} ...>
<RedirectBoundary>
<RedirectErrorBoundary router={{...}}>
<Head>
<script>
<script>
<script>
<ClientSegmentRoot Component={function Root} slots={{...}} params={{}}>
<Root params={Promise}>
<html
- className="server-html"
>
...
...",
<AppDevOverlayErrorBoundary globalError={[...]}>
<ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary>
<HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={<NotAllowedRootHTTPFallbackError>} ...>
<RedirectBoundary>
<RedirectErrorBoundary router={{...}}>
<Head>
<script>
<script>
<script>
<ClientSegmentRoot Component={function Root} slots={{...}} params={{}}>
<Root params={Promise}>
<html
- className="server-html"
>
...",
"description": "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:",
"environmentLabel": null,
"label": "Console Error",
......@@ -245,22 +243,20 @@ describe('Error overlay for hydration errors in App router', () => {
{
"componentStack": "...
<HotReload assetPrefix="" globalError={[...]}>
<AppDevOverlay state={{nextId:1, ...}} dispatch={function bound dispatchReducerAction} globalError={[...]}>
<AppDevOverlayErrorBoundary globalError={[...]} onError={function}>
<ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary>
<HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={<NotAllowedRootHTTPFallbackError>} ...>
<RedirectBoundary>
<RedirectErrorBoundary router={{...}}>
<Head>
<ClientSegmentRoot Component={function Root} slots={{...}} params={{}}>
<Root params={Promise}>
<html
- className="server-html"
>
...
...",
<AppDevOverlayErrorBoundary globalError={[...]}>
<ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary>
<HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}>
<HTTPAccessFallbackErrorBoundary pathname="/" notFound={<NotAllowedRootHTTPFallbackError>} ...>
<RedirectBoundary>
<RedirectErrorBoundary router={{...}}>
<Head>
<ClientSegmentRoot Component={function Root} slots={{...}} params={{}}>
<Root params={Promise}>
<html
- className="server-html"
>
...",
"description": "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up. This can happen if a SSR-ed Client Component used:",
"environmentLabel": null,
"label": "Console Error",
......@@ -1044,9 +1040,11 @@ describe('Error overlay for hydration errors in App router', () => {
},
{
"componentStack": "...
<HotReload assetPrefix="" globalError={[...]}>
<AppDevOverlay state={{nextId:1, ...}} dispatch={function bound dispatchReducerAction} globalError={[...]}>
<AppDevOverlayErrorBoundary globalError={[...]} onError={function}>
<Router actionQueue={{state:{...}, ...}} assetPrefix="" globalError={[...]} gracefullyDegrade={false}>
<HistoryUpdater>
<RuntimeStyles>
<HotReload assetPrefix="" globalError={[...]}>
<AppDevOverlayErrorBoundary globalError={[...]}>
<ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary>
<HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}>
......@@ -1059,8 +1057,7 @@ describe('Error overlay for hydration errors in App router', () => {
<body>
<Script src="https://ex..." strategy="beforeInte...">
> <script nonce={undefined} dangerouslySetInnerHTML={{__html:"(self.__ne..."}}>
...
...",
...",
"description": "In HTML, <script> cannot be a child of <html>.
This will cause a hydration error.",
"environmentLabel": null,
......
......@@ -15,6 +15,9 @@
"packages/next/src/client/app-bootstrap.ts",
"packages/next/src/client/components/errors/graceful-degrade-boundary.tsx"
],
"ban-script-appendchild-calls": [
"packages/next/src/client/components/react-dev-overlay/app/app-dev-overlay.browser.tsx"
],
"ban-script-content-assignments": ["packages/next/src/client/script.tsx"],
"ban-script-src-assignments": [
"packages/next/src/client/script.tsx",
......
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