Unverified Commit 19a19a39 authored by Sam Selikoff's avatar Sam Selikoff Committed by GitHub

Updates to Instant Navs devtools functionality (#91005)

Updates the Instant Navs devtools functionality to use a panel and show
you two options for capturing the SSR shell or the prefetch for a Client
navigation.

Replaces current functionality where clicking Instant Navs changed the
devtools indicator to a blue pending state awaiting the user's next
navigation.


https://github.com/user-attachments/assets/de5c5a40-e836-4719-9517-6d5c6b0aef2c
parent 4271c8b8
...@@ -22,7 +22,7 @@ import { ...@@ -22,7 +22,7 @@ import {
type OverlayState, type OverlayState,
type DispatcherEvent, type DispatcherEvent,
ACTION_CACHE_INDICATOR, ACTION_CACHE_INDICATOR,
ACTION_CACHE_ONLY_TOGGLE, ACTION_INSTANT_NAVS_TOGGLE,
} from './dev-overlay/shared' } from './dev-overlay/shared'
import { import {
...@@ -74,7 +74,7 @@ export interface Dispatcher { ...@@ -74,7 +74,7 @@ export interface Dispatcher {
segmentExplorerNodeAdd(nodeState: SegmentNodeState): void segmentExplorerNodeAdd(nodeState: SegmentNodeState): void
segmentExplorerNodeRemove(nodeState: SegmentNodeState): void segmentExplorerNodeRemove(nodeState: SegmentNodeState): void
segmentExplorerUpdateRouteState(page: string): void segmentExplorerUpdateRouteState(page: string): void
cacheOnlyToggle(): void instantNavsToggle(): void
} }
type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1] type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1]
...@@ -226,8 +226,8 @@ export const dispatcher: Dispatcher = { ...@@ -226,8 +226,8 @@ export const dispatcher: Dispatcher = {
dispatch({ type: ACTION_DEVTOOL_UPDATE_ROUTE_STATE, page }) dispatch({ type: ACTION_DEVTOOL_UPDATE_ROUTE_STATE, page })
} }
), ),
cacheOnlyToggle: createQueuable((dispatch: Dispatch) => { instantNavsToggle: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_CACHE_ONLY_TOGGLE }) dispatch({ type: ACTION_INSTANT_NAVS_TOGGLE })
}), }),
} }
......
...@@ -45,23 +45,16 @@ export function NextLogo({ ...@@ -45,23 +45,16 @@ export function NextLogo({
const isCacheFilling = state.cacheIndicator === 'filling' const isCacheFilling = state.cacheIndicator === 'filling'
const isCacheBypassing = state.cacheIndicator === 'bypass' const isCacheBypassing = state.cacheIndicator === 'bypass'
// Determine if we should show any transient status (excluding cache bypass) // Determine if we should show any status (excluding cache bypass, which renders like error badge)
const shouldShowTransientStatus = const shouldShowStatus =
state.buildingIndicator || state.renderingIndicator || isCacheFilling state.buildingIndicator || state.renderingIndicator || isCacheFilling
// Delay showing for 400ms to catch fast operations, // Delay showing for 400ms to catch fast operations,
// and keep visible for minimum time (longer for warnings) // and keep visible for minimum time (longer for warnings)
const { rendered: showTransientStatusIndicator } = useDelayedRender( const { rendered: showStatusIndicator } = useDelayedRender(shouldShowStatus, {
shouldShowTransientStatus, enterDelay: 400,
{ exitDelay: 500,
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 ref = useRef<HTMLDivElement | null>(null)
const measuredWidth = useMeasureWidth(ref) const measuredWidth = useMeasureWidth(ref)
...@@ -70,8 +63,7 @@ export function NextLogo({ ...@@ -70,8 +63,7 @@ export function NextLogo({
const currentStatus = getCurrentStatus( const currentStatus = getCurrentStatus(
state.buildingIndicator, state.buildingIndicator,
state.renderingIndicator, state.renderingIndicator,
state.cacheIndicator, state.cacheIndicator
state.cacheOnly
) )
const displayStatus = showStatusIndicator ? currentStatus : Status.None const displayStatus = showStatusIndicator ? currentStatus : Status.None
...@@ -192,17 +184,6 @@ export function NextLogo({ ...@@ -192,17 +184,6 @@ 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] { &[data-error-expanded='false'][data-error='true'] ~ [data-dot] {
scale: 1; scale: 1;
} }
...@@ -398,7 +379,6 @@ export function NextLogo({ ...@@ -398,7 +379,6 @@ export function NextLogo({
data-error-expanded={isExpanded} data-error-expanded={isExpanded}
data-status={hasError || isCacheBypassing ? Status.None : currentStatus} data-status={hasError || isCacheBypassing ? Status.None : currentStatus}
data-cache-bypassing={isCacheBypassing} data-cache-bypassing={isCacheBypassing}
data-cache-only={isCacheOnly}
data-animate={newErrorDetected} data-animate={newErrorDetected}
style={{ width }} style={{ width }}
> >
...@@ -509,20 +489,7 @@ export function NextLogo({ ...@@ -509,20 +489,7 @@ export function NextLogo({
!state.disableDevIndicator && ( !state.disableDevIndicator && (
<StatusIndicator <StatusIndicator
status={displayStatus} status={displayStatus}
title={ onClick={onTriggerClick}
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,18 +7,16 @@ export enum Status { ...@@ -7,18 +7,16 @@ export enum Status {
Compiling = 'compiling', Compiling = 'compiling',
Prerendering = 'prerendering', Prerendering = 'prerendering',
CacheBypassing = 'cache-bypassing', CacheBypassing = 'cache-bypassing',
Instant = 'instant',
} }
export function getCurrentStatus( export function getCurrentStatus(
buildingIndicator: boolean, buildingIndicator: boolean,
renderingIndicator: boolean, renderingIndicator: boolean,
cacheIndicator: CacheIndicatorState, cacheIndicator: CacheIndicatorState
instantMode?: boolean
): Status { ): Status {
const isCacheFilling = cacheIndicator === 'filling' const isCacheFilling = cacheIndicator === 'filling'
// Priority order: compiling > prerendering > rendering > instant // Priority order: compiling > prerendering > rendering
// Note: cache bypassing is now handled as a badge, not a status indicator // Note: cache bypassing is now handled as a badge, not a status indicator
if (buildingIndicator) { if (buildingIndicator) {
return Status.Compiling return Status.Compiling
...@@ -29,30 +27,21 @@ export function getCurrentStatus( ...@@ -29,30 +27,21 @@ export function getCurrentStatus(
if (renderingIndicator) { if (renderingIndicator) {
return Status.Rendering return Status.Rendering
} }
if (instantMode) {
return Status.Instant
}
return Status.None return Status.None
} }
interface StatusIndicatorProps { interface StatusIndicatorProps {
status: Status status: Status
onClick?: () => void onClick?: () => void
title?: string
} }
export function StatusIndicator({ export function StatusIndicator({ status, onClick }: StatusIndicatorProps) {
status,
onClick,
title,
}: StatusIndicatorProps) {
const statusText: Record<Status, string> = { const statusText: Record<Status, string> = {
[Status.None]: '', [Status.None]: '',
[Status.CacheBypassing]: 'Cache disabled', [Status.CacheBypassing]: 'Cache disabled',
[Status.Prerendering]: 'Prerendering', [Status.Prerendering]: 'Prerendering',
[Status.Compiling]: 'Compiling', [Status.Compiling]: 'Compiling',
[Status.Rendering]: 'Rendering', [Status.Rendering]: 'Rendering',
[Status.Instant]: 'Instant UI only',
} }
// Status dot colors // Status dot colors
...@@ -62,7 +51,6 @@ export function StatusIndicator({ ...@@ -62,7 +51,6 @@ export function StatusIndicator({
[Status.Prerendering]: '#f5a623', [Status.Prerendering]: '#f5a623',
[Status.Compiling]: '#f5a623', [Status.Compiling]: '#f5a623',
[Status.Rendering]: '#50e3c2', [Status.Rendering]: '#50e3c2',
[Status.Instant]: '#fff', // White dot on blue badge background
} }
if (status === Status.None) { if (status === Status.None) {
...@@ -172,8 +160,7 @@ export function StatusIndicator({ ...@@ -172,8 +160,7 @@ export function StatusIndicator({
data-indicator-status data-indicator-status
data-nextjs-dev-tools-button data-nextjs-dev-tools-button
onClick={onClick} onClick={onClick}
title={title} aria-label={'Open Next.js Dev Tools'}
aria-label={title || 'Open Next.js Dev Tools'}
> >
{statusDotColor[status] && ( {statusDotColor[status] && (
<div <div
......
.instant-nav-panel {
display: flex;
flex-direction: column;
height: 100%;
}
.instant-nav-content {
flex: 1;
padding: 12px 20px 0;
}
/* Waiting state: preference-style sections */
.instant-nav-section {
padding: 12px 20px;
border-bottom: 1px solid var(--color-gray-400);
display: flex;
justify-content: space-between;
align-items: center;
gap: 24px;
}
.instant-nav-section:last-child {
border-bottom: none;
}
.instant-nav-section-header {
flex: 1;
}
.instant-nav-section-header label {
font-size: var(--size-14);
font-weight: 500;
color: var(--color-gray-1000);
margin: 0;
}
.instant-nav-section-description {
color: var(--color-gray-900);
font-size: var(--size-14);
margin: 0;
}
.instant-nav-section-control {
flex-shrink: 0;
}
.instant-nav-section-control .action-button {
display: flex;
align-items: center;
gap: 8px;
background: var(--color-background-100);
border: 1px solid var(--color-gray-400);
border-radius: var(--rounded-lg);
font-weight: 400;
font-size: var(--size-14);
color: var(--color-gray-1000);
padding: 6px 8px;
cursor: pointer;
transition: border-color 150ms var(--timing-swift);
}
.instant-nav-section-control .action-button:hover {
border-color: var(--color-gray-500);
}
.instant-nav-section-control .action-button svg {
width: 14px;
height: 14px;
overflow: visible;
}
.instant-nav-helper-text {
font-size: var(--size-14);
color: var(--color-gray-900);
font-style: italic;
white-space: nowrap;
}
/* Result states (client-nav, initial-load) */
.instant-nav-status-title {
margin: 0;
font-size: 14px;
font-weight: 600;
color: var(--color-gray-900);
}
.instant-nav-urls {
display: flex;
flex-direction: column;
gap: 4px;
margin-top: 4px;
}
.instant-nav-url-row {
display: flex;
gap: 8px;
font-size: 13px;
}
.instant-nav-url-label {
color: var(--color-gray-700);
flex-shrink: 0;
}
.instant-nav-url-value {
color: var(--color-gray-900);
word-break: break-all;
font-family: var(--font-mono);
}
.instant-nav-actions {
margin-top: 8px;
display: flex;
}
.instant-nav-share-button {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 16px;
border-radius: 6px;
border: 1px solid var(--color-gray-alpha-400);
background: var(--color-background-200);
color: var(--color-gray-900);
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: background 150ms ease;
}
.instant-nav-share-button:hover {
background: var(--color-gray-alpha-200);
}
.instant-nav-helper-description {
color: var(--color-gray-900);
font-size: var(--size-14);
margin: 8px 0 0;
}
/* Footer (pinned to bottom, matching segment-explorer-footer) */
.instant-nav-footer {
display: flex;
gap: 8px;
padding: 8px;
border-top: 1px solid var(--color-gray-400);
user-select: none;
}
.instant-nav-footer-button {
display: flex;
align-items: center;
justify-content: center;
flex: 1;
gap: 8px;
padding: 6px;
background: var(--color-background-100);
border: 1px solid var(--color-gray-400);
border-radius: 6px;
color: var(--color-gray-1000);
font-size: var(--size-14);
font-weight: 500;
cursor: pointer;
transition: background-color 0.15s ease;
}
.instant-nav-footer-button:hover {
background: var(--color-gray-200);
}
import { useEffect, useRef, useState } from 'react'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
import {
ACTION_INSTANT_NAVS_SET_STATUS,
ACTION_INSTANT_NAVS_RESET,
} from '../../shared'
import './instant-navs-panel.css'
export function InstantNavsPanel() {
const { state, dispatch } = useDevOverlayContext()
const { status } = state.instantNavsPanel
const panel = state.instantNavsPanel
const fromUrlRef = useRef<string>(
typeof window !== 'undefined'
? window.location.pathname + window.location.search
: ''
)
const initialPageRef = useRef<string>(state.page)
// Cleanup on unmount: clear cookie and reset state
useEffect(() => {
return () => {
// Read cookie before clearing to check if we were showing results
const match = document.cookie.match(
/next-instant-navigation-testing=([^;]*)/
)
const value = match ? match[1] : null
document.cookie = 'next-instant-navigation-testing=; path=/; max-age=0'
dispatch({ type: ACTION_INSTANT_NAVS_RESET })
// If we were showing results, reload to restore dynamic content
if (value) {
window.location.reload()
}
}
}, [dispatch])
// Navigation detection: watch state.page for changes while in waiting state
useEffect(() => {
if (status !== 'waiting') return
if (!state.page) return
// Capture the first non-empty page as baseline (state.page starts as '')
if (!initialPageRef.current) {
initialPageRef.current = state.page
return
}
if (state.page !== initialPageRef.current) {
dispatch({
type: ACTION_INSTANT_NAVS_SET_STATUS,
status: 'client-nav',
fromUrl: fromUrlRef.current,
toUrl: window.location.pathname + window.location.search,
})
}
}, [state.page, status, dispatch])
function handleReload() {
// Cookie is already set to '1' from when the panel opened.
// Just reload — the server will see the cookie and render the static shell.
window.location.reload()
}
function handleContinueRendering() {
document.cookie = 'next-instant-navigation-testing=; path=/; max-age=0'
window.location.reload()
}
function getShareUrl(): string {
const targetUrl = 'toUrl' in panel ? panel.toUrl : window.location.pathname
const url = new URL(targetUrl, window.location.origin)
url.searchParams.set('__instant_nav', '1')
if (panel.status === 'client-nav') {
url.searchParams.set('from', panel.fromUrl)
}
return url.toString()
}
if (panel.status === 'waiting') {
return (
<div className="instant-nav-panel">
<div className="instant-nav-section">
<div className="instant-nav-section-header">
<label>Page load</label>
<p className="instant-nav-section-description">
Reload to view the initial static UI for this page.
</p>
</div>
<div className="instant-nav-section-control">
<button
className="action-button"
onClick={handleReload}
data-instant-nav-refresh
>
<svg
width="14"
height="14"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M2.5 8a5.5 5.5 0 0 1 9.68-3.578L11.092 5.5H14.5V2.092l-1.395 1.395A7 7 0 1 0 15 8h-1.5A5.5 5.5 0 0 1 2.5 8Z"
fill="currentColor"
/>
</svg>
<span>Reload</span>
</button>
</div>
</div>
<div className="instant-nav-section">
<div className="instant-nav-section-header">
<label>Client navigation</label>
<p className="instant-nav-section-description">
Click any link in your app to view the prefetched UI for that
page.
</p>
</div>
</div>
</div>
)
}
if (panel.status === 'client-nav') {
return (
<div className="instant-nav-panel">
<div className="instant-nav-content">
<div className="instant-nav-section-header">
<label>Client navigation</label>
</div>
<div className="instant-nav-urls">
<div className="instant-nav-url-row">
<span className="instant-nav-url-label">From:</span>
<span className="instant-nav-url-value">{panel.fromUrl}</span>
</div>
<div className="instant-nav-url-row">
<span className="instant-nav-url-label">To:</span>
<span className="instant-nav-url-value">{panel.toUrl}</span>
</div>
</div>
<p className="instant-nav-helper-description">
You're viewing the prefetched UI for the previous navigation to the
current URL.
</p>
{/* TODO: Add back in after the navigation cookie supports reloads. */}
{/* <p className="instant-nav-helper-description">
Edit your code and reload the page to see any changes.
</p> */}
</div>
<div className="instant-nav-footer">
{/* TODO: Remove hidden wrapper once we add share functionality. */}
<span style={{ display: 'none' }}>
<ShareButton getShareUrl={getShareUrl} />
</span>
<button
className="instant-nav-footer-button"
onClick={handleContinueRendering}
type="button"
>
Continue rendering
</button>
</div>
</div>
)
}
if (panel.status === 'initial-load') {
return (
<div className="instant-nav-panel">
<div className="instant-nav-content">
<div className="instant-nav-section-header">
<label>Page load</label>
</div>
<div className="instant-nav-urls">
<div className="instant-nav-url-row">
<span className="instant-nav-url-label">Route:</span>
<span className="instant-nav-url-value">{panel.toUrl}</span>
</div>
</div>
<p className="instant-nav-helper-description">
You're viewing the pre-rendered static UI for the current URL.
</p>
{/* TODO: Add back in after the navigation cookie supports reloads. */}
{/* <p className="instant-nav-helper-description">
Edit your code and reload the page to see any changes.
</p> */}
</div>
<div className="instant-nav-footer">
{/* TODO: Remove hidden wrapper once we add share functionality. */}
<span style={{ display: 'none' }}>
<ShareButton getShareUrl={getShareUrl} />
</span>
<button
className="instant-nav-footer-button"
onClick={handleContinueRendering}
type="button"
>
Continue rendering
</button>
</div>
</div>
)
}
return null
}
function ShareButton({ getShareUrl }: { getShareUrl: () => string }) {
const [copied, setCopied] = useState(false)
function handleClick() {
navigator.clipboard.writeText(getShareUrl()).then(() => {
setCopied(true)
setTimeout(() => setCopied(false), 2000)
})
}
return (
<button
className="instant-nav-footer-button"
onClick={handleClick}
type="button"
data-instant-nav-share
>
{copied ? 'Copied!' : 'Share'}
</button>
)
}
...@@ -18,10 +18,12 @@ export const RenderErrorContext = createContext<{ ...@@ -18,10 +18,12 @@ export const RenderErrorContext = createContext<{
export const useRenderErrorContext = () => useContext(RenderErrorContext) export const useRenderErrorContext = () => useContext(RenderErrorContext)
export function DevOverlay() { export function DevOverlay() {
const [panel, setPanel] = useState<null | PanelStateKind>(null)
const [selectedIndex, setSelectedIndex] = useState(-1) const [selectedIndex, setSelectedIndex] = useState(-1)
const { state, dispatch, getSquashedHydrationErrorDetails } = const { state, dispatch, getSquashedHydrationErrorDetails } =
useDevOverlayContext() useDevOverlayContext()
const [panel, setPanel] = useState<null | PanelStateKind>(() =>
state.instantNavs ? 'instant-navs' : null
)
const triggerRef = useRef<HTMLButtonElement>(null) const triggerRef = useRef<HTMLButtonElement>(null)
return ( return (
......
...@@ -10,6 +10,7 @@ export type PanelStateKind = ...@@ -10,6 +10,7 @@ export type PanelStateKind =
| 'route-type' | 'route-type'
| 'segment-explorer' | 'segment-explorer'
| 'panel-selector' | 'panel-selector'
| 'instant-navs'
export const PanelRouterContext = createContext<{ export const PanelRouterContext = createContext<{
panel: PanelStateKind | null panel: PanelStateKind | null
......
...@@ -16,12 +16,12 @@ import { useDevOverlayContext } from '../../dev-overlay.browser' ...@@ -16,12 +16,12 @@ import { useDevOverlayContext } from '../../dev-overlay.browser'
import { createContext, useContext } from 'react' import { createContext, useContext } from 'react'
import { useRenderErrorContext } from '../dev-overlay' import { useRenderErrorContext } from '../dev-overlay'
import { import {
ACTION_INSTANT_NAVS_TOGGLE,
ACTION_DEV_INDICATOR_SET, ACTION_DEV_INDICATOR_SET,
ACTION_DEVTOOLS_POSITION, ACTION_DEVTOOLS_POSITION,
ACTION_DEVTOOLS_SCALE, ACTION_DEVTOOLS_SCALE,
ACTION_ERROR_OVERLAY_CLOSE, ACTION_ERROR_OVERLAY_CLOSE,
ACTION_ERROR_OVERLAY_OPEN, ACTION_ERROR_OVERLAY_OPEN,
ACTION_CACHE_ONLY_TOGGLE,
} from '../shared' } from '../shared'
import GearIcon from '../icons/gear-icon' import GearIcon from '../icons/gear-icon'
import { LoadingIcon } from '../icons/loading-icon' import { LoadingIcon } from '../icons/loading-icon'
...@@ -29,6 +29,7 @@ import { UserPreferencesBody } from '../components/errors/dev-tools-indicator/de ...@@ -29,6 +29,7 @@ import { UserPreferencesBody } from '../components/errors/dev-tools-indicator/de
import { useShortcuts } from '../hooks/use-shortcuts' import { useShortcuts } from '../hooks/use-shortcuts'
import { useUpdateAllPanelPositions } from '../components/devtools-indicator/devtools-indicator' import { useUpdateAllPanelPositions } from '../components/devtools-indicator/devtools-indicator'
import { saveDevToolsConfig } from '../utils/save-devtools-config' import { saveDevToolsConfig } from '../utils/save-devtools-config'
import { InstantNavsPanel } from '../components/instant-navs/instant-navs-panel'
import './panel-router.css' import './panel-router.css'
const MenuPanel = () => { const MenuPanel = () => {
...@@ -107,27 +108,20 @@ const MenuPanel = () => { ...@@ -107,27 +108,20 @@ const MenuPanel = () => {
}, },
isAppRouter && isAppRouter &&
!!process.env.__NEXT_INSTANT_NAV_TOGGLE && { !!process.env.__NEXT_INSTANT_NAV_TOGGLE && {
title: title: 'Test instant navigation behavior.',
'When enabled, navigations show only the cached/prefetched state.', label: 'Instant Navs',
label: 'Instant Navigation Mode', value: <ChevronRight />,
value: state.cacheOnly ? 'On' : 'Off',
onClick: () => { onClick: () => {
if (state.cacheOnly) { // Set cookie to activate the navigation lock (read by
// Turn off: delete cookie and reload to get dynamic data // navigation-testing-lock.ts via CookieStore change event)
document.cookie = document.cookie = 'next-instant-navigation-testing=1; path=/'
'next-instant-navigation-testing=; path=/; max-age=0' if (!state.instantNavs) {
dispatch({ type: ACTION_CACHE_ONLY_TOGGLE }) dispatch({ type: ACTION_INSTANT_NAVS_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)
} }
setPanel('instant-navs')
}, },
attributes: { attributes: {
'data-cache-only': true, 'data-instant-nav': true,
}, },
}, },
isAppRouter && { isAppRouter && {
...@@ -269,6 +263,22 @@ export const PanelRouter = () => { ...@@ -269,6 +263,22 @@ export const PanelRouter = () => {
</DynamicPanel> </DynamicPanel>
</PanelRoute> </PanelRoute>
)} )}
{isAppRouter && !!process.env.__NEXT_INSTANT_NAV_TOGGLE && (
<PanelRoute name="instant-navs">
<DynamicPanel
sharePanelSizeGlobally={false}
sizeConfig={{
kind: 'fixed',
height: 300 / state.scale,
width: 480 / state.scale,
}}
header={<DevToolsHeader title="Instant Navs" />}
>
<InstantNavsPanel />
</DynamicPanel>
</PanelRoute>
)}
</> </>
) )
} }
......
...@@ -70,7 +70,15 @@ export interface OverlayState { ...@@ -70,7 +70,15 @@ export interface OverlayState {
readonly page: string readonly page: string
readonly theme: 'light' | 'dark' | 'system' readonly theme: 'light' | 'dark' | 'system'
readonly hideShortcut: string | null readonly hideShortcut: string | null
readonly cacheOnly: boolean readonly instantNavs: boolean
readonly instantNavsPanel:
| { readonly status: 'waiting' }
| { readonly status: 'initial-load'; readonly toUrl: string }
| {
readonly status: 'client-nav'
readonly fromUrl: string
readonly toUrl: string
}
} }
type DevtoolsPanelName = string type DevtoolsPanelName = string
export type OverlayDispatch = React.Dispatch<DispatcherEvent> export type OverlayDispatch = React.Dispatch<DispatcherEvent>
...@@ -102,7 +110,9 @@ export const ACTION_DEVTOOLS_PANEL_POSITION = 'devtools-panel-position' ...@@ -102,7 +110,9 @@ export const ACTION_DEVTOOLS_PANEL_POSITION = 'devtools-panel-position'
export const ACTION_DEVTOOLS_SCALE = 'devtools-scale' export const ACTION_DEVTOOLS_SCALE = 'devtools-scale'
export const ACTION_DEVTOOLS_CONFIG = 'devtools-config' export const ACTION_DEVTOOLS_CONFIG = 'devtools-config'
export const ACTION_CACHE_ONLY_TOGGLE = 'cache-only-toggle' export const ACTION_INSTANT_NAVS_TOGGLE = 'instant-navs-toggle'
export const ACTION_INSTANT_NAVS_SET_STATUS = 'instant-navs-set-status'
export const ACTION_INSTANT_NAVS_RESET = 'instant-navs-reset'
export const STORAGE_KEY_PANEL_POSITION_PREFIX = export const STORAGE_KEY_PANEL_POSITION_PREFIX =
'__nextjs-dev-tools-panel-position' '__nextjs-dev-tools-panel-position'
...@@ -219,7 +229,25 @@ interface DevToolsConfigAction { ...@@ -219,7 +229,25 @@ interface DevToolsConfigAction {
} }
interface CacheOnlyToggleAction { interface CacheOnlyToggleAction {
type: typeof ACTION_CACHE_ONLY_TOGGLE type: typeof ACTION_INSTANT_NAVS_TOGGLE
}
type InstantNavSetStatusAction =
| { type: typeof ACTION_INSTANT_NAVS_SET_STATUS; status: 'waiting' }
| {
type: typeof ACTION_INSTANT_NAVS_SET_STATUS
status: 'initial-load'
toUrl: string
}
| {
type: typeof ACTION_INSTANT_NAVS_SET_STATUS
status: 'client-nav'
fromUrl: string
toUrl: string
}
interface InstantNavResetAction {
type: typeof ACTION_INSTANT_NAVS_RESET
} }
export type DispatcherEvent = export type DispatcherEvent =
...@@ -248,6 +276,8 @@ export type DispatcherEvent = ...@@ -248,6 +276,8 @@ export type DispatcherEvent =
| DevIndicatorSetAction | DevIndicatorSetAction
| DevToolsConfigAction | DevToolsConfigAction
| CacheOnlyToggleAction | CacheOnlyToggleAction
| InstantNavSetStatusAction
| InstantNavResetAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: new frame + v8 // 1st group: new frame + v8
...@@ -270,7 +300,7 @@ const shouldDisableDevIndicator = ...@@ -270,7 +300,7 @@ const shouldDisableDevIndicator =
const devToolsInitialPositionFromNextConfig = (process.env const devToolsInitialPositionFromNextConfig = (process.env
.__NEXT_DEV_INDICATOR_POSITION ?? 'bottom-left') as Corners .__NEXT_DEV_INDICATOR_POSITION ?? 'bottom-left') as Corners
const hasInstantTestCookie = const hasInstantNavsCookie =
!!process.env.__NEXT_INSTANT_NAV_TOGGLE && !!process.env.__NEXT_INSTANT_NAV_TOGGLE &&
typeof document !== 'undefined' && typeof document !== 'undefined' &&
document.cookie.includes('next-instant-navigation-testing=') document.cookie.includes('next-instant-navigation-testing=')
...@@ -291,10 +321,10 @@ export const INITIAL_OVERLAY_STATE: Omit< ...@@ -291,10 +321,10 @@ export const INITIAL_OVERLAY_STATE: Omit<
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. Otherwise the surface would flicker because the disabled flag loads from the config.
*/ */
// When cache-only is active, show the indicator immediately so the user // When instant nav is active, show the indicator immediately so the user
// can toggle it off. Normally this is set to true by the HMR connection, // can toggle it off. Normally this is set to true by the HMR connection,
// but the HMR WebSocket is only created during hydration. // but the HMR WebSocket is only created during hydration.
showIndicator: hasInstantTestCookie, showIndicator: hasInstantNavsCookie,
disableDevIndicator: false, disableDevIndicator: false,
buildingIndicator: false, buildingIndicator: false,
refreshState: { type: 'idle' }, refreshState: { type: 'idle' },
...@@ -309,7 +339,16 @@ export const INITIAL_OVERLAY_STATE: Omit< ...@@ -309,7 +339,16 @@ export const INITIAL_OVERLAY_STATE: Omit<
page: '', page: '',
theme: 'system', theme: 'system',
hideShortcut: null, hideShortcut: null,
cacheOnly: hasInstantTestCookie, instantNavs: hasInstantNavsCookie,
instantNavsPanel: hasInstantNavsCookie
? {
status: 'initial-load',
toUrl:
typeof window !== 'undefined'
? window.location.pathname + window.location.search
: '',
}
: { status: 'waiting' },
} }
function getInitialState( function getInitialState(
...@@ -523,8 +562,30 @@ export function useErrorOverlayReducer( ...@@ -523,8 +562,30 @@ export function useErrorOverlayReducer(
hideShortcut !== undefined ? hideShortcut : state.hideShortcut, hideShortcut !== undefined ? hideShortcut : state.hideShortcut,
} }
} }
case ACTION_CACHE_ONLY_TOGGLE: { case ACTION_INSTANT_NAVS_TOGGLE: {
return { ...state, cacheOnly: !state.cacheOnly } return { ...state, instantNavs: !state.instantNavs }
}
case ACTION_INSTANT_NAVS_SET_STATUS: {
return {
...state,
instantNavsPanel:
action.status === 'waiting'
? { status: 'waiting' }
: action.status === 'initial-load'
? { status: 'initial-load', toUrl: action.toUrl }
: {
status: 'client-nav',
fromUrl: action.fromUrl,
toUrl: action.toUrl,
},
}
}
case ACTION_INSTANT_NAVS_RESET: {
return {
...state,
instantNavs: false,
instantNavsPanel: { status: 'waiting' },
}
} }
default: { default: {
return state return state
......
...@@ -8,7 +8,9 @@ import { ...@@ -8,7 +8,9 @@ import {
ACTION_BUILDING_INDICATOR_HIDE, ACTION_BUILDING_INDICATOR_HIDE,
ACTION_BUILDING_INDICATOR_SHOW, ACTION_BUILDING_INDICATOR_SHOW,
ACTION_CACHE_INDICATOR, ACTION_CACHE_INDICATOR,
ACTION_CACHE_ONLY_TOGGLE, ACTION_INSTANT_NAVS_TOGGLE,
ACTION_INSTANT_NAVS_SET_STATUS,
ACTION_INSTANT_NAVS_RESET,
ACTION_DEBUG_INFO, ACTION_DEBUG_INFO,
ACTION_DEV_INDICATOR, ACTION_DEV_INDICATOR,
ACTION_DEV_INDICATOR_SET, ACTION_DEV_INDICATOR_SET,
...@@ -84,7 +86,9 @@ export function useStorybookOverlayReducer(initialState?: OverlayState) { ...@@ -84,7 +86,9 @@ export function useStorybookOverlayReducer(initialState?: OverlayState) {
case ACTION_RENDERING_INDICATOR_HIDE: case ACTION_RENDERING_INDICATOR_HIDE:
case ACTION_RENDERING_INDICATOR_SHOW: case ACTION_RENDERING_INDICATOR_SHOW:
case ACTION_CACHE_INDICATOR: case ACTION_CACHE_INDICATOR:
case ACTION_CACHE_ONLY_TOGGLE: case ACTION_INSTANT_NAVS_TOGGLE:
case ACTION_INSTANT_NAVS_SET_STATUS:
case ACTION_INSTANT_NAVS_RESET:
case ACTION_STATIC_INDICATOR: case ACTION_STATIC_INDICATOR:
case ACTION_UNHANDLED_ERROR: case ACTION_UNHANDLED_ERROR:
case ACTION_UNHANDLED_REJECTION: case ACTION_UNHANDLED_REJECTION:
......
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>
)
}
...@@ -6,7 +6,7 @@ export default function Root({ children }: { children: ReactNode }) { ...@@ -6,7 +6,7 @@ export default function Root({ children }: { children: ReactNode }) {
style={{ style={{
fontFamily: fontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif', '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
maxWidth: 640, maxWidth: 900,
margin: '0 auto', margin: '0 auto',
padding: '2rem 1rem', padding: '2rem 1rem',
lineHeight: 1.6, lineHeight: 1.6,
......
...@@ -30,7 +30,7 @@ export default function Page() { ...@@ -30,7 +30,7 @@ export default function Page() {
</ol> </ol>
<nav style={{ marginTop: '1.5rem' }}> <nav style={{ marginTop: '1.5rem' }}>
<Link <Link
href="/target-page" href="/target-page/my-post?search=foo"
id="link-to-target" id="link-to-target"
style={{ style={{
display: 'inline-block', display: 'inline-block',
......
'use client'
import { Suspense } from 'react'
import { useSearchParams, usePathname, useParams } from 'next/navigation'
function Box({
label,
children,
}: {
label: string
children: React.ReactNode
}) {
return (
<div
style={{
background: '#fff',
border: '1px solid #ddd',
borderRadius: 8,
padding: '1rem',
marginBottom: '0.75rem',
}}
>
<div
style={{
fontSize: '0.7rem',
textTransform: 'uppercase',
letterSpacing: '0.05em',
color: '#888',
marginBottom: '0.5rem',
}}
>
{label}
</div>
{children}
</div>
)
}
function PathnameDisplay() {
const pathname = usePathname()
return (
<p style={{ margin: 0 }}>
<code>{pathname}</code>
</p>
)
}
function ParamsDisplay() {
const params = useParams()
return (
<p style={{ margin: 0 }} data-testid="client-params">
<code>slug={String(params.slug ?? '(none)')}</code>
</p>
)
}
function SearchParamsDisplay() {
const searchParams = useSearchParams()
return (
<p style={{ margin: 0 }} data-testid="client-search-param">
<code>?search={searchParams.get('search') ?? '(none)'}</code>
</p>
)
}
export function ClientFeatures() {
return (
<>
<Box label="Static Client Content">
<p style={{ margin: 0 }}>
This text is rendered by a Client Component. It is part of the JS
bundle and renders immediately.
</p>
</Box>
<Box label="usePathname()">
<Suspense
fallback={
<p style={{ margin: 0 }}>
<span
className="skeleton"
style={{
display: 'inline-block',
width: 120,
height: '1em',
verticalAlign: 'middle',
}}
/>
</p>
}
>
<PathnameDisplay />
</Suspense>
</Box>
<Box label="useParams()">
<Suspense
fallback={
<p style={{ margin: 0 }}>
<span
className="skeleton"
style={{
display: 'inline-block',
width: 120,
height: '1em',
verticalAlign: 'middle',
}}
/>
</p>
}
>
<ParamsDisplay />
</Suspense>
</Box>
<Box label="useSearchParams()">
<Suspense
fallback={
<p style={{ margin: 0 }}>
<span
className="skeleton"
style={{
display: 'inline-block',
width: 120,
height: '1em',
verticalAlign: 'middle',
}}
/>
</p>
}
>
<SearchParamsDisplay />
</Suspense>
</Box>
</>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
import Link from 'next/link'
import { ClientFeatures } from './client'
function Box({
label,
children,
}: {
label: string
children: React.ReactNode
}) {
return (
<div
style={{
background: '#fff',
border: '1px solid #ddd',
borderRadius: 8,
padding: '1rem',
marginBottom: '0.75rem',
}}
>
<div
style={{
fontSize: '0.7rem',
textTransform: 'uppercase',
letterSpacing: '0.05em',
color: '#888',
marginBottom: '0.5rem',
}}
>
{label}
</div>
{children}
</div>
)
}
async function DynamicStats() {
await connection()
const stats = [
{ label: 'Stat one', value: '123' },
{ label: 'Stat two', value: '456' },
{ label: 'Stat three', value: '789' },
]
return (
<div data-testid="dynamic-content" style={{ display: 'flex', gap: '1rem' }}>
{stats.map((s) => (
<div key={s.label} style={{ flex: 1, textAlign: 'center' }}>
<div style={{ fontSize: '1.25rem', fontWeight: 600 }}>{s.value}</div>
<div style={{ fontSize: '0.75rem', color: '#888' }}>{s.label}</div>
</div>
))}
</div>
)
}
async function SearchParamReader({
searchParams,
}: {
searchParams: Promise<{ search?: string }>
}) {
const { search } = await searchParams
return (
<p data-testid="search-param-value" style={{ margin: 0 }}>
<code>?search={search ?? '(none)'}</code>
</p>
)
}
async function ParamReader({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
return (
<p data-testid="param-value" style={{ margin: 0 }}>
<code>slug={slug}</code>
</p>
)
}
export default async function TargetPage({
params,
searchParams,
}: {
params: Promise<{ slug: string }>
searchParams: Promise<{ search?: string }>
}) {
return (
<div>
<style>{`
@keyframes shimmer {
0% { background-position: -400px 0; }
100% { background-position: 400px 0; }
}
.skeleton {
background: linear-gradient(90deg, #eee 25%, #93c5fd 50%, #eee 75%);
background-size: 800px 100%;
animation: shimmer 1.5s ease-in-out infinite;
border-radius: 4px;
}
`}</style>
<h1 style={{ marginBottom: '0.25rem' }}>Target Page</h1>
<p style={{ color: '#666', marginTop: 0 }}>
A sandbox showing Next.js features and how they behave with Instant
Navs.
</p>
<div
style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr',
gap: '1.5rem',
marginTop: '1.5rem',
}}
>
{/* Server Components (left column) */}
<div
style={{
background: '#fafafa',
border: '1px solid #e5e5e5',
borderRadius: 12,
padding: '1.25rem',
}}
>
<h2
style={{
fontSize: '0.85rem',
marginTop: 0,
marginBottom: '1rem',
textTransform: 'uppercase',
letterSpacing: '0.05em',
color: '#666',
}}
>
Server Components
</h2>
<Box label="Static Server Content">
<p style={{ margin: 0 }}>
This text is rendered by a Server Component. It is static and
renders immediately.
</p>
</Box>
<Box label="Data Fetching">
<Suspense
fallback={
<div
data-testid="dynamic-skeleton"
style={{ display: 'flex', gap: '1rem' }}
>
{['Stat one', 'Stat two', 'Stat three'].map((label) => (
<div key={label} style={{ flex: 1, textAlign: 'center' }}>
<div style={{ fontSize: '1.25rem', fontWeight: 600 }}>
<span
className="skeleton"
style={{
display: 'inline-block',
width: 48,
height: '1em',
verticalAlign: 'middle',
}}
/>
</div>
<div style={{ fontSize: '0.75rem', color: '#888' }}>
{label}
</div>
</div>
))}
</div>
}
>
<DynamicStats />
</Suspense>
</Box>
<Box label="await params">
<Suspense
fallback={
<p data-testid="param-skeleton" style={{ margin: 0 }}>
<span
className="skeleton"
style={{
display: 'inline-block',
width: 120,
height: '1em',
verticalAlign: 'middle',
}}
/>
</p>
}
>
<ParamReader params={params} />
</Suspense>
</Box>
<Box label="await searchParams">
<Suspense
fallback={
<p data-testid="search-param-skeleton" style={{ margin: 0 }}>
<span
className="skeleton"
style={{
display: 'inline-block',
width: 120,
height: '1em',
verticalAlign: 'middle',
}}
/>
</p>
}
>
<SearchParamReader searchParams={searchParams} />
</Suspense>
</Box>
</div>
{/* Client Components (right column) */}
<div
style={{
background: '#fafafa',
border: '1px solid #e5e5e5',
borderRadius: 12,
padding: '1.25rem',
}}
>
<h2
style={{
fontSize: '0.85rem',
marginTop: 0,
marginBottom: '1rem',
textTransform: 'uppercase',
letterSpacing: '0.05em',
color: '#666',
}}
>
Client Components
</h2>
<ClientFeatures />
</div>
</div>
<nav style={{ marginTop: '1.5rem' }}>
<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>
)
}
...@@ -5,7 +5,7 @@ import { ...@@ -5,7 +5,7 @@ import {
toggleDevToolsIndicatorPopover, toggleDevToolsIndicatorPopover,
} from 'next-test-utils' } from 'next-test-utils'
describe('instant-mode-toggle', () => { describe('instant-nav-panel', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
...@@ -16,18 +16,18 @@ describe('instant-mode-toggle', () => { ...@@ -16,18 +16,18 @@ describe('instant-mode-toggle', () => {
}) })
} }
async function clickInstantModeMenuItem(browser: any) { async function clickInstantNavMenuItem(browser: any) {
await browser.eval(() => { await browser.eval(() => {
const portal = [].slice const portal = [].slice
.call(document.querySelectorAll('nextjs-portal')) .call(document.querySelectorAll('nextjs-portal'))
.find((p: any) => .find((p: any) =>
p.shadowRoot.querySelector('[data-nextjs-toast]') p.shadowRoot.querySelector('[data-nextjs-toast]')
) as any ) as any
portal?.shadowRoot?.querySelector('[data-cache-only]')?.click() portal?.shadowRoot?.querySelector('[data-instant-nav]')?.click()
}) })
} }
async function getInstantModeMenuValue(browser: any): Promise<string> { async function getBadgeStatus(browser: any): Promise<string> {
return browser.eval(() => { return browser.eval(() => {
const portal = [].slice const portal = [].slice
.call(document.querySelectorAll('nextjs-portal')) .call(document.querySelectorAll('nextjs-portal'))
...@@ -36,114 +36,136 @@ describe('instant-mode-toggle', () => { ...@@ -36,114 +36,136 @@ describe('instant-mode-toggle', () => {
) as any ) as any
return ( return (
portal?.shadowRoot portal?.shadowRoot
?.querySelector('[data-cache-only]') ?.querySelector('[data-next-badge]')
?.innerText.split('\n') ?.getAttribute('data-status') || ''
.pop() || ''
) )
}) })
} }
async function getBadgeStatus(browser: any): Promise<string> { async function getPanelText(browser: any): Promise<string> {
return browser.eval(() => { return browser.eval(() => {
const portal = [].slice const portal = [].slice
.call(document.querySelectorAll('nextjs-portal')) .call(document.querySelectorAll('nextjs-portal'))
.find((p: any) => .find((p: any) =>
p.shadowRoot.querySelector('[data-nextjs-toast]') p.shadowRoot.querySelector('[data-nextjs-toast]')
) as any ) as any
return ( const panel = portal?.shadowRoot?.querySelector('.instant-nav-panel')
portal?.shadowRoot return panel?.innerText || ''
?.querySelector('[data-next-badge]') })
?.getAttribute('data-status') || '' }
)
async function hasPanelOpen(browser: any): Promise<boolean> {
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('.instant-nav-panel')
})
}
async function closePanelViaHeader(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('#_next-devtools-panel-close')?.click()
}) })
} }
it('should show "instant" status after toggling on, not stuck on "compiling"', async () => { async function openInstantNavPanel(browser: any) {
await waitForDevToolsIndicator(browser)
await toggleDevToolsIndicatorPopover(browser)
await clickInstantNavMenuItem(browser)
}
it('should open panel in waiting state and set cookie', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await clearInstantModeCookie(browser) await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]') await browser.waitForElementByCss('[data-testid="home-title"]')
// Wait for initial compilation to settle — the badge status should // Wait for initial compilation to settle
// become "none" once compilation is done and no transient status is active
await retry(async () => { await retry(async () => {
const status = await getBadgeStatus(browser) const status = await getBadgeStatus(browser)
expect(status).toBe('none') expect(status).toBe('none')
}) })
// Toggle instant mode on await openInstantNavPanel(browser)
await waitForDevToolsIndicator(browser)
await toggleDevToolsIndicatorPopover(browser)
await clickInstantModeMenuItem(browser)
// The badge status should settle to "instant", not stay on "compiling" // Panel should show waiting state with Page load and Client navigation sections
await retry(async () => { await retry(async () => {
const status = await getBadgeStatus(browser) const text = await getPanelText(browser)
expect(status).toBe('instant') expect(text).toContain('Page load')
expect(text).toContain('Client navigation')
}) })
// Cookie should be set to activate navigation lock
const cookie = await browser.eval(() => document.cookie)
expect(cookie).toContain('next-instant-navigation-testing=1')
// Clean up // Clean up
await clearInstantModeCookie(browser) await clearInstantModeCookie(browser)
}) })
it('should show "Instant mode" menu item and toggle it on', async () => { it('should show client nav state after SPA navigation', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await clearInstantModeCookie(browser) await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]')
await waitForDevToolsIndicator(browser) // Wait for initial compilation to settle (tsconfig creation triggers Fast Refresh)
await toggleDevToolsIndicatorPopover(browser)
// Verify the "Instant mode" menu item shows "Off"
await retry(async () => { await retry(async () => {
const value = await getInstantModeMenuValue(browser) const status = await getBadgeStatus(browser)
expect(value).toBe('Off') expect(status).toBe('none')
}) })
// Click to toggle on — this also closes the menu await openInstantNavPanel(browser)
await clickInstantModeMenuItem(browser)
// Verify the badge appears with data-cache-only="true" // Wait for panel to be open
await retry(async () => { await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]') expect(await hasPanelOpen(browser)).toBe(true)
const attr = await badge.getAttribute('data-cache-only') })
expect(attr).toBe('true')
// Navigate to target page via SPA (use eval to bypass overlay pointer interception)
await browser.eval(() => {
document.querySelector<HTMLAnchorElement>('#link-to-target')!.click()
}) })
// Verify the status indicator shows "Instant..." // Panel should transition to client-nav state
await retry(async () => { await retry(async () => {
const hasIndicator = await browser.hasElementByCss( const text = await getPanelText(browser)
'[data-indicator-status]' expect(text).toContain('Client navigation')
) expect(text).toContain('prefetched UI')
expect(hasIndicator).toBe(true) expect(text).toContain('Continue rendering')
}) })
// Clean up // Clean up
await clearInstantModeCookie(browser) await clearInstantModeCookie(browser)
}) })
it('should show loading skeleton during SPA navigation when instant mode is on', async () => { it('should show loading skeleton during SPA navigation when panel is open', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await clearInstantModeCookie(browser) await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]') await browser.waitForElementByCss('[data-testid="home-title"]')
// Toggle instant mode on await openInstantNavPanel(browser)
await toggleDevToolsIndicatorPopover(browser)
await clickInstantModeMenuItem(browser)
// Wait for instant mode to be active // Wait for panel to be open (instant mode is active)
await retry(async () => { await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]') expect(await hasPanelOpen(browser)).toBe(true)
const attr = await badge.getAttribute('data-cache-only')
expect(attr).toBe('true')
}) })
// Navigate to target page via SPA // Navigate to target page via SPA (use eval to bypass overlay pointer interception)
await browser.elementByCss('#link-to-target').click() await browser.eval(() => {
document.querySelector<HTMLAnchorElement>('#link-to-target')!.click()
})
// The comments skeleton should be visible (dynamic content is locked) // The data fetching skeleton should be visible (dynamic content is locked)
// while static content (heading, paragraph) is already rendered
await retry(async () => { await retry(async () => {
const skeleton = await browser.hasElementByCss( const skeleton = await browser.hasElementByCss(
'[data-testid="comments-skeleton"]' '[data-testid="dynamic-skeleton"]'
) )
expect(skeleton).toBe(true) expect(skeleton).toBe(true)
}) })
...@@ -152,37 +174,26 @@ describe('instant-mode-toggle', () => { ...@@ -152,37 +174,26 @@ describe('instant-mode-toggle', () => {
await clearInstantModeCookie(browser) await clearInstantModeCookie(browser)
}) })
it('should turn off instant mode when clicking the badge', async () => { it('should clear cookie when closing panel via X button', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
await clearInstantModeCookie(browser) await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]') await browser.waitForElementByCss('[data-testid="home-title"]')
// Toggle instant mode on via menu await openInstantNavPanel(browser)
await toggleDevToolsIndicatorPopover(browser)
await clickInstantModeMenuItem(browser)
// Verify it's on // Verify cookie is set
await retry(async () => { await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]') const cookie = await browser.eval(() => document.cookie)
const attr = await badge.getAttribute('data-cache-only') expect(cookie).toContain('next-instant-navigation-testing=')
expect(attr).toBe('true')
}) })
// Click the "Instant..." status indicator to unlock — this clears the cookie and reloads // Close panel via X button
await browser.eval(() => { await closePanelViaHeader(browser)
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 // Cookie should be cleared
await retry(async () => { await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]') const cookie = await browser.eval(() => document.cookie)
const attr = await badge.getAttribute('data-cache-only') expect(cookie).not.toContain('next-instant-navigation-testing=')
expect(attr).toBe('false')
}) })
}) })
}) })
...@@ -669,7 +669,7 @@ ...@@ -669,7 +669,7 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/development/app-dir/cache-only-toggle/cache-only-toggle.test.ts": { "test/development/app-dir/instant-navs-devtools/instant-navs-devtools.test.ts": {
"passed": [ "passed": [
"instant-mode-toggle should show \"Instant mode\" menu item and toggle it on", "instant-mode-toggle should show \"Instant mode\" menu item and toggle it on",
"instant-mode-toggle should show \"instant\" status after toggling on, not stuck on \"compiling\"", "instant-mode-toggle should show \"instant\" status after toggling on, not stuck on \"compiling\"",
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