Unverified Commit 895908a3 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[dev-overlay] Move building indicator into Dev Overlay state (#79985)

Used to be a singleton treated as a sync external store. The singleton would require extra attention once we move into a separate bundle. Instead, I moved it into actual React state to get rid of the sync external store.
We want to avoid sync external stores as much as possible to leverage React's concurrent features to the fullest.

If we need to slice the state up, we can investigate that separately.
parent 61bd07fa
...@@ -3,12 +3,10 @@ ...@@ -3,12 +3,10 @@
import './app-webpack' import './app-webpack'
import { appBootstrap } from './app-bootstrap' import { appBootstrap } from './app-bootstrap'
import { initializeDevBuildIndicatorForAppRouter } from './dev/dev-build-indicator/initialize-for-app-router'
const instrumentationHooks = require('../lib/require-instrumentation-client') const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap(() => { appBootstrap(() => {
const { hydrate } = require('./app-index') const { hydrate } = require('./app-index')
hydrate(instrumentationHooks) hydrate(instrumentationHooks)
initializeDevBuildIndicatorForAppRouter()
}) })
...@@ -10,10 +10,4 @@ const instrumentationHooks = require('../lib/require-instrumentation-client') ...@@ -10,10 +10,4 @@ const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap(() => { appBootstrap(() => {
const { hydrate } = require('./app-index') const { hydrate } = require('./app-index')
hydrate(instrumentationHooks) hydrate(instrumentationHooks)
if (process.env.NODE_ENV !== 'production') {
const { initializeDevBuildIndicatorForAppRouter } =
require('./dev/dev-build-indicator/initialize-for-app-router') as typeof import('./dev/dev-build-indicator/initialize-for-app-router')
initializeDevBuildIndicatorForAppRouter()
}
}) })
...@@ -7,8 +7,10 @@ import formatWebpackMessages from '../utils/format-webpack-messages' ...@@ -7,8 +7,10 @@ import formatWebpackMessages from '../utils/format-webpack-messages'
import { useRouter } from '../../navigation' import { useRouter } from '../../navigation'
import { import {
ACTION_BEFORE_REFRESH, ACTION_BEFORE_REFRESH,
ACTION_BUILDING_INDICATOR_HIDE,
ACTION_BUILD_ERROR, ACTION_BUILD_ERROR,
ACTION_BUILD_OK, ACTION_BUILD_OK,
ACTION_BUILDING_INDICATOR_SHOW,
ACTION_DEBUG_INFO, ACTION_DEBUG_INFO,
ACTION_DEV_INDICATOR, ACTION_DEV_INDICATOR,
ACTION_ERROR_OVERLAY_OPEN, ACTION_ERROR_OVERLAY_OPEN,
...@@ -40,7 +42,6 @@ import type { ...@@ -40,7 +42,6 @@ import type {
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared' import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from '../shared'
import type { DebugInfo } from '../types' import type { DebugInfo } from '../types'
import { useUntrackedPathname } from '../../navigation-untracked' import { useUntrackedPathname } from '../../navigation-untracked'
import { handleDevBuildIndicatorHmrEvents } from '../../../dev/dev-build-indicator/internal/handle-dev-build-indicator-hmr-events'
import type { GlobalErrorComponent } from '../../global-error' import type { GlobalErrorComponent } from '../../global-error'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state' import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
import reportHmrLatency from '../utils/report-hmr-latency' import reportHmrLatency from '../utils/report-hmr-latency'
...@@ -61,6 +62,8 @@ export interface Dispatcher { ...@@ -61,6 +62,8 @@ export interface Dispatcher {
onUnhandledError(error: Error): void onUnhandledError(error: Error): void
onUnhandledRejection(error: Error): void onUnhandledRejection(error: Error): void
openErrorOverlay(): void openErrorOverlay(): void
buildingIndicatorHide(): void
buildingIndicatorShow(): void
} }
let mostRecentCompilationHash: any = null let mostRecentCompilationHash: any = null
...@@ -302,6 +305,8 @@ function processMessage( ...@@ -302,6 +305,8 @@ function processMessage(
break break
} }
case HMR_ACTIONS_SENT_TO_BROWSER.BUILDING: { case HMR_ACTIONS_SENT_TO_BROWSER.BUILDING: {
dispatcher.buildingIndicatorShow()
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
turbopackHmr!.onBuilding() turbopackHmr!.onBuilding()
} else { } else {
...@@ -313,6 +318,8 @@ function processMessage( ...@@ -313,6 +318,8 @@ function processMessage(
} }
case HMR_ACTIONS_SENT_TO_BROWSER.BUILT: case HMR_ACTIONS_SENT_TO_BROWSER.BUILT:
case HMR_ACTIONS_SENT_TO_BROWSER.SYNC: { case HMR_ACTIONS_SENT_TO_BROWSER.SYNC: {
dispatcher.buildingIndicatorHide()
if (obj.hash) { if (obj.hash) {
handleAvailableHash(obj.hash) handleAvailableHash(obj.hash)
} }
...@@ -535,6 +542,12 @@ export default function HotReload({ ...@@ -535,6 +542,12 @@ export default function HotReload({
openErrorOverlay() { openErrorOverlay() {
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN }) dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
}, },
buildingIndicatorHide() {
dispatch({ type: ACTION_BUILDING_INDICATOR_HIDE })
},
buildingIndicatorShow() {
dispatch({ type: ACTION_BUILDING_INDICATOR_SHOW })
},
} }
}, [dispatch]) }, [dispatch])
...@@ -596,7 +609,6 @@ export default function HotReload({ ...@@ -596,7 +609,6 @@ export default function HotReload({
const handler = (event: MessageEvent<any>) => { const handler = (event: MessageEvent<any>) => {
try { try {
const obj = JSON.parse(event.data) const obj = JSON.parse(event.data)
handleDevBuildIndicatorHmrEvents(obj)
processMessage( processMessage(
obj, obj,
sendMessage, sendMessage,
......
...@@ -5,8 +5,10 @@ import { ...@@ -5,8 +5,10 @@ import {
} from './hydration-error-state' } from './hydration-error-state'
import { import {
ACTION_BEFORE_REFRESH, ACTION_BEFORE_REFRESH,
ACTION_BUILDING_INDICATOR_HIDE,
ACTION_BUILD_ERROR, ACTION_BUILD_ERROR,
ACTION_BUILD_OK, ACTION_BUILD_OK,
ACTION_BUILDING_INDICATOR_SHOW,
ACTION_DEV_INDICATOR, ACTION_DEV_INDICATOR,
ACTION_REFRESH, ACTION_REFRESH,
ACTION_STATIC_INDICATOR, ACTION_STATIC_INDICATOR,
...@@ -115,5 +117,13 @@ export function onDevIndicator(devIndicatorsState: DevIndicatorServerState) { ...@@ -115,5 +117,13 @@ export function onDevIndicator(devIndicatorsState: DevIndicatorServerState) {
Bus.emit({ type: ACTION_DEV_INDICATOR, devIndicator: devIndicatorsState }) Bus.emit({ type: ACTION_DEV_INDICATOR, devIndicator: devIndicatorsState })
} }
export function buildingIndicatorShow() {
Bus.emit({ type: ACTION_BUILDING_INDICATOR_SHOW })
}
export function buildingIndicatorHide() {
Bus.emit({ type: ACTION_BUILDING_INDICATOR_HIDE })
}
export { getErrorByType } from '../utils/get-error-by-type' export { getErrorByType } from '../utils/get-error-by-type'
export { getServerError } from '../utils/node-stack-frames' export { getServerError } from '../utils/node-stack-frames'
...@@ -41,6 +41,8 @@ import { ...@@ -41,6 +41,8 @@ import {
onVersionInfo, onVersionInfo,
onStaticIndicator, onStaticIndicator,
onDevIndicator, onDevIndicator,
buildingIndicatorHide,
buildingIndicatorShow,
} from './client' } from './client'
import stripAnsi from 'next/dist/compiled/strip-ansi' import stripAnsi from 'next/dist/compiled/strip-ansi'
import { addMessageListener, sendMessage } from './websocket' import { addMessageListener, sendMessage } from './websocket'
...@@ -272,6 +274,8 @@ function processMessage(obj: HMR_ACTION_TYPES) { ...@@ -272,6 +274,8 @@ function processMessage(obj: HMR_ACTION_TYPES) {
break break
} }
case HMR_ACTIONS_SENT_TO_BROWSER.BUILDING: { case HMR_ACTIONS_SENT_TO_BROWSER.BUILDING: {
buildingIndicatorShow()
if (process.env.TURBOPACK) { if (process.env.TURBOPACK) {
turbopackHmr!.onBuilding() turbopackHmr!.onBuilding()
} else { } else {
...@@ -282,6 +286,8 @@ function processMessage(obj: HMR_ACTION_TYPES) { ...@@ -282,6 +286,8 @@ function processMessage(obj: HMR_ACTION_TYPES) {
} }
case HMR_ACTIONS_SENT_TO_BROWSER.BUILT: case HMR_ACTIONS_SENT_TO_BROWSER.BUILT:
case HMR_ACTIONS_SENT_TO_BROWSER.SYNC: { case HMR_ACTIONS_SENT_TO_BROWSER.SYNC: {
buildingIndicatorHide()
if (obj.hash) handleAvailableHash(obj.hash) if (obj.hash) handleAvailableHash(obj.hash)
const { errors, warnings } = obj const { errors, warnings } = obj
......
...@@ -22,6 +22,7 @@ export interface OverlayState { ...@@ -22,6 +22,7 @@ export interface OverlayState {
refreshState: FastRefreshState refreshState: FastRefreshState
versionInfo: VersionInfo versionInfo: VersionInfo
notFound: boolean notFound: boolean
buildingIndicator: boolean
staticIndicator: boolean staticIndicator: boolean
showIndicator: boolean showIndicator: boolean
disableDevIndicator: boolean disableDevIndicator: boolean
...@@ -44,6 +45,8 @@ export const ACTION_DEV_INDICATOR = 'dev-indicator' ...@@ -44,6 +45,8 @@ export const ACTION_DEV_INDICATOR = 'dev-indicator'
export const ACTION_ERROR_OVERLAY_OPEN = 'error-overlay-open' export const ACTION_ERROR_OVERLAY_OPEN = 'error-overlay-open'
export const ACTION_ERROR_OVERLAY_CLOSE = 'error-overlay-close' export const ACTION_ERROR_OVERLAY_CLOSE = 'error-overlay-close'
export const ACTION_ERROR_OVERLAY_TOGGLE = 'error-overlay-toggle' 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 STORAGE_KEY_THEME = '__nextjs-dev-tools-theme' export const STORAGE_KEY_THEME = '__nextjs-dev-tools-theme'
export const STORAGE_KEY_POSITION = '__nextjs-dev-tools-position' export const STORAGE_KEY_POSITION = '__nextjs-dev-tools-position'
...@@ -102,6 +105,13 @@ export interface ErrorOverlayToggleAction { ...@@ -102,6 +105,13 @@ export interface ErrorOverlayToggleAction {
type: typeof ACTION_ERROR_OVERLAY_TOGGLE type: typeof ACTION_ERROR_OVERLAY_TOGGLE
} }
export interface BuildingIndicatorShowAction {
type: typeof ACTION_BUILDING_INDICATOR_SHOW
}
export interface BuildingIndicatorHideAction {
type: typeof ACTION_BUILDING_INDICATOR_HIDE
}
export type BusEvent = export type BusEvent =
| BuildOkAction | BuildOkAction
| BuildErrorAction | BuildErrorAction
...@@ -116,6 +126,8 @@ export type BusEvent = ...@@ -116,6 +126,8 @@ export type BusEvent =
| ErrorOverlayOpenAction | ErrorOverlayOpenAction
| ErrorOverlayCloseAction | ErrorOverlayCloseAction
| ErrorOverlayToggleAction | ErrorOverlayToggleAction
| BuildingIndicatorShowAction
| BuildingIndicatorHideAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: v8 // 1st group: v8
...@@ -149,6 +161,7 @@ export const INITIAL_OVERLAY_STATE: Omit< ...@@ -149,6 +161,7 @@ export const INITIAL_OVERLAY_STATE: Omit<
*/ */
showIndicator: false, showIndicator: false,
disableDevIndicator: false, disableDevIndicator: false,
buildingIndicator: false,
refreshState: { type: 'idle' }, refreshState: { type: 'idle' },
versionInfo: { installed: '0.0.0', staleness: 'unknown' }, versionInfo: { installed: '0.0.0', staleness: 'unknown' },
debugInfo: { devtoolsFrontendUrl: undefined }, debugInfo: { devtoolsFrontendUrl: undefined },
...@@ -296,6 +309,12 @@ export function useErrorOverlayReducer( ...@@ -296,6 +309,12 @@ export function useErrorOverlayReducer(
case ACTION_ERROR_OVERLAY_TOGGLE: { case ACTION_ERROR_OVERLAY_TOGGLE: {
return { ...state, isErrorOverlayOpen: !state.isErrorOverlayOpen } return { ...state, isErrorOverlayOpen: !state.isErrorOverlayOpen }
} }
case ACTION_BUILDING_INDICATOR_SHOW: {
return { ...state, buildingIndicator: true }
}
case ACTION_BUILDING_INDICATOR_HIDE: {
return { ...state, buildingIndicator: false }
}
default: { default: {
return state return state
} }
......
...@@ -54,6 +54,7 @@ const state: OverlayState = { ...@@ -54,6 +54,7 @@ const state: OverlayState = {
showIndicator: true, showIndicator: true,
versionInfo: mockVersionInfo, versionInfo: mockVersionInfo,
notFound: false, notFound: false,
buildingIndicator: false,
staticIndicator: true, staticIndicator: true,
debugInfo: { devtoolsFrontendUrl: undefined }, debugInfo: { devtoolsFrontendUrl: undefined },
isErrorOverlayOpen: false, isErrorOverlayOpen: false,
......
...@@ -10,7 +10,6 @@ import { ...@@ -10,7 +10,6 @@ import {
import { useState, useEffect, useRef, createContext, useContext } from 'react' import { useState, useEffect, useRef, createContext, useContext } from 'react'
import { Toast } from '../../toast' import { Toast } from '../../toast'
import { NextLogo } from './next-logo' import { NextLogo } from './next-logo'
import { useIsDevBuilding } from '../../../../../../dev/dev-build-indicator/internal/initialize'
import { useIsDevRendering } from '../../../../utils/dev-indicator/dev-render-indicator' import { useIsDevRendering } from '../../../../utils/dev-indicator/dev-render-indicator'
import { useDelayedRender } from '../../../hooks/use-delayed-render' import { useDelayedRender } from '../../../hooks/use-delayed-render'
import { TurbopackInfo } from './dev-tools-info/turbopack-info' import { TurbopackInfo } from './dev-tools-info/turbopack-info'
...@@ -54,6 +53,7 @@ export function DevToolsIndicator({ ...@@ -54,6 +53,7 @@ export function DevToolsIndicator({
routerType={state.routerType} routerType={state.routerType}
semver={state.versionInfo.installed} semver={state.versionInfo.installed}
issueCount={errorCount} issueCount={errorCount}
isDevBuilding={state.buildingIndicator}
isStaticRoute={state.staticIndicator} isStaticRoute={state.staticIndicator}
hide={() => { hide={() => {
setIsDevToolsIndicatorVisible(false) setIsDevToolsIndicatorVisible(false)
...@@ -95,6 +95,7 @@ function DevToolsPopover({ ...@@ -95,6 +95,7 @@ function DevToolsPopover({
routerType, routerType,
disabled, disabled,
issueCount, issueCount,
isDevBuilding,
isStaticRoute, isStaticRoute,
isTurbopack, isTurbopack,
isBuildError, isBuildError,
...@@ -108,6 +109,7 @@ function DevToolsPopover({ ...@@ -108,6 +109,7 @@ function DevToolsPopover({
issueCount: number issueCount: number
isStaticRoute: boolean isStaticRoute: boolean
semver: string | undefined semver: string | undefined
isDevBuilding: boolean
isTurbopack: boolean isTurbopack: boolean
isBuildError: boolean isBuildError: boolean
hide: () => void hide: () => void
...@@ -294,7 +296,7 @@ function DevToolsPopover({ ...@@ -294,7 +296,7 @@ function DevToolsPopover({
issueCount={issueCount} issueCount={issueCount}
onTriggerClick={onTriggerClick} onTriggerClick={onTriggerClick}
toggleErrorOverlay={toggleErrorOverlay} toggleErrorOverlay={toggleErrorOverlay}
isDevBuilding={useIsDevBuilding()} isDevBuilding={isDevBuilding}
isDevRendering={useIsDevRendering()} isDevRendering={useIsDevRendering()}
isBuildError={isBuildError} isBuildError={isBuildError}
scale={scale} scale={scale}
......
...@@ -73,6 +73,7 @@ const initialState: OverlayState = { ...@@ -73,6 +73,7 @@ const initialState: OverlayState = {
], ],
refreshState: { type: 'idle' }, refreshState: { type: 'idle' },
notFound: false, notFound: false,
buildingIndicator: false,
staticIndicator: false, staticIndicator: false,
debugInfo: { devtoolsFrontendUrl: undefined }, debugInfo: { devtoolsFrontendUrl: undefined },
versionInfo: { versionInfo: {
......
import { devBuildIndicator } from './internal/dev-build-indicator'
/** Integrates the generic dev build indicator with the App Router. */
export const initializeDevBuildIndicatorForAppRouter = () => {
if (!process.env.__NEXT_DEV_INDICATOR) {
return
}
devBuildIndicator.initialize()
}
import { addMessageListener } from '../../components/react-dev-overlay/pages/websocket'
import { devBuildIndicator } from './internal/dev-build-indicator'
import { handleDevBuildIndicatorHmrEvents } from './internal/handle-dev-build-indicator-hmr-events'
/** Integrates the generic dev build indicator with the Pages Router. */
export const initializeDevBuildIndicatorForPageRouter = () => {
if (!process.env.__NEXT_DEV_INDICATOR) {
return
}
devBuildIndicator.initialize()
// Add message listener specifically for Pages Router to handle lifecycle events
// related to dev builds (building, built, sync)
addMessageListener(handleDevBuildIndicatorHmrEvents)
}
import { initialize } from './initialize'
const NOOP = () => {}
export const devBuildIndicator = {
/** Shows build indicator when Next.js is compiling. Requires initialize() first. */
show: NOOP,
/** Hides build indicator when Next.js finishes compiling. Requires initialize() first. */
hide: NOOP,
/** Sets up the build indicator UI component. Call this before using show/hide. */
initialize,
}
import {
HMR_ACTIONS_SENT_TO_BROWSER,
type HMR_ACTION_TYPES,
} from '../../../../server/dev/hot-reloader-types'
import { devBuildIndicator } from './dev-build-indicator'
/**
* Handles HMR events to control the dev build indicator visibility.
* Shows indicator when building and hides it when build completes or syncs.
*/
export const handleDevBuildIndicatorHmrEvents = (obj: HMR_ACTION_TYPES) => {
try {
if (!('action' in obj)) {
return
}
// eslint-disable-next-line default-case
switch (obj.action) {
case HMR_ACTIONS_SENT_TO_BROWSER.BUILDING:
devBuildIndicator.show()
break
case HMR_ACTIONS_SENT_TO_BROWSER.BUILT:
case HMR_ACTIONS_SENT_TO_BROWSER.SYNC:
devBuildIndicator.hide()
break
}
} catch {}
}
/*
* Singleton store to track whether the app is currently being built
* Used by the dev tools indicator of the new overlay to show build status
*/
import { devBuildIndicator } from './dev-build-indicator'
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
export function useIsDevBuilding() {
return useSyncExternalStore(subscribe, getSnapshot)
}
export function initialize() {
devBuildIndicator.show = () => {
isVisible = true
listeners.forEach((listener) => listener())
}
devBuildIndicator.hide = () => {
isVisible = false
listeners.forEach((listener) => listener())
}
}
import '../lib/require-instrumentation-client' import '../lib/require-instrumentation-client'
import { hydrate, router } from './' import { hydrate, router } from './'
import initOnDemandEntries from './dev/on-demand-entries-client' import initOnDemandEntries from './dev/on-demand-entries-client'
import { devBuildIndicator } from './dev/dev-build-indicator/internal/dev-build-indicator'
import { displayContent } from './dev/fouc' import { displayContent } from './dev/fouc'
import { import {
connectHMR, connectHMR,
...@@ -15,7 +14,10 @@ import { HMR_ACTIONS_SENT_TO_BROWSER } from '../server/dev/hot-reloader-types' ...@@ -15,7 +14,10 @@ import { HMR_ACTIONS_SENT_TO_BROWSER } from '../server/dev/hot-reloader-types'
import { RuntimeErrorHandler } from './components/errors/runtime-error-handler' import { RuntimeErrorHandler } from './components/errors/runtime-error-handler'
import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from './components/react-dev-overlay/shared' import { REACT_REFRESH_FULL_RELOAD_FROM_ERROR } from './components/react-dev-overlay/shared'
import { performFullReload } from './components/react-dev-overlay/pages/hot-reloader-client' import { performFullReload } from './components/react-dev-overlay/pages/hot-reloader-client'
import { initializeDevBuildIndicatorForPageRouter } from './dev/dev-build-indicator/initialize-for-page-router' import {
buildingIndicatorHide,
buildingIndicatorShow,
} from './components/react-dev-overlay/pages/client'
export function pageBootstrap(assetPrefix: string) { export function pageBootstrap(assetPrefix: string) {
connectHMR({ assetPrefix, path: '/_next/webpack-hmr' }) connectHMR({ assetPrefix, path: '/_next/webpack-hmr' })
...@@ -23,8 +25,6 @@ export function pageBootstrap(assetPrefix: string) { ...@@ -23,8 +25,6 @@ export function pageBootstrap(assetPrefix: string) {
return hydrate({ beforeRender: displayContent }).then(() => { return hydrate({ beforeRender: displayContent }).then(() => {
initOnDemandEntries() initOnDemandEntries()
initializeDevBuildIndicatorForPageRouter()
let reloading = false let reloading = false
addMessageListener((payload) => { addMessageListener((payload) => {
...@@ -93,8 +93,8 @@ export function pageBootstrap(assetPrefix: string) { ...@@ -93,8 +93,8 @@ export function pageBootstrap(assetPrefix: string) {
if (!router.clc && pages.includes(router.pathname)) { if (!router.clc && pages.includes(router.pathname)) {
console.log('Refreshing page data due to server-side change') console.log('Refreshing page data due to server-side change')
devBuildIndicator.show() buildingIndicatorShow()
const clearIndicator = () => devBuildIndicator.hide() const clearIndicator = buildingIndicatorHide
router router
.replace( .replace(
......
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