Unverified Commit 5c49eecb authored by Jude Gao's avatar Jude Gao Committed by GitHub

refactor: generic dev build indicator (#74615)

- Decoupled pages router specific logic from the dev build indicator to
extract a generic version
- Created a pages router specific initialize function for dev build
indicator to be called on pages router hydration
- This prepares for upcoming work on the dev build indicator for App
router
- Covered by [e2e
test](https://github.com/vercel/next.js/blob/jude/refactor-dev-build-indicator/test/integration/build-indicator/test/index.test.js)
parent 6784575f
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../../server/dev/hot-reloader-types'
import { addMessageListener } from '../../components/react-dev-overlay/pages/websocket'
import { devBuildIndicator } from './internal/dev-build-indicator'
/** Integrates the generic dev build indicator with the Pages Router. */
export const initializeDevBuildIndicatorForPageRouter = () => {
if (!process.env.__NEXT_BUILD_INDICATOR) {
return
}
devBuildIndicator.initialize(process.env.__NEXT_BUILD_INDICATOR_POSITION)
// Add message listener specifically for Pages Router to handle lifecycle events
// related to dev builds (building, built, sync)
addMessageListener((obj) => {
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 {}
})
}
/* eslint-disable @typescript-eslint/no-use-before-define */
import { HMR_ACTIONS_SENT_TO_BROWSER } from '../../server/dev/hot-reloader-types'
import type { HMR_ACTION_TYPES } from '../../server/dev/hot-reloader-types'
import { addMessageListener } from '../components/react-dev-overlay/pages/websocket'
type VerticalPosition = 'top' | 'bottom' type VerticalPosition = 'top' | 'bottom'
type HorizonalPosition = 'left' | 'right' type HorizonalPosition = 'left' | 'right'
export interface ShowHideHandler { const NOOP = () => {}
show: () => void
hide: () => void 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,
} }
export default function initializeBuildWatcher( function initialize(position = 'bottom-right') {
toggleCallback: (handlers: ShowHideHandler) => void,
position = 'bottom-right'
) {
const shadowHost = document.createElement('div') const shadowHost = document.createElement('div')
const [verticalProperty, horizontalProperty] = position.split('-', 2) as [ const [verticalProperty, horizontalProperty] = position.split('-', 2) as [
VerticalPosition, VerticalPosition,
HorizonalPosition, HorizonalPosition,
] ]
shadowHost.id = '__next-build-watcher' shadowHost.id = '__next-build-indicator'
// Make sure container is fixed and on a high zIndex so it shows // Make sure container is fixed and on a high zIndex so it shows
shadowHost.style.position = 'fixed' shadowHost.style.position = 'fixed'
// Ensure container's position to be top or bottom (default) // Ensure container's position to be top or bottom (default)
...@@ -42,7 +40,7 @@ export default function initializeBuildWatcher( ...@@ -42,7 +40,7 @@ export default function initializeBuildWatcher(
// the Shadow DOM, we need to prefix all the names so there // the Shadow DOM, we need to prefix all the names so there
// will be no conflicts // will be no conflicts
shadowRoot = shadowHost shadowRoot = shadowHost
prefix = '__next-build-watcher-' prefix = '__next-build-indicator-'
} }
// Container // Container
...@@ -58,22 +56,14 @@ export default function initializeBuildWatcher( ...@@ -58,22 +56,14 @@ export default function initializeBuildWatcher(
let isBuilding = false let isBuilding = false
let timeoutId: null | ReturnType<typeof setTimeout> = null let timeoutId: null | ReturnType<typeof setTimeout> = null
// Handle events devBuildIndicator.show = () => {
addMessageListener((obj) => {
try {
handleMessage(obj)
} catch {}
})
function show() {
timeoutId && clearTimeout(timeoutId) timeoutId && clearTimeout(timeoutId)
isVisible = true isVisible = true
isBuilding = true isBuilding = true
updateContainer() updateContainer()
} }
function hide() { devBuildIndicator.hide = () => {
isBuilding = false isBuilding = false
// Wait for the fade out transition to complete // Wait for the fade out transition to complete
timeoutId = setTimeout(() => { timeoutId = setTimeout(() => {
...@@ -83,28 +73,6 @@ export default function initializeBuildWatcher( ...@@ -83,28 +73,6 @@ export default function initializeBuildWatcher(
updateContainer() updateContainer()
} }
function handleMessage(obj: HMR_ACTION_TYPES) {
if (!('action' in obj)) {
return
}
// eslint-disable-next-line default-case
switch (obj.action) {
case HMR_ACTIONS_SENT_TO_BROWSER.BUILDING:
show()
break
case HMR_ACTIONS_SENT_TO_BROWSER.BUILT:
case HMR_ACTIONS_SENT_TO_BROWSER.SYNC:
hide()
break
}
}
toggleCallback({
show,
hide,
})
function updateContainer() { function updateContainer() {
if (isBuilding) { if (isBuilding) {
container.classList.add(`${prefix}building`) container.classList.add(`${prefix}building`)
......
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 initializeBuildWatcher from './dev/dev-build-watcher' import { devBuildIndicator } from './dev/dev-build-indicator/internal/dev-build-indicator'
import type { ShowHideHandler } from './dev/dev-build-watcher'
import { displayContent } from './dev/fouc' import { displayContent } from './dev/fouc'
import { import {
connectHMR, connectHMR,
...@@ -15,6 +14,7 @@ import { HMR_ACTIONS_SENT_TO_BROWSER } from '../server/dev/hot-reloader-types' ...@@ -15,6 +14,7 @@ import { HMR_ACTIONS_SENT_TO_BROWSER } from '../server/dev/hot-reloader-types'
import { RuntimeErrorHandler } from './components/react-dev-overlay/internal/helpers/runtime-error-handler' import { RuntimeErrorHandler } from './components/react-dev-overlay/internal/helpers/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'
export function pageBootstrap(assetPrefix: string) { export function pageBootstrap(assetPrefix: string) {
connectHMR({ assetPrefix, path: '/_next/webpack-hmr' }) connectHMR({ assetPrefix, path: '/_next/webpack-hmr' })
...@@ -22,13 +22,7 @@ export function pageBootstrap(assetPrefix: string) { ...@@ -22,13 +22,7 @@ export function pageBootstrap(assetPrefix: string) {
return hydrate({ beforeRender: displayContent }).then(() => { return hydrate({ beforeRender: displayContent }).then(() => {
initOnDemandEntries() initOnDemandEntries()
let buildIndicatorHandler: ShowHideHandler | undefined initializeDevBuildIndicatorForPageRouter()
if (process.env.__NEXT_BUILD_INDICATOR) {
initializeBuildWatcher((handler) => {
buildIndicatorHandler = handler
}, process.env.__NEXT_BUILD_INDICATOR_POSITION)
}
let reloading = false let reloading = false
...@@ -98,10 +92,8 @@ export function pageBootstrap(assetPrefix: string) { ...@@ -98,10 +92,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()
buildIndicatorHandler?.show() const clearIndicator = () => devBuildIndicator.hide()
const clearIndicator = () => buildIndicatorHandler?.hide()
router router
.replace( .replace(
......
...@@ -14,7 +14,7 @@ import { NextInstance } from 'e2e-utils' ...@@ -14,7 +14,7 @@ import { NextInstance } from 'e2e-utils'
const installCheckVisible = (browser) => { const installCheckVisible = (browser) => {
return browser.eval(`(function() { return browser.eval(`(function() {
window.checkInterval = setInterval(function() { window.checkInterval = setInterval(function() {
let watcherDiv = document.querySelector('#__next-build-watcher') let watcherDiv = document.querySelector('#__next-build-indicator')
watcherDiv = watcherDiv.shadowRoot || watcherDiv watcherDiv = watcherDiv.shadowRoot || watcherDiv
window.showedBuilder = window.showedBuilder || ( window.showedBuilder = window.showedBuilder || (
watcherDiv.querySelector('div').className.indexOf('visible') > -1 watcherDiv.querySelector('div').className.indexOf('visible') > -1
......
...@@ -14,7 +14,7 @@ let app ...@@ -14,7 +14,7 @@ let app
const installCheckVisible = (browser) => { const installCheckVisible = (browser) => {
return browser.eval(`(function() { return browser.eval(`(function() {
window.checkInterval = setInterval(function() { window.checkInterval = setInterval(function() {
let watcherDiv = document.querySelector('#__next-build-watcher') let watcherDiv = document.querySelector('#__next-build-indicator')
watcherDiv = watcherDiv.shadowRoot || watcherDiv watcherDiv = watcherDiv.shadowRoot || watcherDiv
window.showedBuilder = window.showedBuilder || ( window.showedBuilder = window.showedBuilder || (
watcherDiv.querySelector('div').className.indexOf('visible') > -1 watcherDiv.querySelector('div').className.indexOf('visible') > -1
...@@ -70,7 +70,7 @@ describe('Build Activity Indicator', () => { ...@@ -70,7 +70,7 @@ describe('Build Activity Indicator', () => {
it('Adds the build indicator container', async () => { it('Adds the build indicator container', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
const html = await browser.eval('document.body.innerHTML') const html = await browser.eval('document.body.innerHTML')
expect(html).toMatch(/__next-build-watcher/) expect(html).toMatch(/__next-build-indicator/)
await browser.close() await browser.close()
}) })
;(process.env.TURBOPACK ? describe.skip : describe)('webpack only', () => { ;(process.env.TURBOPACK ? describe.skip : describe)('webpack only', () => {
...@@ -120,7 +120,7 @@ describe('Build Activity Indicator', () => { ...@@ -120,7 +120,7 @@ describe('Build Activity Indicator', () => {
it('Does not add the build indicator container', async () => { it('Does not add the build indicator container', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
const html = await browser.eval('document.body.innerHTML') const html = await browser.eval('document.body.innerHTML')
expect(html).not.toMatch(/__next-build-watcher/) expect(html).not.toMatch(/__next-build-indicator/)
await browser.close() await browser.close()
}) })
}) })
......
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