Unverified Commit 2ff660c2 authored by Hannes Bornö's avatar Hannes Bornö Committed by GitHub

Remove full reload overlay and warn in CLI instead (#37874)

- Always perform a full reload when needed without blocking with the overlay.
- Old client warnings re-added.
- Post client warning to dev server and print it in the CLI. 


## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The examples guidelines are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing.md#adding-examples)
parent ee895178
...@@ -31,7 +31,6 @@ import { ...@@ -31,7 +31,6 @@ import {
onBuildError, onBuildError,
onBuildOk, onBuildOk,
onRefresh, onRefresh,
onFullRefreshNeeded,
} from 'next/dist/compiled/@next/react-dev-overlay/dist/client' } from 'next/dist/compiled/@next/react-dev-overlay/dist/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'
...@@ -314,15 +313,23 @@ function tryApplyUpdates(onHotUpdateSuccess) { ...@@ -314,15 +313,23 @@ function tryApplyUpdates(onHotUpdateSuccess) {
function handleApplyUpdates(err, updatedModules) { function handleApplyUpdates(err, updatedModules) {
if (err || hadRuntimeError || !updatedModules) { if (err || hadRuntimeError || !updatedModules) {
if (err) { if (err) {
performFullRefresh(err) console.warn(
'[Fast Refresh] performing full reload\n\n' +
"Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.\n" +
'You might have a file which exports a React component but also exports a value that is imported by a non-React component file.\n' +
'Consider migrating the non-React component export to a separate file and importing it into both files.\n\n' +
'It is also possible the parent component of the component you edited is a class component, which disables Fast Refresh.\n' +
'Fast Refresh requires at least one parent function component in your React tree.'
)
} else if (hadRuntimeError) { } else if (hadRuntimeError) {
performFullRefresh() console.warn(
'[Fast Refresh] performing full reload because your application had an unrecoverable error'
)
} }
performFullReload(err)
return return
} }
clearFullRefreshStorage()
const hasUpdates = Boolean(updatedModules.length) const hasUpdates = Boolean(updatedModules.length)
if (typeof onHotUpdateSuccess === 'function') { if (typeof onHotUpdateSuccess === 'function') {
// Maybe we want to do something. // Maybe we want to do something.
...@@ -356,27 +363,19 @@ function tryApplyUpdates(onHotUpdateSuccess) { ...@@ -356,27 +363,19 @@ function tryApplyUpdates(onHotUpdateSuccess) {
) )
} }
const FULL_REFRESH_STORAGE_KEY = '_has_warned_about_full_refresh' function performFullReload(err) {
const stackTrace =
function performFullRefresh(err) { err &&
if (!hasAlreadyWarnedAboutFullRefresh()) { ((err.stack && err.stack.split('\n').slice(0, 5).join('\n')) ||
sessionStorage.setItem(FULL_REFRESH_STORAGE_KEY, 'true') err.message ||
const reason = err + '')
err &&
((err.stack && err.stack.split('\n').slice(0, 5).join('\n')) || sendMessage(
err.message || JSON.stringify({
err + '') event: 'client-full-reload',
onFullRefreshNeeded(reason) stackTrace,
} else { })
window.location.reload() )
}
}
function hasAlreadyWarnedAboutFullRefresh() {
return sessionStorage.getItem(FULL_REFRESH_STORAGE_KEY) !== null
}
function clearFullRefreshStorage() { window.location.reload()
if (sessionStorage.getItem(FULL_REFRESH_STORAGE_KEY) !== 'ignore')
sessionStorage.removeItem(FULL_REFRESH_STORAGE_KEY)
} }
...@@ -15,6 +15,7 @@ import { ...@@ -15,6 +15,7 @@ import {
runDependingOnPageType, runDependingOnPageType,
} from '../../build/entries' } from '../../build/entries'
import { watchCompilers } from '../../build/output' import { watchCompilers } from '../../build/output'
import * as Log from '../../build/output/log'
import getBaseWebpackConfig from '../../build/webpack-config' import getBaseWebpackConfig from '../../build/webpack-config'
import { API_ROUTE, APP_DIR_ALIAS } from '../../lib/constants' import { API_ROUTE, APP_DIR_ALIAS } from '../../lib/constants'
import { recursiveDelete } from '../../lib/recursive-delete' import { recursiveDelete } from '../../lib/recursive-delete'
...@@ -351,6 +352,15 @@ export default class HotReloader { ...@@ -351,6 +352,15 @@ export default class HotReloader {
} }
break break
} }
case 'client-full-reload': {
Log.warn(
'Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works'
)
if (payload.stackTrace) {
console.warn(payload.stackTrace)
}
break
}
default: { default: {
break break
} }
......
...@@ -85,10 +85,6 @@ function onBuildError(message: string) { ...@@ -85,10 +85,6 @@ function onBuildError(message: string) {
Bus.emit({ type: Bus.TYPE_BUILD_ERROR, message }) Bus.emit({ type: Bus.TYPE_BUILD_ERROR, message })
} }
function onFullRefreshNeeded(reason?: string) {
Bus.emit({ type: Bus.TYPE_FULL_REFRESH_NEEDED, reason: reason ?? null })
}
function onRefresh() { function onRefresh() {
Bus.emit({ type: Bus.TYPE_REFRESH }) Bus.emit({ type: Bus.TYPE_REFRESH })
} }
...@@ -96,11 +92,4 @@ function onRefresh() { ...@@ -96,11 +92,4 @@ function onRefresh() {
export { getErrorByType } from './internal/helpers/getErrorByType' export { getErrorByType } from './internal/helpers/getErrorByType'
export { getServerError } from './internal/helpers/nodeStackFrames' export { getServerError } from './internal/helpers/nodeStackFrames'
export { default as ReactDevOverlay } from './internal/ReactDevOverlay' export { default as ReactDevOverlay } from './internal/ReactDevOverlay'
export { export { onBuildOk, onBuildError, register, unregister, onRefresh }
onBuildOk,
onBuildError,
onFullRefreshNeeded,
register,
unregister,
onRefresh,
}
...@@ -4,7 +4,6 @@ import * as Bus from './bus' ...@@ -4,7 +4,6 @@ import * as Bus from './bus'
import { ShadowPortal } from './components/ShadowPortal' import { ShadowPortal } from './components/ShadowPortal'
import { BuildError } from './container/BuildError' import { BuildError } from './container/BuildError'
import { Errors, SupportedErrorEvent } from './container/Errors' import { Errors, SupportedErrorEvent } from './container/Errors'
import { FullRefreshWarning } from './container/FullRefreshWarning'
import { ErrorBoundary } from './ErrorBoundary' import { ErrorBoundary } from './ErrorBoundary'
import { Base } from './styles/Base' import { Base } from './styles/Base'
import { ComponentStyles } from './styles/ComponentStyles' import { ComponentStyles } from './styles/ComponentStyles'
...@@ -14,8 +13,6 @@ type OverlayState = { ...@@ -14,8 +13,6 @@ type OverlayState = {
nextId: number nextId: number
buildError: string | null buildError: string | null
errors: SupportedErrorEvent[] errors: SupportedErrorEvent[]
fullRefreshReason: string | null
isAboutToFullRefresh: boolean
} }
function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
...@@ -26,19 +23,6 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { ...@@ -26,19 +23,6 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
case Bus.TYPE_BUILD_ERROR: { case Bus.TYPE_BUILD_ERROR: {
return { ...state, buildError: ev.message } return { ...state, buildError: ev.message }
} }
case Bus.TYPE_FULL_REFRESH_NEEDED: {
const aboutToRefreshNewState: OverlayState = {
...state,
fullRefreshReason: null,
isAboutToFullRefresh: true,
}
if (ev.reason === null) {
return aboutToRefreshNewState
}
return { ...aboutToRefreshNewState, fullRefreshReason: ev.reason }
}
case Bus.TYPE_REFRESH: { case Bus.TYPE_REFRESH: {
return { ...state, buildError: null, errors: [] } return { ...state, buildError: null, errors: [] }
} }
...@@ -58,7 +42,7 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { ...@@ -58,7 +42,7 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
} }
} }
type ErrorType = 'runtime' | 'build' | 'full-refresh' type ErrorType = 'runtime' | 'build'
const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({ const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({
children, children,
...@@ -73,8 +57,6 @@ const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({ ...@@ -73,8 +57,6 @@ const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({
nextId: 1, nextId: 1,
buildError: null, buildError: null,
errors: [], errors: [],
fullRefreshReason: null,
isAboutToFullRefresh: false,
}) })
React.useEffect(() => { React.useEffect(() => {
...@@ -93,9 +75,8 @@ const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({ ...@@ -93,9 +75,8 @@ const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({
const hasBuildError = state.buildError != null const hasBuildError = state.buildError != null
const hasRuntimeErrors = Boolean(state.errors.length) const hasRuntimeErrors = Boolean(state.errors.length)
const isAboutToFullRefresh = state.isAboutToFullRefresh
const isMounted = hasBuildError || hasRuntimeErrors || isAboutToFullRefresh const isMounted = hasBuildError || hasRuntimeErrors
return ( return (
<React.Fragment> <React.Fragment>
...@@ -109,17 +90,9 @@ const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({ ...@@ -109,17 +90,9 @@ const ReactDevOverlay: React.FunctionComponent = function ReactDevOverlay({
<ComponentStyles /> <ComponentStyles />
{shouldPreventDisplay( {shouldPreventDisplay(
hasBuildError hasBuildError ? 'build' : hasRuntimeErrors ? 'runtime' : null,
? 'build'
: hasRuntimeErrors
? 'runtime'
: isAboutToFullRefresh
? 'full-refresh'
: null,
preventDisplay preventDisplay
) ? null : isAboutToFullRefresh ? ( ) ? null : hasBuildError ? (
<FullRefreshWarning reason={state.fullRefreshReason} />
) : hasBuildError ? (
<BuildError message={state.buildError!} /> <BuildError message={state.buildError!} />
) : hasRuntimeErrors ? ( ) : hasRuntimeErrors ? (
<Errors errors={state.errors} /> <Errors errors={state.errors} />
......
...@@ -2,7 +2,6 @@ import { StackFrame } from 'stacktrace-parser' ...@@ -2,7 +2,6 @@ import { StackFrame } from 'stacktrace-parser'
export const TYPE_BUILD_OK = 'build-ok' export const TYPE_BUILD_OK = 'build-ok'
export const TYPE_BUILD_ERROR = 'build-error' export const TYPE_BUILD_ERROR = 'build-error'
export const TYPE_FULL_REFRESH_NEEDED = 'full-refresh-needed'
export const TYPE_REFRESH = 'fast-refresh' export const TYPE_REFRESH = 'fast-refresh'
export const TYPE_UNHANDLED_ERROR = 'unhandled-error' export const TYPE_UNHANDLED_ERROR = 'unhandled-error'
export const TYPE_UNHANDLED_REJECTION = 'unhandled-rejection' export const TYPE_UNHANDLED_REJECTION = 'unhandled-rejection'
...@@ -13,10 +12,6 @@ export type BuildError = { ...@@ -13,10 +12,6 @@ export type BuildError = {
message: string message: string
} }
export type FastRefresh = { type: typeof TYPE_REFRESH } export type FastRefresh = { type: typeof TYPE_REFRESH }
export type FullRefreshNeeded = {
type: typeof TYPE_FULL_REFRESH_NEEDED
reason: string | null
}
export type UnhandledError = { export type UnhandledError = {
type: typeof TYPE_UNHANDLED_ERROR type: typeof TYPE_UNHANDLED_ERROR
reason: Error reason: Error
...@@ -31,7 +26,6 @@ export type BusEvent = ...@@ -31,7 +26,6 @@ export type BusEvent =
| BuildOk | BuildOk
| BuildError | BuildError
| FastRefresh | FastRefresh
| FullRefreshNeeded
| UnhandledError | UnhandledError
| UnhandledRejection | UnhandledRejection
......
import * as React from 'react'
import {
Dialog,
DialogBody,
DialogContent,
DialogHeader,
} from '../components/Dialog'
import { Overlay } from '../components/Overlay'
import { Terminal } from '../components/Terminal'
import { noop as css } from '../helpers/noop-template'
export type FullRefreshWarningProps = { reason: string | null }
const FULL_REFRESH_STORAGE_KEY = '_has_warned_about_full_refresh'
export const FullRefreshWarning: React.FC<FullRefreshWarningProps> =
function FullRefreshWarning({ reason }) {
const reload = React.useCallback(() => {
window.location.reload()
}, [])
const change = React.useCallback((e) => {
sessionStorage.setItem(
FULL_REFRESH_STORAGE_KEY,
e.target.checked ? 'ignore' : 'true'
)
}, [])
return (
<Overlay fixed>
<Dialog
type="warning"
aria-labelledby="nextjs__container_refresh_warning_label"
aria-describedby="nextjs__container_refresh_warning_desc"
onClose={reload}
>
<DialogContent>
<DialogHeader className="nextjs-container-refresh-warning-header">
<h4 id="nextjs__container_refresh_warning_label">
About to perform a full refresh
</h4>
</DialogHeader>
<DialogBody className="nextjs-container-refresh-warning-body">
<FullRefreshWarningReason reason={reason} />
<footer>
<p>
You can read more about Fast Refresh in{' '}
<a href="https://nextjs.org/docs/basic-features/fast-refresh#how-it-works">
our documentation
</a>
.
</p>
<label>
<input type="checkbox" onChange={change} /> Don't show again
for session
</label>
<button onClick={reload}>Reload</button>
</footer>
</DialogBody>
</DialogContent>
</Dialog>
</Overlay>
)
}
export const styles = css`
.nextjs-container-refresh-warning-header > h4 {
line-height: 1.5;
margin: 0;
padding: 0;
}
.nextjs-container-refresh-warning-body footer {
margin-top: var(--size-gap-double);
}
.nextjs-container-build-error-body p {
color: #757575;
}
.nextjs-container-refresh-warning-body button {
background-color: var(--color-ansi-yellow);
border: 0;
border-radius: var(--size-gap-half);
color: var(--color-ansi-black);
cursor: pointer;
display: block;
margin-left: auto;
padding: calc(var(--size-gap) + var(--size-gap-half))
calc(var(--size-gap-double) + var(--size-gap-half));
transition: background-color 0.25s ease;
}
.nextjs-container-refresh-warning-body button:hover {
background-color: var(--color-ansi-bright-yellow);
}
`
type FullRefreshBodyProps = {
reason: string | null
}
const FullRefreshWarningReason = ({
reason,
}: FullRefreshBodyProps): JSX.Element => {
if (reason === null) {
return (
<p>
Fast Refresh will perform a full reload because your application had an
unrecoverable error.
</p>
)
}
return (
<>
<p>
Fast Refresh will perform a full reload when you edit a file that is
imported by modules outside of the React rendering tree. It is also
possible the parent component of the component you edited is a class
component, which disables Fast Refresh. Fast Refresh requires at least
one parent function component in your React tree.
</p>
<p>You can find more information in the related error below:</p>
<Terminal content={reason} />
</>
)
}
...@@ -8,7 +8,6 @@ import { styles as terminal } from '../components/Terminal/styles' ...@@ -8,7 +8,6 @@ import { styles as terminal } from '../components/Terminal/styles'
import { styles as toast } from '../components/Toast' import { styles as toast } from '../components/Toast'
import { styles as buildErrorStyles } from '../container/BuildError' import { styles as buildErrorStyles } from '../container/BuildError'
import { styles as containerErrorStyles } from '../container/Errors' import { styles as containerErrorStyles } from '../container/Errors'
import { styles as fullRefreshWarningStyles } from '../container/FullRefreshWarning'
import { styles as containerRuntimeErrorStyles } from '../container/RuntimeError' import { styles as containerRuntimeErrorStyles } from '../container/RuntimeError'
import { noop as css } from '../helpers/noop-template' import { noop as css } from '../helpers/noop-template'
...@@ -26,7 +25,6 @@ export function ComponentStyles() { ...@@ -26,7 +25,6 @@ export function ComponentStyles() {
${buildErrorStyles} ${buildErrorStyles}
${containerErrorStyles} ${containerErrorStyles}
${containerRuntimeErrorStyles} ${containerRuntimeErrorStyles}
${fullRefreshWarningStyles}
`} `}
</style> </style>
) )
......
import { import {
ignoreFullRefreshWarnings,
getRedboxDescription, getRedboxDescription,
getRedboxHeader, getRedboxHeader,
getRedboxSource, getRedboxSource,
...@@ -31,7 +30,6 @@ export async function sandbox( ...@@ -31,7 +30,6 @@ export async function sandbox(
} }
await next.start() await next.start()
const browser = await webdriver(next.appPort, '/') const browser = await webdriver(next.appPort, '/')
await ignoreFullRefreshWarnings(browser)
return { return {
session: { session: {
async write(filename, content) { async write(filename, content) {
......
...@@ -3,7 +3,6 @@ import cheerio from 'cheerio' ...@@ -3,7 +3,6 @@ import cheerio from 'cheerio'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { import {
check, check,
clickReloadOnFullRefreshWarning,
getBrowserBodyText, getBrowserBodyText,
getRedboxHeader, getRedboxHeader,
getRedboxSource, getRedboxSource,
...@@ -383,7 +382,6 @@ describe('basic HMR', () => { ...@@ -383,7 +382,6 @@ describe('basic HMR', () => {
await next.patchFile(aboutPage, aboutContent) await next.patchFile(aboutPage, aboutContent)
await clickReloadOnFullRefreshWarning(browser)
await check( await check(
() => getBrowserBodyText(browser), () => getBrowserBodyText(browser),
/This is the contact page/ /This is the contact page/
...@@ -418,8 +416,6 @@ describe('basic HMR', () => { ...@@ -418,8 +416,6 @@ describe('basic HMR', () => {
aboutContent.replace('export', 'aa=20;\nexport') aboutContent.replace('export', 'aa=20;\nexport')
) )
await clickReloadOnFullRefreshWarning(browser)
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatch(/aa is not defined/) expect(await getRedboxHeader(browser)).toMatch(/aa is not defined/)
...@@ -489,7 +485,6 @@ describe('basic HMR', () => { ...@@ -489,7 +485,6 @@ describe('basic HMR', () => {
) )
) )
await clickReloadOnFullRefreshWarning(browser)
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(` expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(`
" 1 of 1 unhandled error " 1 of 1 unhandled error
...@@ -539,7 +534,6 @@ describe('basic HMR', () => { ...@@ -539,7 +534,6 @@ describe('basic HMR', () => {
const isReact17 = process.env.NEXT_TEST_REACT_VERSION === '^17' const isReact17 = process.env.NEXT_TEST_REACT_VERSION === '^17'
await clickReloadOnFullRefreshWarning(browser)
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
// TODO: Replace this when webpack 5 is the default // TODO: Replace this when webpack 5 is the default
expect( expect(
...@@ -591,7 +585,6 @@ describe('basic HMR', () => { ...@@ -591,7 +585,6 @@ describe('basic HMR', () => {
) )
) )
await clickReloadOnFullRefreshWarning(browser)
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(` expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(`
" 1 of 1 unhandled error " 1 of 1 unhandled error
...@@ -645,7 +638,6 @@ describe('basic HMR', () => { ...@@ -645,7 +638,6 @@ describe('basic HMR', () => {
errorContent.replace('throw error', 'return {}') errorContent.replace('throw error', 'return {}')
) )
await clickReloadOnFullRefreshWarning(browser)
await check(() => getBrowserBodyText(browser), /Hello/) await check(() => getBrowserBodyText(browser), /Hello/)
await next.patchFile(erroredPage, errorContent) await next.patchFile(erroredPage, errorContent)
...@@ -694,7 +686,6 @@ describe('basic HMR', () => { ...@@ -694,7 +686,6 @@ describe('basic HMR', () => {
errorContent.replace('throw error', 'return {}') errorContent.replace('throw error', 'return {}')
) )
await clickReloadOnFullRefreshWarning(browser)
await check(() => getBrowserBodyText(browser), /Hello/) await check(() => getBrowserBodyText(browser), /Hello/)
await next.patchFile(erroredPage, errorContent) await next.patchFile(erroredPage, errorContent)
......
...@@ -3,7 +3,6 @@ import cheerio from 'cheerio' ...@@ -3,7 +3,6 @@ import cheerio from 'cheerio'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { import {
check, check,
clickReloadOnFullRefreshWarning,
getBrowserBodyText, getBrowserBodyText,
getRedboxHeader, getRedboxHeader,
getRedboxSource, getRedboxSource,
...@@ -137,7 +136,6 @@ describe('basic HMR', () => { ...@@ -137,7 +136,6 @@ describe('basic HMR', () => {
// change the content // change the content
try { try {
await next.patchFile(aboutPagePath, editedContent) await next.patchFile(aboutPagePath, editedContent)
await clickReloadOnFullRefreshWarning(browser)
await check(() => getBrowserBodyText(browser), /COOL page/) await check(() => getBrowserBodyText(browser), /COOL page/)
} finally { } finally {
// add the original content // add the original content
...@@ -449,7 +447,6 @@ describe('basic HMR', () => { ...@@ -449,7 +447,6 @@ describe('basic HMR', () => {
await next.patchFile(aboutPage, aboutContent) await next.patchFile(aboutPage, aboutContent)
await clickReloadOnFullRefreshWarning(browser)
await check( await check(
() => getBrowserBodyText(browser), () => getBrowserBodyText(browser),
/This is the contact page/ /This is the contact page/
...@@ -484,7 +481,6 @@ describe('basic HMR', () => { ...@@ -484,7 +481,6 @@ describe('basic HMR', () => {
aboutContent.replace('export', 'aa=20;\nexport') aboutContent.replace('export', 'aa=20;\nexport')
) )
await clickReloadOnFullRefreshWarning(browser)
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatch(/aa is not defined/) expect(await getRedboxHeader(browser)).toMatch(/aa is not defined/)
...@@ -554,7 +550,6 @@ describe('basic HMR', () => { ...@@ -554,7 +550,6 @@ describe('basic HMR', () => {
) )
) )
await clickReloadOnFullRefreshWarning(browser)
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(` expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(`
" 1 of 1 unhandled error " 1 of 1 unhandled error
...@@ -604,7 +599,6 @@ describe('basic HMR', () => { ...@@ -604,7 +599,6 @@ describe('basic HMR', () => {
const isReact17 = process.env.NEXT_TEST_REACT_VERSION === '^17' const isReact17 = process.env.NEXT_TEST_REACT_VERSION === '^17'
await clickReloadOnFullRefreshWarning(browser)
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
// TODO: Replace this when webpack 5 is the default // TODO: Replace this when webpack 5 is the default
expect( expect(
...@@ -656,7 +650,6 @@ describe('basic HMR', () => { ...@@ -656,7 +650,6 @@ describe('basic HMR', () => {
) )
) )
await clickReloadOnFullRefreshWarning(browser)
expect(await hasRedbox(browser)).toBe(true) expect(await hasRedbox(browser)).toBe(true)
expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(` expect(await getRedboxHeader(browser)).toMatchInlineSnapshot(`
" 1 of 1 unhandled error " 1 of 1 unhandled error
...@@ -710,7 +703,6 @@ describe('basic HMR', () => { ...@@ -710,7 +703,6 @@ describe('basic HMR', () => {
errorContent.replace('throw error', 'return {}') errorContent.replace('throw error', 'return {}')
) )
await clickReloadOnFullRefreshWarning(browser)
await check(() => getBrowserBodyText(browser), /Hello/) await check(() => getBrowserBodyText(browser), /Hello/)
await next.patchFile(erroredPage, errorContent) await next.patchFile(erroredPage, errorContent)
...@@ -759,7 +751,6 @@ describe('basic HMR', () => { ...@@ -759,7 +751,6 @@ describe('basic HMR', () => {
errorContent.replace('throw error', 'return {}') errorContent.replace('throw error', 'return {}')
) )
await clickReloadOnFullRefreshWarning(browser)
await check(() => getBrowserBodyText(browser), /Hello/) await check(() => getBrowserBodyText(browser), /Hello/)
await next.patchFile(erroredPage, errorContent) await next.patchFile(erroredPage, errorContent)
......
import { createNext } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { check, getRedboxHeader } from 'next-test-utils'
import webdriver from 'next-webdriver'
describe('show a warning in CLI and browser when doing a full reload', () => {
let next: NextInstance
beforeEach(async () => {
next = await createNext({
files: {
'pages/anonymous-page-function.js': `
export default function() {
return <p>hello world</p>
}
`,
'pages/runtime-error.js': `
export default function() {
return whoops
}
`,
},
dependencies: {},
})
})
afterEach(() => next.destroy())
test('error', async () => {
const browser = await webdriver(next.url, `/anonymous-page-function`)
expect(await browser.elementByCss('p').text()).toBe('hello world')
expect(next.cliOutput).not.toContain(
'Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works'
)
const currentFileContent = await next.readFile(
'./pages/anonymous-page-function.js'
)
const newFileContent = currentFileContent.replace(
'<p>hello world</p>',
'<p>hello world!!!</p>'
)
await next.patchFile('./pages/anonymous-page-function.js', newFileContent)
await check(() => browser.elementByCss('p').text(), 'hello world!!!')
// CLI warning and stacktrace
expect(next.cliOutput).toContain(
'Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works'
)
expect(next.cliOutput).toContain(
'Error: Aborted because ./pages/anonymous-page-function.js is not accepted'
)
// Browser warning
const browserLogs = await browser.log()
expect(
browserLogs.some(({ message }) =>
message.includes(
"Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree."
)
)
).toBeTruthy()
})
test('runtime-error', async () => {
const browser = await webdriver(next.url, `/runtime-error`)
await check(
() => getRedboxHeader(browser),
/ReferenceError: whoops is not defined/
)
expect(next.cliOutput).not.toContain(
'Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works'
)
const currentFileContent = await next.readFile('./pages/runtime-error.js')
const newFileContent = currentFileContent.replace('whoops', '"whoops"')
await next.patchFile('./pages/runtime-error.js', newFileContent)
await check(() => browser.elementByCss('body').text(), 'whoops')
// CLI warning and stacktrace
expect(next.cliOutput).toContain(
'Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/basic-features/fast-refresh#how-it-works'
)
expect(next.cliOutput).not.toContain(
'Error: Aborted because ./pages/runtime-error.js is not accepted'
)
// Browser warning
const browserLogs = await browser.log()
expect(
browserLogs.some(({ message }) =>
message.includes(
'[Fast Refresh] performing full reload because your application had an unrecoverable error'
)
)
).toBeTruthy()
})
})
...@@ -3,13 +3,7 @@ ...@@ -3,13 +3,7 @@
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { import { killApp, findPort, launchApp, check } from 'next-test-utils'
killApp,
findPort,
launchApp,
check,
clickReloadOnFullRefreshWarning,
} from 'next-test-utils'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const appPage = join(appDir, 'pages/_app.js') const appPage = join(appDir, 'pages/_app.js')
...@@ -46,7 +40,6 @@ describe('_app/_document add HMR', () => { ...@@ -46,7 +40,6 @@ describe('_app/_document add HMR', () => {
` `
) )
await clickReloadOnFullRefreshWarning(browser)
await check(async () => { await check(async () => {
const html = await browser.eval('document.documentElement.innerHTML') const html = await browser.eval('document.documentElement.innerHTML')
return html.includes('custom _app') && html.includes('index page') return html.includes('custom _app') && html.includes('index page')
......
...@@ -3,13 +3,7 @@ ...@@ -3,13 +3,7 @@
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { import { killApp, findPort, launchApp, check } from 'next-test-utils'
killApp,
findPort,
launchApp,
check,
clickReloadOnFullRefreshWarning,
} from 'next-test-utils'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const appPage = join(appDir, 'pages/_app.js') const appPage = join(appDir, 'pages/_app.js')
...@@ -36,7 +30,6 @@ describe('_app removal HMR', () => { ...@@ -36,7 +30,6 @@ describe('_app removal HMR', () => {
await fs.rename(appPage, appPage + '.bak') await fs.rename(appPage, appPage + '.bak')
await clickReloadOnFullRefreshWarning(browser)
await check(async () => { await check(async () => {
const html = await browser.eval('document.documentElement.innerHTML') const html = await browser.eval('document.documentElement.innerHTML')
return html.includes('index page') && !html.includes('custom _app') return html.includes('index page') && !html.includes('custom _app')
...@@ -63,7 +56,6 @@ describe('_app removal HMR', () => { ...@@ -63,7 +56,6 @@ describe('_app removal HMR', () => {
await fs.rename(appPage + '.bak', appPage) await fs.rename(appPage + '.bak', appPage)
await clickReloadOnFullRefreshWarning(browser)
await check(async () => { await check(async () => {
const html = await browser.eval('document.documentElement.innerHTML') const html = await browser.eval('document.documentElement.innerHTML')
return html.includes('index page updated') && return html.includes('index page updated') &&
......
/* eslint-env jest */ /* eslint-env jest */
import { import {
check, check,
clickReloadOnFullRefreshWarning,
File, File,
findPort, findPort,
hasRedbox, hasRedbox,
...@@ -44,8 +43,6 @@ describe('no duplicate compile error output', () => { ...@@ -44,8 +43,6 @@ describe('no duplicate compile error output', () => {
f.restore() f.restore()
} }
await clickReloadOnFullRefreshWarning(browser)
// Wait for compile error to disappear: // Wait for compile error to disappear:
await check( await check(
() => hasRedbox(browser, false).then((r) => (r ? 'yes' : 'no')), () => hasRedbox(browser, false).then((r) => (r ? 'yes' : 'no')),
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
import fs from 'fs-extra' import fs from 'fs-extra'
import { import {
check, check,
ignoreFullRefreshWarnings,
findPort, findPort,
getBrowserBodyText, getBrowserBodyText,
getRedboxHeader, getRedboxHeader,
...@@ -37,7 +36,6 @@ describe('TypeScript HMR', () => { ...@@ -37,7 +36,6 @@ describe('TypeScript HMR', () => {
let browser let browser
try { try {
browser = await webdriver(appPort, '/hello') browser = await webdriver(appPort, '/hello')
await ignoreFullRefreshWarnings(browser)
await check(() => getBrowserBodyText(browser), /Hello World/) await check(() => getBrowserBodyText(browser), /Hello World/)
const pagePath = join(appDir, 'pages/hello.tsx') const pagePath = join(appDir, 'pages/hello.tsx')
...@@ -91,7 +89,6 @@ describe('TypeScript HMR', () => { ...@@ -91,7 +89,6 @@ describe('TypeScript HMR', () => {
const origContent = await fs.readFile(pagePath, 'utf8') const origContent = await fs.readFile(pagePath, 'utf8')
try { try {
browser = await webdriver(appPort, '/type-error-recover') browser = await webdriver(appPort, '/type-error-recover')
await ignoreFullRefreshWarnings(browser)
const errContent = origContent.replace( const errContent = origContent.replace(
'() => <p>Hello world</p>', '() => <p>Hello world</p>',
'(): boolean => <p>hello with error</p>' '(): boolean => <p>hello with error</p>'
......
...@@ -607,42 +607,6 @@ export async function hasRedbox(browser, expected = true) { ...@@ -607,42 +607,6 @@ export async function hasRedbox(browser, expected = true) {
return false return false
} }
export async function ignoreFullRefreshWarnings(browser) {
await browser.eval(() => {
sessionStorage.setItem('_has_warned_about_full_refresh', 'ignore')
})
}
export async function clickReloadOnFullRefreshWarning(browser) {
await retry(async () => {
const hasFullRefreshWarning = await evaluate(browser, () =>
Boolean(
Array.from(document.querySelectorAll('nextjs-portal')).find(
(p) =>
p.shadowRoot.querySelector(
'#nextjs__container_refresh_warning_label'
)?.textContent === 'About to perform a full refresh'
)
)
)
if (!hasFullRefreshWarning) throw new Error('No full refresh warning')
return evaluate(browser, () => {
const buttons = Array.from(document.querySelectorAll('nextjs-portal'))
.find(
(p) =>
p.shadowRoot.querySelector(
'#nextjs__container_refresh_warning_label'
)?.textContent === 'About to perform a full refresh'
)
.shadowRoot.querySelectorAll('button')
Array.from(buttons)
.find((b) => b.textContent === 'Reload')
.click()
})
})
}
export async function getRedboxHeader(browser) { export async function getRedboxHeader(browser) {
return retry( return retry(
() => () =>
......
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