Unverified Commit 1c9e8af8 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

[dev-overlay] hide dev indicator for server session or 1 day (#76430)

### Why?

When users want to hide the dev indicator, they might be frustrated if
it reappears every reload. Hence, make a default to hide it for the
current server session or a day.

Closes NDX-890

---------
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
parent 00f56aa2
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
ACTION_BUILD_ERROR, ACTION_BUILD_ERROR,
ACTION_BUILD_OK, ACTION_BUILD_OK,
ACTION_DEBUG_INFO, ACTION_DEBUG_INFO,
ACTION_DEV_INDICATOR,
ACTION_REFRESH, ACTION_REFRESH,
ACTION_STATIC_INDICATOR, ACTION_STATIC_INDICATOR,
ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_ERROR,
...@@ -48,6 +49,7 @@ import { getReactStitchedError } from '../../errors/stitched-error' ...@@ -48,6 +49,7 @@ import { getReactStitchedError } from '../../errors/stitched-error'
import { shouldRenderRootLevelErrorOverlay } from '../../../lib/is-error-thrown-while-rendering-rsc' import { shouldRenderRootLevelErrorOverlay } from '../../../lib/is-error-thrown-while-rendering-rsc'
import { handleDevBuildIndicatorHmrEvents } from '../../../dev/dev-build-indicator/internal/handle-dev-build-indicator-hmr-events' import { handleDevBuildIndicatorHmrEvents } from '../../../dev/dev-build-indicator/internal/handle-dev-build-indicator-hmr-events'
import type { GlobalErrorComponent } from '../../error-boundary' import type { GlobalErrorComponent } from '../../error-boundary'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
export interface Dispatcher { export interface Dispatcher {
onBuildOk(): void onBuildOk(): void
...@@ -57,6 +59,7 @@ export interface Dispatcher { ...@@ -57,6 +59,7 @@ export interface Dispatcher {
onBeforeRefresh(): void onBeforeRefresh(): void
onRefresh(): void onRefresh(): void
onStaticIndicator(status: boolean): void onStaticIndicator(status: boolean): void
onDevIndicator(devIndicator: DevIndicatorServerState): void
} }
let mostRecentCompilationHash: any = null let mostRecentCompilationHash: any = null
...@@ -379,6 +382,7 @@ function processMessage( ...@@ -379,6 +382,7 @@ function processMessage(
// Is undefined when it's a 'built' event // Is undefined when it's a 'built' event
if ('versionInfo' in obj) dispatcher.onVersionInfo(obj.versionInfo) if ('versionInfo' in obj) dispatcher.onVersionInfo(obj.versionInfo)
if ('debug' in obj && obj.debug) dispatcher.onDebugInfo(obj.debug) if ('debug' in obj && obj.debug) dispatcher.onDebugInfo(obj.debug)
if ('devIndicator' in obj) dispatcher.onDevIndicator(obj.devIndicator)
const hasErrors = Boolean(errors && errors.length) const hasErrors = Boolean(errors && errors.length)
// Compilation with errors (e.g. syntax error or missing modules). // Compilation with errors (e.g. syntax error or missing modules).
...@@ -566,6 +570,12 @@ export default function HotReload({ ...@@ -566,6 +570,12 @@ export default function HotReload({
onDebugInfo(debugInfo) { onDebugInfo(debugInfo) {
dispatch({ type: ACTION_DEBUG_INFO, debugInfo }) dispatch({ type: ACTION_DEBUG_INFO, debugInfo })
}, },
onDevIndicator(devIndicator) {
dispatch({
type: ACTION_DEV_INDICATOR,
devIndicator,
})
},
} }
}, [dispatch]) }, [dispatch])
......
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
ACTION_BEFORE_REFRESH, ACTION_BEFORE_REFRESH,
ACTION_BUILD_ERROR, ACTION_BUILD_ERROR,
ACTION_BUILD_OK, ACTION_BUILD_OK,
ACTION_DEV_INDICATOR,
ACTION_REFRESH, ACTION_REFRESH,
ACTION_STATIC_INDICATOR, ACTION_STATIC_INDICATOR,
ACTION_UNHANDLED_ERROR, ACTION_UNHANDLED_ERROR,
...@@ -17,6 +18,7 @@ import { ...@@ -17,6 +18,7 @@ import {
} from '../shared' } from '../shared'
import type { VersionInfo } from '../../../../server/dev/parse-version-info' import type { VersionInfo } from '../../../../server/dev/parse-version-info'
import { attachHydrationErrorState } from '../../errors/attach-hydration-error-state' import { attachHydrationErrorState } from '../../errors/attach-hydration-error-state'
import type { DevIndicatorServerState } from '../../../../server/dev/dev-indicator-server-state'
let isRegistered = false let isRegistered = false
let stackTraceLimit: number | undefined = undefined let stackTraceLimit: number | undefined = undefined
...@@ -143,5 +145,9 @@ export function onStaticIndicator(isStatic: boolean) { ...@@ -143,5 +145,9 @@ export function onStaticIndicator(isStatic: boolean) {
Bus.emit({ type: ACTION_STATIC_INDICATOR, staticIndicator: isStatic }) Bus.emit({ type: ACTION_STATIC_INDICATOR, staticIndicator: isStatic })
} }
export function onDevIndicator(devIndicatorsState: DevIndicatorServerState) {
Bus.emit({ type: ACTION_DEV_INDICATOR, devIndicator: devIndicatorsState })
}
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'
...@@ -36,6 +36,7 @@ import { ...@@ -36,6 +36,7 @@ import {
onRefresh, onRefresh,
onVersionInfo, onVersionInfo,
onStaticIndicator, onStaticIndicator,
onDevIndicator,
} 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'
...@@ -318,6 +319,7 @@ function processMessage(obj: HMR_ACTION_TYPES) { ...@@ -318,6 +319,7 @@ function processMessage(obj: HMR_ACTION_TYPES) {
// Is undefined when it's a 'built' event // Is undefined when it's a 'built' event
if ('versionInfo' in obj) onVersionInfo(obj.versionInfo) if ('versionInfo' in obj) onVersionInfo(obj.versionInfo)
if ('devIndicator' in obj) onDevIndicator(obj.devIndicator)
const hasErrors = Boolean(errors && errors.length) const hasErrors = Boolean(errors && errors.length)
if (hasErrors) { if (hasErrors) {
......
...@@ -6,13 +6,17 @@ export const middlewareResponse = { ...@@ -6,13 +6,17 @@ export const middlewareResponse = {
res.statusCode = 204 res.statusCode = 204
res.end('No Content') res.end('No Content')
}, },
badRequest(res: ServerResponse) {
res.statusCode = 400
res.end('Bad Request')
},
notFound(res: ServerResponse) { notFound(res: ServerResponse) {
res.statusCode = 404 res.statusCode = 404
res.end('Not Found') res.end('Not Found')
}, },
badRequest(res: ServerResponse) { methodNotAllowed(res: ServerResponse) {
res.statusCode = 400 res.statusCode = 405
res.end('Bad Request') res.end('Method Not Allowed')
}, },
internalServerError(res: ServerResponse, error?: unknown) { internalServerError(res: ServerResponse, error?: unknown) {
res.statusCode = 500 res.statusCode = 500
......
...@@ -5,6 +5,7 @@ import type { VersionInfo } from '../../../server/dev/parse-version-info' ...@@ -5,6 +5,7 @@ import type { VersionInfo } from '../../../server/dev/parse-version-info'
import type { SupportedErrorEvent } from './ui/container/runtime-error/render-error' import type { SupportedErrorEvent } from './ui/container/runtime-error/render-error'
import type { ComponentStackFrame } from './utils/parse-component-stack' import type { ComponentStackFrame } from './utils/parse-component-stack'
import type { DebugInfo } from './types' import type { DebugInfo } from './types'
import type { DevIndicatorServerState } from '../../../server/dev/dev-indicator-server-state'
type FastRefreshState = type FastRefreshState =
/** No refresh in progress. */ /** No refresh in progress. */
...@@ -35,6 +36,7 @@ export const ACTION_VERSION_INFO = 'version-info' ...@@ -35,6 +36,7 @@ export const ACTION_VERSION_INFO = 'version-info'
export const ACTION_UNHANDLED_ERROR = 'unhandled-error' export const ACTION_UNHANDLED_ERROR = 'unhandled-error'
export const ACTION_UNHANDLED_REJECTION = 'unhandled-rejection' export const ACTION_UNHANDLED_REJECTION = 'unhandled-rejection'
export const ACTION_DEBUG_INFO = 'debug-info' export const ACTION_DEBUG_INFO = 'debug-info'
export const ACTION_DEV_INDICATOR = 'dev-indicator'
interface StaticIndicatorAction { interface StaticIndicatorAction {
type: typeof ACTION_STATIC_INDICATOR type: typeof ACTION_STATIC_INDICATOR
...@@ -78,6 +80,11 @@ interface VersionInfoAction { ...@@ -78,6 +80,11 @@ interface VersionInfoAction {
versionInfo: VersionInfo versionInfo: VersionInfo
} }
interface DevIndicatorAction {
type: typeof ACTION_DEV_INDICATOR
devIndicator: DevIndicatorServerState
}
export type BusEvent = export type BusEvent =
| BuildOkAction | BuildOkAction
| BuildErrorAction | BuildErrorAction
...@@ -88,6 +95,7 @@ export type BusEvent = ...@@ -88,6 +95,7 @@ export type BusEvent =
| VersionInfoAction | VersionInfoAction
| StaticIndicatorAction | StaticIndicatorAction
| DebugInfoAction | DebugInfoAction
| DevIndicatorAction
function pushErrorFilterDuplicates( function pushErrorFilterDuplicates(
errors: SupportedErrorEvent[], errors: SupportedErrorEvent[],
...@@ -102,13 +110,17 @@ function pushErrorFilterDuplicates( ...@@ -102,13 +110,17 @@ function pushErrorFilterDuplicates(
] ]
} }
const shouldDisableDevIndicator =
process.env.__NEXT_DEV_INDICATOR?.toString() === 'false'
export const INITIAL_OVERLAY_STATE: Omit<OverlayState, 'routerType'> = { export const INITIAL_OVERLAY_STATE: Omit<OverlayState, 'routerType'> = {
nextId: 1, nextId: 1,
buildError: null, buildError: null,
errors: [], errors: [],
notFound: false, notFound: false,
staticIndicator: false, staticIndicator: false,
disableDevIndicator: process.env.__NEXT_DEV_INDICATOR?.toString() === 'false', // To prevent flickering, set the initial state to disabled.
disableDevIndicator: true,
refreshState: { type: 'idle' }, refreshState: { type: 'idle' },
rootLayoutMissingTags: [], rootLayoutMissingTags: [],
versionInfo: { installed: '0.0.0', staleness: 'unknown' }, versionInfo: { installed: '0.0.0', staleness: 'unknown' },
...@@ -194,6 +206,13 @@ export function useErrorOverlayReducer(routerType: 'pages' | 'app') { ...@@ -194,6 +206,13 @@ export function useErrorOverlayReducer(routerType: 'pages' | 'app') {
case ACTION_VERSION_INFO: { case ACTION_VERSION_INFO: {
return { ..._state, versionInfo: action.versionInfo } return { ..._state, versionInfo: action.versionInfo }
} }
case ACTION_DEV_INDICATOR: {
return {
..._state,
disableDevIndicator:
shouldDisableDevIndicator || !!action.devIndicator.disabledUntil,
}
}
default: { default: {
return _state return _state
} }
......
...@@ -47,6 +47,9 @@ export function DevToolsIndicator({ ...@@ -47,6 +47,9 @@ export function DevToolsIndicator({
isStaticRoute={state.staticIndicator} isStaticRoute={state.staticIndicator}
hide={() => { hide={() => {
setIsDevToolsIndicatorVisible(false) setIsDevToolsIndicatorVisible(false)
fetch('/__nextjs_disable_dev_indicator', {
method: 'POST',
})
}} }}
setIsErrorOverlayOpen={setIsErrorOverlayOpen} setIsErrorOverlayOpen={setIsErrorOverlayOpen}
isTurbopack={!!process.env.TURBOPACK} isTurbopack={!!process.env.TURBOPACK}
...@@ -380,7 +383,7 @@ function DevToolsPopover({ ...@@ -380,7 +383,7 @@ function DevToolsPopover({
<MenuItem <MenuItem
data-hide-dev-tools data-hide-dev-tools
title="Hide Dev Tools for the current server session or a day." title="Hide Dev Tools for the current server session or a day."
label="Hide Dev Tools" label="Hide for Dev Session"
value={<StopIcon />} value={<StopIcon />}
onClick={hide} onClick={hide}
index={isTurbopack ? 2 : 3} index={isTurbopack ? 2 : 3}
......
import type { ServerResponse, IncomingMessage } from 'http'
import { middlewareResponse } from '../../client/components/react-dev-overlay/server/middleware-response'
import * as Log from '../../build/output/log'
import { devIndicatorServerState } from './dev-indicator-server-state'
const DISABLE_DEV_INDICATOR_PREFIX = '/__nextjs_disable_dev_indicator'
const COOLDOWN_TIME_MS = process.env.__NEXT_DEV_INDICATOR_COOLDOWN_MS
? parseInt(process.env.__NEXT_DEV_INDICATOR_COOLDOWN_MS)
: // 1 day from now
1000 * 60 * 60 * 24
export function getDisableDevIndicatorMiddleware() {
return async function disableDevIndicatorMiddleware(
req: IncomingMessage,
res: ServerResponse,
next: () => void
): Promise<void> {
try {
const { pathname } = new URL(`http://n${req.url}`)
if (!pathname.startsWith(DISABLE_DEV_INDICATOR_PREFIX)) {
return next()
}
if (req.method !== 'POST') {
return middlewareResponse.methodNotAllowed(res)
}
devIndicatorServerState.disabledUntil = Date.now() + COOLDOWN_TIME_MS
return middlewareResponse.noContent(res)
} catch (err) {
Log.error(
'Failed to disable the dev indicator:',
err instanceof Error ? err.message : err
)
return middlewareResponse.internalServerError(res)
}
}
}
export type DevIndicatorServerState = typeof devIndicatorServerState
export const devIndicatorServerState = {
disabledUntil: 0,
}
...@@ -27,6 +27,7 @@ import { isMiddlewareFilename } from '../../build/utils' ...@@ -27,6 +27,7 @@ import { isMiddlewareFilename } from '../../build/utils'
import type { VersionInfo } from './parse-version-info' import type { VersionInfo } from './parse-version-info'
import type { HMR_ACTION_TYPES } from './hot-reloader-types' import type { HMR_ACTION_TYPES } from './hot-reloader-types'
import { HMR_ACTIONS_SENT_TO_BROWSER } from './hot-reloader-types' import { HMR_ACTIONS_SENT_TO_BROWSER } from './hot-reloader-types'
import { devIndicatorServerState } from './dev-indicator-server-state'
function isMiddlewareStats(stats: webpack.Stats) { function isMiddlewareStats(stats: webpack.Stats) {
for (const key of stats.compilation.entrypoints.keys()) { for (const key of stats.compilation.entrypoints.keys()) {
...@@ -202,6 +203,10 @@ export class WebpackHotMiddleware { ...@@ -202,6 +203,10 @@ export class WebpackHotMiddleware {
const stats = statsToJson(syncStats) const stats = statsToJson(syncStats)
const middlewareStats = statsToJson(this.middlewareLatestStats?.stats) const middlewareStats = statsToJson(this.middlewareLatestStats?.stats)
if (devIndicatorServerState.disabledUntil < Date.now()) {
devIndicatorServerState.disabledUntil = 0
}
this.publish({ this.publish({
action: HMR_ACTIONS_SENT_TO_BROWSER.SYNC, action: HMR_ACTIONS_SENT_TO_BROWSER.SYNC,
hash: stats.hash!, hash: stats.hash!,
...@@ -214,6 +219,7 @@ export class WebpackHotMiddleware { ...@@ -214,6 +219,7 @@ export class WebpackHotMiddleware {
debug: { debug: {
devtoolsFrontendUrl: this.devtoolsFrontendUrl, devtoolsFrontendUrl: this.devtoolsFrontendUrl,
}, },
devIndicator: devIndicatorServerState,
}) })
} }
} }
......
...@@ -95,6 +95,8 @@ import { ...@@ -95,6 +95,8 @@ import {
type TopLevelIssuesMap, type TopLevelIssuesMap,
} from '../../shared/lib/turbopack/utils' } from '../../shared/lib/turbopack/utils'
import { getDevOverlayFontMiddleware } from '../../client/components/react-dev-overlay/font/get-dev-overlay-font-middleware' import { getDevOverlayFontMiddleware } from '../../client/components/react-dev-overlay/font/get-dev-overlay-font-middleware'
import { devIndicatorServerState } from './dev-indicator-server-state'
import { getDisableDevIndicatorMiddleware } from './dev-indicator-middleware'
// import { getSupportedBrowsers } from '../../build/utils' // import { getSupportedBrowsers } from '../../build/utils'
const wsServer = new ws.Server({ noServer: true }) const wsServer = new ws.Server({ noServer: true })
...@@ -636,6 +638,7 @@ export async function createHotReloaderTurbopack( ...@@ -636,6 +638,7 @@ export async function createHotReloaderTurbopack(
getSourceMapMiddleware(project), getSourceMapMiddleware(project),
getNextErrorFeedbackMiddleware(opts.telemetry), getNextErrorFeedbackMiddleware(opts.telemetry),
getDevOverlayFontMiddleware(), getDevOverlayFontMiddleware(),
getDisableDevIndicatorMiddleware(),
] ]
const versionInfoPromise = getVersionInfo() const versionInfoPromise = getVersionInfo()
...@@ -824,6 +827,10 @@ export async function createHotReloaderTurbopack( ...@@ -824,6 +827,10 @@ export async function createHotReloaderTurbopack(
} }
} }
if (devIndicatorServerState.disabledUntil < Date.now()) {
devIndicatorServerState.disabledUntil = 0
}
;(async function () { ;(async function () {
const versionInfo = await versionInfoPromise const versionInfo = await versionInfoPromise
...@@ -836,6 +843,7 @@ export async function createHotReloaderTurbopack( ...@@ -836,6 +843,7 @@ export async function createHotReloaderTurbopack(
debug: { debug: {
devtoolsFrontendUrl, devtoolsFrontendUrl,
}, },
devIndicator: devIndicatorServerState,
} }
sendToClient(client, sync) sendToClient(client, sync)
......
...@@ -7,6 +7,7 @@ import type { RouteDefinition } from '../route-definitions/route-definition' ...@@ -7,6 +7,7 @@ import type { RouteDefinition } from '../route-definitions/route-definition'
import type { Project, Update as TurbopackUpdate } from '../../build/swc/types' import type { Project, Update as TurbopackUpdate } from '../../build/swc/types'
import type { VersionInfo } from './parse-version-info' import type { VersionInfo } from './parse-version-info'
import type { DebugInfo } from '../../client/components/react-dev-overlay/types' import type { DebugInfo } from '../../client/components/react-dev-overlay/types'
import type { DevIndicatorServerState } from './dev-indicator-server-state'
export const enum HMR_ACTIONS_SENT_TO_BROWSER { export const enum HMR_ACTIONS_SENT_TO_BROWSER {
ADDED_PAGE = 'addedPage', ADDED_PAGE = 'addedPage',
...@@ -24,6 +25,7 @@ export const enum HMR_ACTIONS_SENT_TO_BROWSER { ...@@ -24,6 +25,7 @@ export const enum HMR_ACTIONS_SENT_TO_BROWSER {
SERVER_ERROR = 'serverError', SERVER_ERROR = 'serverError',
TURBOPACK_CONNECTED = 'turbopack-connected', TURBOPACK_CONNECTED = 'turbopack-connected',
ISR_MANIFEST = 'isrManifest', ISR_MANIFEST = 'isrManifest',
DEV_INDICATOR = 'devIndicator',
} }
interface ServerErrorAction { interface ServerErrorAction {
...@@ -55,6 +57,7 @@ export interface SyncAction { ...@@ -55,6 +57,7 @@ export interface SyncAction {
versionInfo: VersionInfo versionInfo: VersionInfo
updatedModules?: ReadonlyArray<string> updatedModules?: ReadonlyArray<string>
debug?: DebugInfo debug?: DebugInfo
devIndicator: DevIndicatorServerState
} }
interface BuiltAction { interface BuiltAction {
action: HMR_ACTIONS_SENT_TO_BROWSER.BUILT action: HMR_ACTIONS_SENT_TO_BROWSER.BUILT
...@@ -116,6 +119,11 @@ export interface AppIsrManifestAction { ...@@ -116,6 +119,11 @@ export interface AppIsrManifestAction {
data: Record<string, boolean> data: Record<string, boolean>
} }
export interface DevIndicatorAction {
action: HMR_ACTIONS_SENT_TO_BROWSER.DEV_INDICATOR
devIndicator: DevIndicatorServerState
}
export type HMR_ACTION_TYPES = export type HMR_ACTION_TYPES =
| TurbopackMessageAction | TurbopackMessageAction
| TurbopackConnectedAction | TurbopackConnectedAction
...@@ -132,6 +140,7 @@ export type HMR_ACTION_TYPES = ...@@ -132,6 +140,7 @@ export type HMR_ACTION_TYPES =
| DevPagesManifestUpdateAction | DevPagesManifestUpdateAction
| ServerErrorAction | ServerErrorAction
| AppIsrManifestAction | AppIsrManifestAction
| DevIndicatorAction
export type TurbopackMsgToBrowser = export type TurbopackMsgToBrowser =
| { type: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE; data: any } | { type: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE; data: any }
......
...@@ -85,6 +85,7 @@ import { FAST_REFRESH_RUNTIME_RELOAD } from './messages' ...@@ -85,6 +85,7 @@ import { FAST_REFRESH_RUNTIME_RELOAD } from './messages'
import { getNodeDebugType } from '../lib/utils' import { getNodeDebugType } from '../lib/utils'
import { getNextErrorFeedbackMiddleware } from '../../client/components/react-dev-overlay/server/get-next-error-feedback-middleware' import { getNextErrorFeedbackMiddleware } from '../../client/components/react-dev-overlay/server/get-next-error-feedback-middleware'
import { getDevOverlayFontMiddleware } from '../../client/components/react-dev-overlay/font/get-dev-overlay-font-middleware' import { getDevOverlayFontMiddleware } from '../../client/components/react-dev-overlay/font/get-dev-overlay-font-middleware'
import { getDisableDevIndicatorMiddleware } from './dev-indicator-middleware'
const MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000) const MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000)
...@@ -1549,6 +1550,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1549,6 +1550,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
}), }),
getNextErrorFeedbackMiddleware(this.telemetry), getNextErrorFeedbackMiddleware(this.telemetry),
getDevOverlayFontMiddleware(), getDevOverlayFontMiddleware(),
getDisableDevIndicatorMiddleware(),
] ]
} }
......
import { nextTestSetup } from 'e2e-utils'
import {
assertHasDevToolsIndicator,
assertNoDevToolsIndicator,
openDevToolsIndicatorPopover,
waitFor,
} from 'next-test-utils'
const COOLDOWN = 3000
describe('dev indicator - Hide DevTools Button', () => {
const { next } = nextTestSetup({
files: __dirname,
env: {
__NEXT_DEV_INDICATOR_COOLDOWN_MS: `${COOLDOWN}`,
},
})
it('should show the dev indicator when the server is manually restarted', async () => {
const browser = await next.browser('/')
await openDevToolsIndicatorPopover(browser)
await browser.elementByCss('[data-hide-dev-tools]').click()
await assertNoDevToolsIndicator(browser)
await next.stop()
await next.start()
const browser2 = await next.browser('/')
await browser2.refresh()
await assertHasDevToolsIndicator(browser2)
})
it('should still hide the dev indicator after reloading the page', async () => {
const browser = await next.browser('/')
await openDevToolsIndicatorPopover(browser)
await browser.elementByCss('[data-hide-dev-tools]').click()
await assertNoDevToolsIndicator(browser)
await browser.refresh()
// Still hidden after reload
await assertNoDevToolsIndicator(browser)
})
it('should show the dev indicator after cooldown period has passed', async () => {
await next.stop()
await next.start()
const browser = await next.browser('/')
await openDevToolsIndicatorPopover(browser)
await browser.elementByCss('[data-hide-dev-tools]').click()
await assertNoDevToolsIndicator(browser)
// Wait for `__NEXT_DEV_INDICATOR_COOLDOWN` to pass.
await waitFor(COOLDOWN)
await browser.refresh()
await assertHasDevToolsIndicator(browser)
})
})
...@@ -13,6 +13,11 @@ describe('client-dev-overlay', () => { ...@@ -13,6 +13,11 @@ describe('client-dev-overlay', () => {
files: { files: {
pages: new FileRef(join(__dirname, 'app/pages')), pages: new FileRef(join(__dirname, 'app/pages')),
}, },
env: {
// Disable the cooldown period for the dev indicator so that hiding the indicator in a test doesn't
// impact subsequent tests.
__NEXT_DEV_INDICATOR_COOLDOWN_MS: '0',
},
}) })
}) })
beforeEach(async () => { beforeEach(async () => {
......
...@@ -523,4 +523,8 @@ export class Playwright extends BrowserInterface { ...@@ -523,4 +523,8 @@ export class Playwright extends BrowserInterface {
'nextjs-portal [aria-labelledby="nextjs__container_errors_label"]' 'nextjs-portal [aria-labelledby="nextjs__container_errors_label"]'
) )
} }
locateDevToolsIndicator(): Locator {
return page.locator('nextjs-portal [data-nextjs-dev-tools-button]')
}
} }
...@@ -958,8 +958,10 @@ export async function goToNextErrorView( ...@@ -958,8 +958,10 @@ export async function goToNextErrorView(
export async function openDevToolsIndicatorPopover( export async function openDevToolsIndicatorPopover(
browser: BrowserInterface browser: BrowserInterface
): Promise<void> { ): Promise<void> {
const devToolsIndicator = await assertHasDevToolsIndicator(browser)
try { try {
await browser.waitForElementByCss('[data-nextjs-dev-tools-button]').click() await devToolsIndicator.click()
} catch (cause) { } catch (cause) {
const error = new Error('No DevTools Indicator to open.', { cause }) const error = new Error('No DevTools Indicator to open.', { cause })
Error.captureStackTrace(error, openDevToolsIndicatorPopover) Error.captureStackTrace(error, openDevToolsIndicatorPopover)
...@@ -967,6 +969,39 @@ export async function openDevToolsIndicatorPopover( ...@@ -967,6 +969,39 @@ export async function openDevToolsIndicatorPopover(
} }
} }
export async function assertHasDevToolsIndicator(browser: BrowserInterface) {
// TODO: Implement for other BrowserInterface implementations
const playwright = browser as Playwright
const devToolsIndicator = playwright.locateDevToolsIndicator()
try {
await devToolsIndicator.waitFor({ timeout: 5000 })
} catch (errorCause) {
const error = new Error(
'Expected DevTools Indicator but found no visible one.'
)
Error.captureStackTrace(error, assertHasDevToolsIndicator)
throw error
}
return devToolsIndicator
}
export async function assertNoDevToolsIndicator(browser: BrowserInterface) {
// TODO: Implement for other BrowserInterface implementations
const playwright = browser as Playwright
const devToolsIndicator = playwright.locateDevToolsIndicator()
if (await devToolsIndicator.isVisible()) {
const error = new Error(
'Expected no visible DevTools Indicator but found one.'
)
Error.captureStackTrace(error, assertNoDevToolsIndicator)
throw error
}
}
export async function getRouteTypeFromDevToolsIndicator( export async function getRouteTypeFromDevToolsIndicator(
browser: BrowserInterface browser: BrowserInterface
): Promise<'Static' | 'Dynamic'> { ): Promise<'Static' | 'Dynamic'> {
......
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