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 {
type OverlayState,
type DispatcherEvent,
ACTION_CACHE_INDICATOR,
ACTION_CACHE_ONLY_TOGGLE,
ACTION_INSTANT_NAVS_TOGGLE,
} from './dev-overlay/shared'
import {
......@@ -74,7 +74,7 @@ export interface Dispatcher {
segmentExplorerNodeAdd(nodeState: SegmentNodeState): void
segmentExplorerNodeRemove(nodeState: SegmentNodeState): void
segmentExplorerUpdateRouteState(page: string): void
cacheOnlyToggle(): void
instantNavsToggle(): void
}
type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1]
......@@ -226,8 +226,8 @@ export const dispatcher: Dispatcher = {
dispatch({ type: ACTION_DEVTOOL_UPDATE_ROUTE_STATE, page })
}
),
cacheOnlyToggle: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_CACHE_ONLY_TOGGLE })
instantNavsToggle: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_INSTANT_NAVS_TOGGLE })
}),
}
......
......@@ -45,23 +45,16 @@ export function NextLogo({
const isCacheFilling = state.cacheIndicator === 'filling'
const isCacheBypassing = state.cacheIndicator === 'bypass'
// Determine if we should show any transient status (excluding cache bypass)
const shouldShowTransientStatus =
// Determine if we should show any status (excluding cache bypass, which renders like error badge)
const shouldShowStatus =
state.buildingIndicator || state.renderingIndicator || isCacheFilling
// Delay showing for 400ms to catch fast operations,
// and keep visible for minimum time (longer for warnings)
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 { rendered: showStatusIndicator } = useDelayedRender(shouldShowStatus, {
enterDelay: 400,
exitDelay: 500,
})
const ref = useRef<HTMLDivElement | null>(null)
const measuredWidth = useMeasureWidth(ref)
......@@ -70,8 +63,7 @@ export function NextLogo({
const currentStatus = getCurrentStatus(
state.buildingIndicator,
state.renderingIndicator,
state.cacheIndicator,
state.cacheOnly
state.cacheIndicator
)
const displayStatus = showStatusIndicator ? currentStatus : Status.None
......@@ -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] {
scale: 1;
}
......@@ -398,7 +379,6 @@ 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 }}
>
......@@ -509,20 +489,7 @@ export function NextLogo({
!state.disableDevIndicator && (
<StatusIndicator
status={displayStatus}
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
}
onClick={onTriggerClick}
/>
)}
</>
......
......@@ -7,18 +7,16 @@ export enum Status {
Compiling = 'compiling',
Prerendering = 'prerendering',
CacheBypassing = 'cache-bypassing',
Instant = 'instant',
}
export function getCurrentStatus(
buildingIndicator: boolean,
renderingIndicator: boolean,
cacheIndicator: CacheIndicatorState,
instantMode?: boolean
cacheIndicator: CacheIndicatorState
): Status {
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
if (buildingIndicator) {
return Status.Compiling
......@@ -29,30 +27,21 @@ 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,
title,
}: StatusIndicatorProps) {
export function StatusIndicator({ status, onClick }: 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
......@@ -62,7 +51,6 @@ export function StatusIndicator({
[Status.Prerendering]: '#f5a623',
[Status.Compiling]: '#f5a623',
[Status.Rendering]: '#50e3c2',
[Status.Instant]: '#fff', // White dot on blue badge background
}
if (status === Status.None) {
......@@ -172,8 +160,7 @@ export function StatusIndicator({
data-indicator-status
data-nextjs-dev-tools-button
onClick={onClick}
title={title}
aria-label={title || 'Open Next.js Dev Tools'}
aria-label={'Open Next.js Dev Tools'}
>
{statusDotColor[status] && (
<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<{
export const useRenderErrorContext = () => useContext(RenderErrorContext)
export function DevOverlay() {
const [panel, setPanel] = useState<null | PanelStateKind>(null)
const [selectedIndex, setSelectedIndex] = useState(-1)
const { state, dispatch, getSquashedHydrationErrorDetails } =
useDevOverlayContext()
const [panel, setPanel] = useState<null | PanelStateKind>(() =>
state.instantNavs ? 'instant-navs' : null
)
const triggerRef = useRef<HTMLButtonElement>(null)
return (
......
......@@ -10,6 +10,7 @@ export type PanelStateKind =
| 'route-type'
| 'segment-explorer'
| 'panel-selector'
| 'instant-navs'
export const PanelRouterContext = createContext<{
panel: PanelStateKind | null
......
......@@ -16,12 +16,12 @@ import { useDevOverlayContext } from '../../dev-overlay.browser'
import { createContext, useContext } from 'react'
import { useRenderErrorContext } from '../dev-overlay'
import {
ACTION_INSTANT_NAVS_TOGGLE,
ACTION_DEV_INDICATOR_SET,
ACTION_DEVTOOLS_POSITION,
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'
......@@ -29,6 +29,7 @@ import { UserPreferencesBody } from '../components/errors/dev-tools-indicator/de
import { useShortcuts } from '../hooks/use-shortcuts'
import { useUpdateAllPanelPositions } from '../components/devtools-indicator/devtools-indicator'
import { saveDevToolsConfig } from '../utils/save-devtools-config'
import { InstantNavsPanel } from '../components/instant-navs/instant-navs-panel'
import './panel-router.css'
const MenuPanel = () => {
......@@ -107,27 +108,20 @@ const MenuPanel = () => {
},
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',
title: 'Test instant navigation behavior.',
label: 'Instant Navs',
value: <ChevronRight />,
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)
// Set cookie to activate the navigation lock (read by
// navigation-testing-lock.ts via CookieStore change event)
document.cookie = 'next-instant-navigation-testing=1; path=/'
if (!state.instantNavs) {
dispatch({ type: ACTION_INSTANT_NAVS_TOGGLE })
}
setPanel('instant-navs')
},
attributes: {
'data-cache-only': true,
'data-instant-nav': true,
},
},
isAppRouter && {
......@@ -269,6 +263,22 @@ export const PanelRouter = () => {
</DynamicPanel>
</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 {
readonly page: string
readonly theme: 'light' | 'dark' | 'system'
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
export type OverlayDispatch = React.Dispatch<DispatcherEvent>
......@@ -102,7 +110,9 @@ 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 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 =
'__nextjs-dev-tools-panel-position'
......@@ -219,7 +229,25 @@ interface DevToolsConfigAction {
}
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 =
......@@ -248,6 +276,8 @@ export type DispatcherEvent =
| DevIndicatorSetAction
| DevToolsConfigAction
| CacheOnlyToggleAction
| InstantNavSetStatusAction
| InstantNavResetAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: new frame + v8
......@@ -270,7 +300,7 @@ const shouldDisableDevIndicator =
const devToolsInitialPositionFromNextConfig = (process.env
.__NEXT_DEV_INDICATOR_POSITION ?? 'bottom-left') as Corners
const hasInstantTestCookie =
const hasInstantNavsCookie =
!!process.env.__NEXT_INSTANT_NAV_TOGGLE &&
typeof document !== 'undefined' &&
document.cookie.includes('next-instant-navigation-testing=')
......@@ -291,10 +321,10 @@ export const INITIAL_OVERLAY_STATE: Omit<
whether the indicator is in disabled state or not.
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,
// but the HMR WebSocket is only created during hydration.
showIndicator: hasInstantTestCookie,
showIndicator: hasInstantNavsCookie,
disableDevIndicator: false,
buildingIndicator: false,
refreshState: { type: 'idle' },
......@@ -309,7 +339,16 @@ export const INITIAL_OVERLAY_STATE: Omit<
page: '',
theme: 'system',
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(
......@@ -523,8 +562,30 @@ export function useErrorOverlayReducer(
hideShortcut !== undefined ? hideShortcut : state.hideShortcut,
}
}
case ACTION_CACHE_ONLY_TOGGLE: {
return { ...state, cacheOnly: !state.cacheOnly }
case ACTION_INSTANT_NAVS_TOGGLE: {
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: {
return state
......
......@@ -8,7 +8,9 @@ import {
ACTION_BUILDING_INDICATOR_HIDE,
ACTION_BUILDING_INDICATOR_SHOW,
ACTION_CACHE_INDICATOR,
ACTION_CACHE_ONLY_TOGGLE,
ACTION_INSTANT_NAVS_TOGGLE,
ACTION_INSTANT_NAVS_SET_STATUS,
ACTION_INSTANT_NAVS_RESET,
ACTION_DEBUG_INFO,
ACTION_DEV_INDICATOR,
ACTION_DEV_INDICATOR_SET,
......@@ -84,7 +86,9 @@ 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_INSTANT_NAVS_TOGGLE:
case ACTION_INSTANT_NAVS_SET_STATUS:
case ACTION_INSTANT_NAVS_RESET:
case ACTION_STATIC_INDICATOR:
case ACTION_UNHANDLED_ERROR:
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 }) {
style={{
fontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',
maxWidth: 640,
maxWidth: 900,
margin: '0 auto',
padding: '2rem 1rem',
lineHeight: 1.6,
......
......@@ -30,7 +30,7 @@ export default function Page() {
</ol>
<nav style={{ marginTop: '1.5rem' }}>
<Link
href="/target-page"
href="/target-page/my-post?search=foo"
id="link-to-target"
style={{
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 {
toggleDevToolsIndicatorPopover,
} from 'next-test-utils'
describe('instant-mode-toggle', () => {
describe('instant-nav-panel', () => {
const { next } = nextTestSetup({
files: __dirname,
})
......@@ -16,18 +16,18 @@ describe('instant-mode-toggle', () => {
})
}
async function clickInstantModeMenuItem(browser: any) {
async function clickInstantNavMenuItem(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()
portal?.shadowRoot?.querySelector('[data-instant-nav]')?.click()
})
}
async function getInstantModeMenuValue(browser: any): Promise<string> {
async function getBadgeStatus(browser: any): Promise<string> {
return browser.eval(() => {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
......@@ -36,114 +36,136 @@ describe('instant-mode-toggle', () => {
) as any
return (
portal?.shadowRoot
?.querySelector('[data-cache-only]')
?.innerText.split('\n')
.pop() || ''
?.querySelector('[data-next-badge]')
?.getAttribute('data-status') || ''
)
})
}
async function getBadgeStatus(browser: any): Promise<string> {
async function getPanelText(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') || ''
)
const panel = portal?.shadowRoot?.querySelector('.instant-nav-panel')
return panel?.innerText || ''
})
}
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('/')
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
// Wait for initial compilation to settle
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)
await openInstantNavPanel(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 () => {
const status = await getBadgeStatus(browser)
expect(status).toBe('instant')
const text = await getPanelText(browser)
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
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('/')
await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]')
await waitForDevToolsIndicator(browser)
await toggleDevToolsIndicatorPopover(browser)
// Verify the "Instant mode" menu item shows "Off"
// Wait for initial compilation to settle (tsconfig creation triggers Fast Refresh)
await retry(async () => {
const value = await getInstantModeMenuValue(browser)
expect(value).toBe('Off')
const status = await getBadgeStatus(browser)
expect(status).toBe('none')
})
// Click to toggle on — this also closes the menu
await clickInstantModeMenuItem(browser)
await openInstantNavPanel(browser)
// Verify the badge appears with data-cache-only="true"
// Wait for panel to be open
await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]')
const attr = await badge.getAttribute('data-cache-only')
expect(attr).toBe('true')
expect(await hasPanelOpen(browser)).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 () => {
const hasIndicator = await browser.hasElementByCss(
'[data-indicator-status]'
)
expect(hasIndicator).toBe(true)
const text = await getPanelText(browser)
expect(text).toContain('Client navigation')
expect(text).toContain('prefetched UI')
expect(text).toContain('Continue rendering')
})
// Clean up
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('/')
await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]')
// Toggle instant mode on
await toggleDevToolsIndicatorPopover(browser)
await clickInstantModeMenuItem(browser)
await openInstantNavPanel(browser)
// Wait for instant mode to be active
// Wait for panel to be open (instant mode is active)
await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]')
const attr = await badge.getAttribute('data-cache-only')
expect(attr).toBe('true')
expect(await hasPanelOpen(browser)).toBe(true)
})
// Navigate to target page via SPA
await browser.elementByCss('#link-to-target').click()
// Navigate to target page via SPA (use eval to bypass overlay pointer interception)
await browser.eval(() => {
document.querySelector<HTMLAnchorElement>('#link-to-target')!.click()
})
// The comments skeleton should be visible (dynamic content is locked)
// while static content (heading, paragraph) is already rendered
// The data fetching skeleton should be visible (dynamic content is locked)
await retry(async () => {
const skeleton = await browser.hasElementByCss(
'[data-testid="comments-skeleton"]'
'[data-testid="dynamic-skeleton"]'
)
expect(skeleton).toBe(true)
})
......@@ -152,37 +174,26 @@ describe('instant-mode-toggle', () => {
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('/')
await clearInstantModeCookie(browser)
await browser.waitForElementByCss('[data-testid="home-title"]')
// Toggle instant mode on via menu
await toggleDevToolsIndicatorPopover(browser)
await clickInstantModeMenuItem(browser)
await openInstantNavPanel(browser)
// Verify it's on
// Verify cookie is set
await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]')
const attr = await badge.getAttribute('data-cache-only')
expect(attr).toBe('true')
const cookie = await browser.eval(() => document.cookie)
expect(cookie).toContain('next-instant-navigation-testing=')
})
// 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()
})
// Close panel via X button
await closePanelViaHeader(browser)
// After reload, instant mode should be off
// Cookie should be cleared
await retry(async () => {
const badge = await browser.elementByCss('[data-next-badge]')
const attr = await badge.getAttribute('data-cache-only')
expect(attr).toBe('false')
const cookie = await browser.eval(() => document.cookie)
expect(cookie).not.toContain('next-instant-navigation-testing=')
})
})
})
......@@ -669,7 +669,7 @@
"flakey": [],
"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": [
"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\"",
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