Unverified Commit 77cd1afa authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[Instant] Dev Tools toggle for Instant Navigation Mode (#90222)

Adds an "Instant Navigation Mode" toggle to the Dev Tools indicator
menu. When enabled, navigations only show the cached/prefetched state —
the same behavior as the instant navigation testing API, but toggled
from the dev tools UI instead of test code.

Gated behind `experimental.instantNavigationDevToolsToggle`.

This is a proof of concept — the UX needs more work before it's ready to
ship broadly (e.g. the toggle should be more discoverable, and the
locked state needs clearer visual feedback). But it's sufficient to
demonstrate the workflow and get feedback.



https://github.com/user-attachments/assets/ce2992e1-2794-43d6-baef-d10750d8d8e8
parent 35adcd1a
......@@ -172,6 +172,8 @@ export function getDefineEnv({
),
'process.env.__NEXT_PPR': isPPREnabled,
'process.env.__NEXT_CACHE_COMPONENTS': isCacheComponentsEnabled,
'process.env.__NEXT_INSTANT_NAV_TOGGLE':
!!config.experimental.instantNavigationDevToolsToggle,
'process.env.__NEXT_USE_CACHE': isUseCacheEnabled,
...(config.experimental?.useSkewCookie || !config.deploymentId
......
......@@ -76,34 +76,29 @@ export function appBootstrap(hydrate: (assetPrefix: string) => void) {
}
}
// Instant Navigation Testing API: If the server returned a partial static
// shell (indicated by the __next_instant_test global injected into the
// HTML), skip hydration. The response doesn't include the full Flight data
// stream. When the test framework deletes the cookie, the CookieStore
// change event triggers a page reload.
// Instant Navigation Testing: When the cookie is set, set up a
// CookieStore listener that auto-reloads when the cookie is cleared.
// This is shared infrastructure for both the dev tools toggle and
// external test frameworks.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (self.__next_instant_test) {
const NEXT_INSTANT_TEST_COOKIE = 'next-instant-navigation-testing'
if (
typeof cookieStore !== 'undefined' &&
document.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=')
) {
// Cookie is still set. Wait for the test framework to delete it,
// then reload to get the full response.
cookieStore.addEventListener('change', (event: CookieChangeEvent) => {
for (const cookie of event.deleted) {
if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {
window.location.reload()
return
}
const NEXT_INSTANT_TEST_COOKIE = 'next-instant-navigation-testing'
if (
document.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=') &&
typeof cookieStore !== 'undefined'
) {
cookieStore.addEventListener('change', (event: CookieChangeEvent) => {
for (const cookie of event.deleted) {
if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {
window.location.reload()
return
}
})
} else {
// Cookie is already gone (or not accessible). Refresh immediately
// to get the full response.
window.location.reload()
}
return
}
})
} else if (self.__next_instant_test) {
// The server returned a static shell but we couldn't set up the
// cookie listener (document.cookie is empty or cookieStore is
// unavailable). Reload immediately to get the full response.
window.location.reload()
}
}
......
......@@ -11,11 +11,28 @@ import { isRecoverableError } from './react-client-callbacks/on-recoverable-erro
const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
// Instant Navigation Mode: When the server returned a partial static shell
// (indicated by the __next_instant_test global), skip app hydration and only
// render the dev overlay so the developer can toggle the mode off. Hydration
// would fail because the static shell response doesn't include the full
// Flight data stream.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (self.__next_instant_test) {
renderAppDevOverlay(
getOwnerStack,
isRecoverableError,
enableCacheIndicator
)
return
}
}
const { hydrate } = require('./app-index') as typeof import('./app-index')
try {
hydrate(instrumentationHooks, assetPrefix)
} finally {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
renderAppDevOverlay(getOwnerStack, isRecoverableError, enableCacheIndicator)
}
})
......@@ -9,6 +9,28 @@ window.next.turbopack = true
const instrumentationHooks = require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => {
// Instant Navigation Mode: The server returned a partial static shell.
// Skip hydration — the response doesn't include the full Flight data
// stream. In dev mode, still render the dev overlay so the developer can
// toggle the mode off.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (self.__next_instant_test) {
if (process.env.__NEXT_DEV_SERVER) {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
const { getOwnerStack } =
require('../next-devtools/userspace/app/errors/stitched-error') as typeof import('../next-devtools/userspace/app/errors/stitched-error')
const { renderAppDevOverlay } =
require('next/dist/compiled/next-devtools') as typeof import('next/dist/compiled/next-devtools')
renderAppDevOverlay(
getOwnerStack,
isRecoverableError,
enableCacheIndicator
)
}
return
}
}
const { hydrate } = require('./app-index') as typeof import('./app-index')
try {
hydrate(instrumentationHooks, assetPrefix)
......
......@@ -8,6 +8,15 @@ const instrumentationHooks =
require('../lib/require-instrumentation-client')
appBootstrap((assetPrefix) => {
// Instant Navigation Mode: The server returned a partial static shell.
// Skip hydration — the response doesn't include the full Flight data
// stream. The cookie listener in app-bootstrap handles the reload.
if (process.env.__NEXT_EXPOSE_TESTING_API) {
if (self.__next_instant_test) {
return
}
}
const { hydrate } = require('./app-index') as typeof import('./app-index')
// Include app-router and layout-router in the main chunk
// eslint-disable-next-line @next/internal/typechecked-require -- Why not relative imports?
......
......@@ -22,6 +22,7 @@ import {
type OverlayState,
type DispatcherEvent,
ACTION_CACHE_INDICATOR,
ACTION_CACHE_ONLY_TOGGLE,
} from './dev-overlay/shared'
import {
......@@ -73,6 +74,7 @@ export interface Dispatcher {
segmentExplorerNodeAdd(nodeState: SegmentNodeState): void
segmentExplorerNodeRemove(nodeState: SegmentNodeState): void
segmentExplorerUpdateRouteState(page: string): void
cacheOnlyToggle(): void
}
type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1]
......@@ -224,6 +226,9 @@ export const dispatcher: Dispatcher = {
dispatch({ type: ACTION_DEVTOOL_UPDATE_ROUTE_STATE, page })
}
),
cacheOnlyToggle: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_CACHE_ONLY_TOGGLE })
}),
}
function replayQueuedEvents(dispatch: NonNullable<typeof maybeDispatch>) {
......
......@@ -45,16 +45,23 @@ export function NextLogo({
const isCacheFilling = state.cacheIndicator === 'filling'
const isCacheBypassing = state.cacheIndicator === 'bypass'
// Determine if we should show any status (excluding cache bypass, which renders like error badge)
const shouldShowStatus =
// Determine if we should show any transient status (excluding cache bypass)
const shouldShowTransientStatus =
state.buildingIndicator || state.renderingIndicator || isCacheFilling
// Delay showing for 400ms to catch fast operations,
// and keep visible for minimum time (longer for warnings)
const { rendered: showStatusIndicator } = useDelayedRender(shouldShowStatus, {
enterDelay: 400,
exitDelay: 500,
})
const { rendered: showTransientStatusIndicator } = useDelayedRender(
shouldShowTransientStatus,
{
enterDelay: 400,
exitDelay: 500,
}
)
// Instant mode shows immediately (no delay) since it's a persistent user-toggled state
const isCacheOnly = state.cacheOnly
const showStatusIndicator = showTransientStatusIndicator || isCacheOnly
const ref = useRef<HTMLDivElement | null>(null)
const measuredWidth = useMeasureWidth(ref)
......@@ -63,7 +70,8 @@ export function NextLogo({
const currentStatus = getCurrentStatus(
state.buildingIndicator,
state.renderingIndicator,
state.cacheIndicator
state.cacheIndicator,
state.cacheOnly
)
const displayStatus = showStatusIndicator ? currentStatus : Status.None
......@@ -184,6 +192,17 @@ export function NextLogo({
}
}
&[data-cache-only='true']:not([data-error='true']):not(
[data-cache-bypassing='true']
) {
background: rgba(59, 130, 246, 0.95);
--color-inner-border: rgba(96, 165, 250, 0.9);
[data-issues-open] {
color: white;
}
}
&[data-error-expanded='false'][data-error='true'] ~ [data-dot] {
scale: 1;
}
......@@ -379,6 +398,7 @@ export function NextLogo({
data-error-expanded={isExpanded}
data-status={hasError || isCacheBypassing ? Status.None : currentStatus}
data-cache-bypassing={isCacheBypassing}
data-cache-only={isCacheOnly}
data-animate={newErrorDetected}
style={{ width }}
>
......@@ -489,7 +509,20 @@ export function NextLogo({
!state.disableDevIndicator && (
<StatusIndicator
status={displayStatus}
onClick={onTriggerClick}
title={
displayStatus === Status.Instant
? 'Unblock dynamic data'
: undefined
}
onClick={
displayStatus === Status.Instant
? () => {
document.cookie =
'next-instant-navigation-testing=; path=/; max-age=0'
window.location.reload()
}
: onTriggerClick
}
/>
)}
</>
......
......@@ -7,16 +7,18 @@ export enum Status {
Compiling = 'compiling',
Prerendering = 'prerendering',
CacheBypassing = 'cache-bypassing',
Instant = 'instant',
}
export function getCurrentStatus(
buildingIndicator: boolean,
renderingIndicator: boolean,
cacheIndicator: CacheIndicatorState
cacheIndicator: CacheIndicatorState,
instantMode?: boolean
): Status {
const isCacheFilling = cacheIndicator === 'filling'
// Priority order: compiling > prerendering > rendering
// Priority order: compiling > prerendering > rendering > instant
// Note: cache bypassing is now handled as a badge, not a status indicator
if (buildingIndicator) {
return Status.Compiling
......@@ -27,21 +29,30 @@ export function getCurrentStatus(
if (renderingIndicator) {
return Status.Rendering
}
if (instantMode) {
return Status.Instant
}
return Status.None
}
interface StatusIndicatorProps {
status: Status
onClick?: () => void
title?: string
}
export function StatusIndicator({ status, onClick }: StatusIndicatorProps) {
export function StatusIndicator({
status,
onClick,
title,
}: StatusIndicatorProps) {
const statusText: Record<Status, string> = {
[Status.None]: '',
[Status.CacheBypassing]: 'Cache disabled',
[Status.Prerendering]: 'Prerendering',
[Status.Compiling]: 'Compiling',
[Status.Rendering]: 'Rendering',
[Status.Instant]: 'Instant UI only',
}
// Status dot colors
......@@ -51,6 +62,7 @@ export function StatusIndicator({ status, onClick }: StatusIndicatorProps) {
[Status.Prerendering]: '#f5a623',
[Status.Compiling]: '#f5a623',
[Status.Rendering]: '#50e3c2',
[Status.Instant]: '#fff', // White dot on blue badge background
}
if (status === Status.None) {
......@@ -160,7 +172,8 @@ export function StatusIndicator({ status, onClick }: StatusIndicatorProps) {
data-indicator-status
data-nextjs-dev-tools-button
onClick={onClick}
aria-label="Open Next.js Dev Tools"
title={title}
aria-label={title || 'Open Next.js Dev Tools'}
>
{statusDotColor[status] && (
<div
......
......@@ -21,6 +21,7 @@ import {
ACTION_DEVTOOLS_SCALE,
ACTION_ERROR_OVERLAY_CLOSE,
ACTION_ERROR_OVERLAY_OPEN,
ACTION_CACHE_ONLY_TOGGLE,
} from '../shared'
import GearIcon from '../icons/gear-icon'
import { LoadingIcon } from '../icons/loading-icon'
......@@ -104,6 +105,31 @@ const MenuPanel = () => {
label: 'Cache Components',
value: 'Enabled',
},
isAppRouter &&
!!process.env.__NEXT_INSTANT_NAV_TOGGLE && {
title:
'When enabled, navigations show only the cached/prefetched state.',
label: 'Instant Navigation Mode',
value: state.cacheOnly ? 'On' : 'Off',
onClick: () => {
if (state.cacheOnly) {
// Turn off: delete cookie and reload to get dynamic data
document.cookie =
'next-instant-navigation-testing=; path=/; max-age=0'
dispatch({ type: ACTION_CACHE_ONLY_TOGGLE })
window.location.reload()
} else {
// Turn on: set cookie to lock dynamic requests
document.cookie = 'next-instant-navigation-testing=1; path=/'
dispatch({ type: ACTION_CACHE_ONLY_TOGGLE })
setPanel(null)
setSelectedIndex(-1)
}
},
attributes: {
'data-cache-only': true,
},
},
isAppRouter && {
label: 'Route Info',
value: <ChevronRight />,
......
......@@ -70,6 +70,7 @@ export interface OverlayState {
readonly page: string
readonly theme: 'light' | 'dark' | 'system'
readonly hideShortcut: string | null
readonly cacheOnly: boolean
}
type DevtoolsPanelName = string
export type OverlayDispatch = React.Dispatch<DispatcherEvent>
......@@ -101,6 +102,7 @@ export const ACTION_DEVTOOLS_PANEL_POSITION = 'devtools-panel-position'
export const ACTION_DEVTOOLS_SCALE = 'devtools-scale'
export const ACTION_DEVTOOLS_CONFIG = 'devtools-config'
export const ACTION_CACHE_ONLY_TOGGLE = 'cache-only-toggle'
export const STORAGE_KEY_PANEL_POSITION_PREFIX =
'__nextjs-dev-tools-panel-position'
......@@ -216,6 +218,10 @@ interface DevToolsConfigAction {
devToolsConfig: DevToolsConfig
}
interface CacheOnlyToggleAction {
type: typeof ACTION_CACHE_ONLY_TOGGLE
}
export type DispatcherEvent =
| BuildOkAction
| BuildErrorAction
......@@ -241,6 +247,7 @@ export type DispatcherEvent =
| DevToolUpdateRouteStateAction
| DevIndicatorSetAction
| DevToolsConfigAction
| CacheOnlyToggleAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: new frame + v8
......@@ -263,6 +270,11 @@ const shouldDisableDevIndicator =
const devToolsInitialPositionFromNextConfig = (process.env
.__NEXT_DEV_INDICATOR_POSITION ?? 'bottom-left') as Corners
const hasInstantTestCookie =
!!process.env.__NEXT_INSTANT_NAV_TOGGLE &&
typeof document !== 'undefined' &&
document.cookie.includes('next-instant-navigation-testing=')
export const INITIAL_OVERLAY_STATE: Omit<
OverlayState,
'isErrorOverlayOpen' | 'routerType'
......@@ -274,12 +286,15 @@ export const INITIAL_OVERLAY_STATE: Omit<
renderingIndicator: false,
cacheIndicator: 'disabled',
staticIndicator: 'disabled',
/*
/*
This is set to `true` when we can reliably know
whether the indicator is in disabled state or not.
whether the indicator is in disabled state or not.
Otherwise the surface would flicker because the disabled flag loads from the config.
*/
showIndicator: false,
// When cache-only is active, show the indicator immediately so the user
// can toggle it off. Normally this is set to true by the HMR connection,
// but the HMR WebSocket is only created during hydration.
showIndicator: hasInstantTestCookie,
disableDevIndicator: false,
buildingIndicator: false,
refreshState: { type: 'idle' },
......@@ -294,6 +309,7 @@ export const INITIAL_OVERLAY_STATE: Omit<
page: '',
theme: 'system',
hideShortcut: null,
cacheOnly: hasInstantTestCookie,
}
function getInitialState(
......@@ -507,6 +523,9 @@ export function useErrorOverlayReducer(
hideShortcut !== undefined ? hideShortcut : state.hideShortcut,
}
}
case ACTION_CACHE_ONLY_TOGGLE: {
return { ...state, cacheOnly: !state.cacheOnly }
}
default: {
return state
}
......
......@@ -8,6 +8,7 @@ import {
ACTION_BUILDING_INDICATOR_HIDE,
ACTION_BUILDING_INDICATOR_SHOW,
ACTION_CACHE_INDICATOR,
ACTION_CACHE_ONLY_TOGGLE,
ACTION_DEBUG_INFO,
ACTION_DEV_INDICATOR,
ACTION_DEV_INDICATOR_SET,
......@@ -83,6 +84,7 @@ export function useStorybookOverlayReducer(initialState?: OverlayState) {
case ACTION_RENDERING_INDICATOR_HIDE:
case ACTION_RENDERING_INDICATOR_SHOW:
case ACTION_CACHE_INDICATOR:
case ACTION_CACHE_ONLY_TOGGLE:
case ACTION_STATIC_INDICATOR:
case ACTION_UNHANDLED_ERROR:
case ACTION_UNHANDLED_REJECTION:
......
......@@ -239,6 +239,7 @@ export const experimentalSchema = {
externalMiddlewareRewritesResolve: z.boolean().optional(),
externalProxyRewritesResolve: z.boolean().optional(),
exposeTestingApiInProductionBuild: z.boolean().optional(),
instantNavigationDevToolsToggle: z.boolean().optional(),
fallbackNodePolyfills: z.literal(false).optional(),
fetchCacheKeyPrefix: z.string().optional(),
forceSwcTransforms: z.boolean().optional(),
......
......@@ -394,6 +394,12 @@ export interface ExperimentalConfig {
* Do not enable in user-facing production deployments.
*/
exposeTestingApiInProductionBuild?: boolean
/**
* Show the Instant Navigation Mode toggle in the dev tools indicator.
* When enabled, a menu item lets you lock navigations to only show
* the cached/prefetched state.
*/
instantNavigationDevToolsToggle?: boolean
extensionAlias?: Record<string, any>
allowedRevalidateHeaderKeys?: string[]
fetchCacheKeyPrefix?: string
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body
style={{
fontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
maxWidth: 640,
margin: '0 auto',
padding: '2rem 1rem',
lineHeight: 1.6,
color: '#111',
}}
>
{children}
</body>
</html>
)
}
import Link from 'next/link'
export default function Page() {
return (
<div>
<h1 data-testid="home-title">Instant Navigation Mode Demo</h1>
<p>
This fixture tests the <strong>Instant Navigation Mode</strong> toggle
in Next.js Dev Tools. When enabled, navigations show only the cached or
prefetched state — dynamic data is not streamed.
</p>
<h2>How to test</h2>
<ol>
<li>
Open <strong>Next.js Dev Tools</strong> (click the Next.js logo in the
corner).
</li>
<li>
Toggle <strong>Instant Navigation Mode</strong> to <em>On</em>. The
indicator turns blue.
</li>
<li>
Click the link below. You should see the loading skeleton instead of
the final page content.
</li>
<li>
Click the blue <em>Instant UI only</em> indicator to unblock dynamic
data and resume normal navigation.
</li>
</ol>
<nav style={{ marginTop: '1.5rem' }}>
<Link
href="/target-page"
id="link-to-target"
style={{
display: 'inline-block',
padding: '0.5rem 1rem',
background: '#0070f3',
color: '#fff',
borderRadius: 6,
textDecoration: 'none',
}}
>
Go to target page &rarr;
</Link>
</nav>
</div>
)
}
export default function Loading() {
return (
<div data-testid="loading-shell">
<style>{`
@keyframes shimmer {
0% { background-position: -400px 0; }
100% { background-position: 400px 0; }
}
.skeleton {
background: linear-gradient(90deg, #eee 25%, #ddd 50%, #eee 75%);
background-size: 800px 100%;
animation: shimmer 1.5s ease-in-out infinite;
border-radius: 4px;
}
`}</style>
<div
className="skeleton"
style={{ width: 160, height: 28, marginBottom: 12 }}
/>
<div
className="skeleton"
style={{ width: '100%', height: 14, marginBottom: 8 }}
/>
<div
className="skeleton"
style={{ width: '80%', height: 14, marginBottom: 24 }}
/>
<div
className="skeleton"
style={{ width: 100, height: 20, marginBottom: 16 }}
/>
<div
style={{
border: '1px solid #eee',
borderRadius: 8,
overflow: 'hidden',
}}
>
{[0, 1, 2].map((i) => (
<div
key={i}
style={{ padding: '0.75rem', borderBottom: '1px solid #eee' }}
>
<div className="skeleton" style={{ width: 80, height: 14 }} />
<div
className="skeleton"
style={{ width: '90%', height: 14, marginTop: 8 }}
/>
</div>
))}
</div>
</div>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import Link from 'next/link'
function Skeleton({
width,
height,
style,
}: {
width: string | number
height: number
style?: React.CSSProperties
}) {
return (
<div
className="skeleton"
style={{
width,
height,
borderRadius: 4,
background: 'linear-gradient(90deg, #eee 25%, #ddd 50%, #eee 75%)',
backgroundSize: '800px 100%',
animation: 'shimmer 1.5s ease-in-out infinite',
...style,
}}
/>
)
}
async function DynamicComments() {
await connection()
const comments = [
{ author: 'Alice', text: 'This loaded dynamically via streaming.' },
{
author: 'Bob',
text: 'With Instant Navigation Mode on, you would see the skeleton instead.',
},
{
author: 'Charlie',
text: 'Click the "Instant UI only" indicator to unblock dynamic data.',
},
]
return (
<div data-testid="dynamic-content">
{comments.map((c, i) => (
<div
key={i}
style={{
padding: '0.75rem',
borderBottom: '1px solid #eee',
}}
>
<strong>{c.author}</strong>
<p style={{ margin: '0.25rem 0 0' }}>{c.text}</p>
</div>
))}
</div>
)
}
function CommentsSkeleton() {
return (
<div data-testid="comments-skeleton">
{[0, 1, 2].map((i) => (
<div
key={i}
style={{
padding: '0.75rem',
borderBottom: '1px solid #eee',
}}
>
<Skeleton width={80} height={14} />
<Skeleton width="90%" height={14} style={{ marginTop: 8 }} />
</div>
))}
</div>
)
}
export default function TargetPage() {
return (
<div>
<style>{`
@keyframes shimmer {
0% { background-position: -400px 0; }
100% { background-position: 400px 0; }
}
`}</style>
<h1>Target Page</h1>
<p>
The heading and this paragraph are static — they appear instantly. The
comments below are dynamic and stream in after the shell.
</p>
<h2 style={{ fontSize: '1.1rem', marginTop: '1.5rem' }}>Comments</h2>
<div
style={{
border: '1px solid #eee',
borderRadius: 8,
overflow: 'hidden',
marginBottom: '1.5rem',
}}
>
<Suspense fallback={<CommentsSkeleton />}>
<DynamicComments />
</Suspense>
</div>
<nav>
<Link
href="/"
style={{
display: 'inline-block',
padding: '0.5rem 1rem',
background: '#0070f3',
color: '#fff',
borderRadius: 6,
textDecoration: 'none',
}}
>
&larr; Back to home
</Link>
</nav>
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
import {
retry,
waitForDevToolsIndicator,
toggleDevToolsIndicatorPopover,
} from 'next-test-utils'
describe('instant-mode-toggle', () => {
const { next } = nextTestSetup({
files: __dirname,
})
async function clearInstantModeCookie(browser: any) {
await browser.eval(() => {
document.cookie = 'next-instant-navigation-testing=; path=/; max-age=0'
})
}
async function clickInstantModeMenuItem(browser: any) {
await browser.eval(() => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p: any) =>
p.shadowRoot.querySelector('[data-nextjs-toast]')
) as any
portal?.shadowRoot?.querySelector('[data-cache-only]')?.click()
})
}
async function getInstantModeMenuValue(browser: any): Promise<string> {
return browser.eval(() => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p: any) =>
p.shadowRoot.querySelector('[data-nextjs-toast]')
) as any
return (
portal?.shadowRoot
?.querySelector('[data-cache-only]')
?.innerText.split('\n')
.pop() || ''
)
})
}
async function getBadgeStatus(browser: any): Promise<string> {
return browser.eval(() => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p: any) =>
p.shadowRoot.querySelector('[data-nextjs-toast]')
) as any
return (
portal?.shadowRoot
?.querySelector('[data-next-badge]')
?.getAttribute('data-status') || ''
)
})
}
it('should show "instant" status after toggling on, not stuck on "compiling"', async () => {
const browser = await next.browser('/')
await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]')
// Wait for initial compilation to settle — the badge status should
// become "none" once compilation is done and no transient status is active
await retry(async () => {
const status = await getBadgeStatus(browser)
expect(status).toBe('none')
})
// Toggle instant mode on
await waitForDevToolsIndicator(browser)
await toggleDevToolsIndicatorPopover(browser)
await clickInstantModeMenuItem(browser)
// The badge status should settle to "instant", not stay on "compiling"
await retry(async () => {
const status = await getBadgeStatus(browser)
expect(status).toBe('instant')
})
// Clean up
await clearInstantModeCookie(browser)
})
it('should show "Instant mode" menu item and toggle it on', async () => {
const browser = await next.browser('/')
await clearInstantModeCookie(browser)
await waitForDevToolsIndicator(browser)
await toggleDevToolsIndicatorPopover(browser)
// Verify the "Instant mode" menu item shows "Off"
await retry(async () => {
const value = await getInstantModeMenuValue(browser)
expect(value).toBe('Off')
})
// Click to toggle on — this also closes the menu
await clickInstantModeMenuItem(browser)
// Verify the badge appears with data-cache-only="true"
await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]')
const attr = await badge.getAttribute('data-cache-only')
expect(attr).toBe('true')
})
// Verify the status indicator shows "Instant..."
await retry(async () => {
const hasIndicator = await browser.hasElementByCss(
'[data-indicator-status]'
)
expect(hasIndicator).toBe(true)
})
// Clean up
await clearInstantModeCookie(browser)
})
it('should show loading skeleton during SPA navigation when instant mode is on', async () => {
const browser = await next.browser('/')
await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]')
// Toggle instant mode on
await toggleDevToolsIndicatorPopover(browser)
await clickInstantModeMenuItem(browser)
// Wait for instant mode to be active
await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]')
const attr = await badge.getAttribute('data-cache-only')
expect(attr).toBe('true')
})
// Navigate to target page via SPA
await browser.elementByCss('#link-to-target').click()
// The comments skeleton should be visible (dynamic content is locked)
// while static content (heading, paragraph) is already rendered
await retry(async () => {
const skeleton = await browser.hasElementByCss(
'[data-testid="comments-skeleton"]'
)
expect(skeleton).toBe(true)
})
// Clean up
await clearInstantModeCookie(browser)
})
it('should turn off instant mode when clicking the badge', async () => {
const browser = await next.browser('/')
await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]')
// Toggle instant mode on via menu
await toggleDevToolsIndicatorPopover(browser)
await clickInstantModeMenuItem(browser)
// Verify it's on
await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]')
const attr = await badge.getAttribute('data-cache-only')
expect(attr).toBe('true')
})
// Click the "Instant..." status indicator to unlock — this clears the cookie and reloads
await browser.eval(() => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find((p: any) =>
p.shadowRoot.querySelector('[data-nextjs-toast]')
) as any
portal?.shadowRoot?.querySelector('[data-indicator-status]')?.click()
})
// After reload, instant mode should be off
await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]')
const attr = await badge.getAttribute('data-cache-only')
expect(attr).toBe('false')
})
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
instantNavigationDevToolsToggle: true,
},
}
module.exports = nextConfig
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