Unverified Commit e54a837e authored by Rob Pruzan's avatar Rob Pruzan Committed by GitHub

feat: new detachable panel UI (#81483)

This PR updates the devtool overlay to use a new detachable panel based
system for rendering content. Each panel can be configured to:
- drag
- resize
- close on click outside
- have min/max sizes if resizable, size if fixed


https://github.com/user-attachments/assets/982ecee3-5ef0-424e-8fcc-4c54dfadcb25
parent 0a220665
......@@ -9,6 +9,8 @@ import { fileURLToPath } from 'url'
function getAbsolutePath(value: string): any {
return dirname(require.resolve(join(value, 'package.json')))
}
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const config: StorybookConfig = {
stories: ['../src/next-devtools/**/*.stories.tsx'],
......
......@@ -18,9 +18,17 @@ import {
ACTION_RENDERING_INDICATOR_HIDE,
ACTION_RENDERING_INDICATOR_SHOW,
ACTION_DEVTOOL_UPDATE_ROUTE_STATE,
type OverlayState,
type DispatcherEvent,
} from './dev-overlay/shared'
import { startTransition, useInsertionEffect } from 'react'
import {
createContext,
startTransition,
useContext,
useInsertionEffect,
type ActionDispatch,
} from 'react'
import { createRoot } from 'react-dom/client'
import { FontStyles } from './dev-overlay/font/font-styles'
import type { HydrationErrorState } from './shared/hydration-error'
......@@ -208,14 +216,31 @@ function DevOverlayRoot({
<>
{/* Fonts can only be loaded outside the Shadow DOM. */}
<FontStyles />
<DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
/>
<DevOverlayContext
value={{
dispatch,
getSquashedHydrationErrorDetails,
state,
}}
>
<DevOverlay
// we also pass props for legacy UI
dispatch={dispatch}
state={state}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
/>
</DevOverlayContext>
</>
)
}
export const DevOverlayContext = createContext<{
state: OverlayState & {
routerType: 'pages' | 'app'
}
dispatch: ActionDispatch<[action: DispatcherEvent]>
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
}>(null!)
export const useDevOverlayContext = () => useContext(DevOverlayContext)
let isPagesMounted = false
let isAppMounted = false
......
import type { Meta, StoryObj } from '@storybook/react'
import type { OverlayState } from '../../shared'
import { DevToolsIndicator } from './devtools-indicator'
import { DevToolsIndicatorNew } from './devtools-indicator'
import { INITIAL_OVERLAY_STATE } from '../../shared'
import { withShadowPortal } from '../../storybook/with-shadow-portal'
const meta: Meta<typeof DevToolsIndicator> = {
component: DevToolsIndicator,
const meta: Meta<typeof DevToolsIndicatorNew> = {
component: DevToolsIndicatorNew,
parameters: {
layout: 'centered',
},
......@@ -37,7 +37,7 @@ const meta: Meta<typeof DevToolsIndicator> = {
}
export default meta
type Story = StoryObj<typeof DevToolsIndicator>
type Story = StoryObj<typeof DevToolsIndicatorNew>
const state: OverlayState = {
...INITIAL_OVERLAY_STATE,
......
import type { CSSProperties } from 'react'
import type { OverlayState, OverlayDispatch } from '../../shared'
import { useState } from 'react'
import { NextLogo } from './next-logo'
import { NextLogoNew } from './next-logo'
import { Toast } from '../toast'
import {
MENU_CURVE,
MENU_DURATION_MS,
} from '../errors/dev-tools-indicator/utils'
import {
ACTION_DEVTOOLS_PANEL_TOGGLE,
STORAGE_KEY_POSITION,
ACTION_DEVTOOLS_POSITION,
ACTION_DEVTOOLS_PANEL_OPEN,
ACTION_ERROR_OVERLAY_OPEN,
STORE_KEY_SHARED_PANEL_LOCATION,
STORAGE_KEY_PANEL_POSITION_PREFIX,
ACTION_DEVTOOLS_PANEL_POSITION,
} from '../../shared'
import { Draggable } from '../errors/dev-tools-indicator/draggable'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
import { usePanelRouterContext } from '../../menu/context'
import type { DevToolsIndicatorPosition } from '../errors/dev-tools-indicator/dev-tools-info/preferences'
export const INDICATOR_PADDING = 20
export function DevToolsIndicator({
state,
dispatch,
errorCount,
isBuildError,
}: {
state: OverlayState
dispatch: OverlayDispatch
errorCount: number
isBuildError: boolean
}) {
const [open, setOpen] = useState(false)
export function DevToolsIndicatorNew() {
const { state, dispatch } = useDevOverlayContext()
const { panel, setPanel, setSelectedIndex } = usePanelRouterContext()
const updateAllPanelPositions = useUpdateAllPanelPositions()
const [vertical, horizontal] = state.devToolsPosition.split('-', 2)
const enableErrorOverlayMode = () => {
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
// Open the DevTools panel to view as error overlay mode.
dispatch({ type: ACTION_DEVTOOLS_PANEL_OPEN })
}
const toggleDevToolsPanel = () => {
dispatch({ type: ACTION_DEVTOOLS_PANEL_TOGGLE })
}
return (
// TODO: why is this called a toast
<Toast
id="devtools-indicator"
data-nextjs-toast
style={
{
......@@ -54,16 +39,14 @@ export function DevToolsIndicator({
boxShadow: 'none',
[vertical]: `${INDICATOR_PADDING}px`,
[horizontal]: `${INDICATOR_PADDING}px`,
visibility:
state.isDevToolsPanelOpen || state.isErrorOverlayOpen
? 'hidden'
: 'visible',
visibility: state.isErrorOverlayOpen ? 'hidden' : 'visible',
} as CSSProperties
}
>
<Draggable
// avoids a lot of weird edge cases that would cause jank if the logo and panel were de-synced
disableDrag={panel !== null}
padding={INDICATOR_PADDING}
onDragStart={() => setOpen(false)}
position={state.devToolsPosition}
setPosition={(p) => {
dispatch({
......@@ -71,25 +54,54 @@ export function DevToolsIndicator({
devToolsPosition: p,
})
localStorage.setItem(STORAGE_KEY_POSITION, p)
updateAllPanelPositions(p)
}}
>
{/* Trigger */}
<NextLogo
aria-haspopup="menu"
aria-expanded={open}
aria-controls="nextjs-dev-tools-menu"
aria-label={`${open ? 'Close' : 'Open'} Next.js Dev Tools`}
data-nextjs-dev-tools-button
disabled={state.disableDevIndicator}
issueCount={errorCount}
onTriggerClick={toggleDevToolsPanel}
toggleErrorOverlay={enableErrorOverlayMode}
isDevBuilding={state.buildingIndicator}
isDevRendering={state.renderingIndicator}
isBuildError={isBuildError}
scale={state.scale}
<NextLogoNew
onTriggerClick={() => {
const newPanel =
panel === 'panel-selector' ? null : 'panel-selector'
setPanel(newPanel)
if (!newPanel) {
setSelectedIndex(-1)
return
}
}}
/>
</Draggable>
</Toast>
)
}
/**
* makes sure we eventually sync the panel to the logo, otherwise
* it will be jarring if the panels start appearing on the other
* side of the logo. This wont teleport the panel because the indicator
* cannot be dragged when any panel is open
*/
export const useUpdateAllPanelPositions = () => {
const { dispatch } = useDevOverlayContext()
return (position: DevToolsIndicatorPosition) => {
dispatch({
type: ACTION_DEVTOOLS_PANEL_POSITION,
devToolsPanelPosition: position,
key: STORE_KEY_SHARED_PANEL_LOCATION,
})
localStorage.setItem(STORE_KEY_SHARED_PANEL_LOCATION, position)
const panelPositionKeys = Object.keys(localStorage).filter((key) =>
key.startsWith(STORAGE_KEY_PANEL_POSITION_PREFIX)
)
panelPositionKeys.forEach((key) => {
dispatch({
type: ACTION_DEVTOOLS_PANEL_POSITION,
devToolsPanelPosition: position,
key,
})
localStorage.setItem(key, position)
})
}
}
import type { Meta, StoryObj } from '@storybook/react'
import { NextLogo } from './next-logo'
import { NextLogoNew } from './next-logo'
import { withShadowPortal } from '../../storybook/with-shadow-portal'
// TODO(rob): this storybook's configurability is broken intentionally
// it will be restored when we wrap it in the storybook context addon https://storybook.js.org/addons/storybook-react-context
const StoryBookNextLogo = (
_: {
issueCount: number
isDevBuilding: boolean
isDevRendering: boolean
} & Record<string, unknown>
) => {
return <NextLogoNew onTriggerClick={() => {}} />
}
const meta: Meta<typeof NextLogo> = {
component: NextLogo,
const meta: Meta<typeof StoryBookNextLogo> = {
component: StoryBookNextLogo,
parameters: {
layout: 'centered',
},
args: {
'aria-label': 'Open Next.js DevTools',
onClick: () => console.log('Clicked!'),
},
decorators: [withShadowPortal],
}
export default meta
type Story = StoryObj<typeof NextLogo>
type Story = StoryObj<typeof StoryBookNextLogo>
export const NoIssues: Story = {
args: {
......
import type { DevToolsScale } from '../errors/dev-tools-indicator/dev-tools-info/preferences'
import { useEffect, useRef, useState } from 'react'
import { useUpdateAnimation } from './hooks/use-update-animation'
import { useMeasureWidth } from './hooks/use-measure-width'
......@@ -7,45 +5,39 @@ import { useMinimumLoadingTimeMultiple } from './hooks/use-minimum-loading-time-
import { Cross } from '../../icons/cross'
import { Warning } from '../../icons/warning'
import { css } from '../../utils/css'
interface Props extends React.ComponentProps<'button'> {
issueCount: number
isDevBuilding: boolean
isDevRendering: boolean
isBuildError: boolean
onTriggerClick: () => void
toggleErrorOverlay: () => void
scale: DevToolsScale
}
import { useDevOverlayContext } from '../../../dev-overlay.browser'
import { useRenderErrorContext } from '../../dev-overlay'
import { ACTION_ERROR_OVERLAY_OPEN } from '../../shared'
import { usePanelRouterContext } from '../../menu/context'
import { BASE_LOGO_SIZE } from '../../utils/indicator-metrics'
const SHORT_DURATION_MS = 150
export function NextLogo({
disabled,
issueCount,
isDevBuilding,
isDevRendering,
isBuildError,
export function NextLogoNew({
onTriggerClick,
toggleErrorOverlay,
scale = 1,
...props
}: Props) {
const SIZE = 36 / scale
const hasError = issueCount > 0
...buttonProps
}: { onTriggerClick: () => void } & React.ComponentProps<'button'>) {
const { state, dispatch } = useDevOverlayContext()
const { totalErrorCount } = useRenderErrorContext()
const SIZE = BASE_LOGO_SIZE / state.scale
const { panel, triggerRef, setPanel } = usePanelRouterContext()
const isMenuOpen = panel === 'panel-selector'
const hasError = totalErrorCount > 0
const [isErrorExpanded, setIsErrorExpanded] = useState(hasError)
const [dismissed, setDismissed] = useState(false)
const newErrorDetected = useUpdateAnimation(issueCount, SHORT_DURATION_MS)
const newErrorDetected = useUpdateAnimation(
totalErrorCount,
SHORT_DURATION_MS
)
const triggerRef = useRef<HTMLButtonElement | null>(null)
const ref = useRef<HTMLDivElement | null>(null)
const measuredWidth = useMeasureWidth(ref)
const isLoading = useMinimumLoadingTimeMultiple(
isDevBuilding || isDevRendering
state.buildingIndicator || state.renderingIndicator
)
const isExpanded = isErrorExpanded || disabled
const isExpanded = isErrorExpanded || state.disableDevIndicator
const width = measuredWidth === 0 ? 'auto' : measuredWidth
useEffect(() => {
......@@ -61,7 +53,10 @@ export function NextLogo({
'--duration-short': `${SHORT_DURATION_MS}ms`,
// if the indicator is disabled, hide the badge
// also allow the "disabled" state be dismissed, as long as there are no build errors
display: disabled && (!hasError || dismissed) ? 'none' : 'block',
display:
state.disableDevIndicator && (!hasError || dismissed)
? 'none'
: 'block',
} as React.CSSProperties
}
>
......@@ -396,15 +391,25 @@ export function NextLogo({
>
<div ref={ref}>
{/* Children */}
{!disabled && (
{!state.disableDevIndicator && (
<button
id="next-logo"
ref={triggerRef}
data-next-mark
data-next-mark-loading={isLoading}
onClick={onTriggerClick}
{...props}
disabled={state.disableDevIndicator}
aria-haspopup="menu"
aria-expanded={isMenuOpen}
aria-controls="nextjs-dev-tools-menu"
aria-label={`${isMenuOpen ? 'Close' : 'Open'} Next.js Dev Tools`}
data-nextjs-dev-tools-button
{...buttonProps}
>
<NextMark isLoading={isLoading} isDevBuilding={isDevBuilding} />
<NextMark
isLoading={isLoading}
isDevBuilding={state.buildingIndicator}
/>
</button>
)}
{isExpanded && (
......@@ -412,42 +417,46 @@ export function NextLogo({
<button
data-issues-open
aria-label="Open issues overlay"
onClick={toggleErrorOverlay}
onClick={() => {
// wait this is wrong
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
setPanel(null)
}}
>
{disabled && (
{state.disableDevIndicator && (
<div data-disabled-icon>
<Warning />
</div>
)}
<AnimateCount
// Used the key to force a re-render when the count changes.
key={issueCount}
key={totalErrorCount}
animate={newErrorDetected}
data-issues-count-animation
>
{issueCount}
{totalErrorCount}
</AnimateCount>{' '}
<div>
Issue
{issueCount > 1 && (
{totalErrorCount > 1 && (
<span
aria-hidden
data-issues-count-plural
// This only needs to animate once the count changes from 1 -> 2,
// otherwise it should stay static between re-renders.
data-animate={newErrorDetected && issueCount === 2}
data-animate={newErrorDetected && totalErrorCount === 2}
>
s
</span>
)}
</div>
</button>
{!isBuildError && (
{!state.buildError && (
<button
data-issues-collapse
aria-label="Collapse issues badge"
onClick={() => {
if (disabled) {
if (state.disableDevIndicator) {
setDismissed(true)
} else {
setIsErrorExpanded(false)
......
import type { OverlayState } from '../../shared'
import { DevToolsPanelVersionInfo } from './devtools-panel-version-info'
import { css } from '../../utils/css'
import { RestartServerButton } from '../errors/error-overlay-toolbar/restart-server-button'
export function DevToolsPanelFooter({
versionInfo,
isDraggable,
showRestartServerButton,
}: {
versionInfo: OverlayState['versionInfo']
isDraggable: boolean
showRestartServerButton: boolean
}) {
const bundlerName = (
process.env.__NEXT_BUNDLER || 'WEBPACK'
).toUpperCase() as 'WEBPACK' | 'TURBOPACK' | 'RSPACK'
return (
<div
data-nextjs-devtools-panel-footer
data-nextjs-devtools-panel-draggable={isDraggable}
>
<div data-nextjs-devtools-panel-footer-tab-group>
<DevToolsPanelVersionInfo versionInfo={versionInfo} />
<div data-nextjs-devtools-panel-footer-tab>
{/* TODO: The details may change, follow up. */}
<span
data-nextjs-devtools-panel-footer-tab-bundler-name={bundlerName}
>
{bundlerName}
</span>
<span data-nextjs-devtools-panel-footer-tab-bundler-status>
enabled
</span>
</div>
</div>
{showRestartServerButton && (
<div data-nextjs-devtools-panel-footer-tab-group>
<RestartServerButton showButton={true} />
</div>
)}
</div>
)
}
export const DEVTOOLS_PANEL_FOOTER_STYLES = css`
[data-nextjs-devtools-panel-footer] {
background-color: var(--color-background-200);
display: flex;
justify-content: space-between;
align-items: center;
border-top: 1px solid var(--color-gray-400);
border-radius: 0 0 var(--rounded-xl) var(--rounded-xl);
height: auto;
}
[data-nextjs-devtools-panel-footer-tab-group] {
display: flex;
align-items: center;
}
[data-nextjs-devtools-panel-footer-tab] {
display: flex;
align-items: center;
padding: 12px;
gap: 8px;
align-self: stretch;
border-right: 1px solid var(--color-gray-400);
color: var(--color-gray-900);
font-size: 12px;
font-family: var(--font-stack-monospace);
}
[data-nextjs-devtools-panel-footer-tab-bundler-name='TURBOPACK'] {
background: linear-gradient(
to right,
var(--color-turbopack-text-red) 0%,
var(--color-turbopack-text-blue) 100%
);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
`
import type { DevToolsPanelTabType } from '../devtools-panel'
import type { Corners, OverlayState } from '../../../shared'
import type { DebugInfo } from '../../../../shared/types'
import type { ReadyRuntimeError } from '../../../utils/get-error-by-type'
import type { HydrationErrorState } from '../../../../shared/hydration-error'
import { SettingsTab } from './settings-tab'
import { IssuesTab } from './issues-tab/issues-tab'
import { SegmentsExplorerTab } from './segments-explorer-tab'
export function DevToolsPanelTab({
activeTab,
devToolsPosition,
scale,
routerType,
handlePositionChange,
handleScaleChange,
debugInfo,
runtimeErrors,
getSquashedHydrationErrorDetails,
buildError,
page,
}: {
activeTab: DevToolsPanelTabType
devToolsPosition: Corners
routerType: 'app' | 'pages'
scale: number
handlePositionChange: (e: React.ChangeEvent<HTMLSelectElement>) => void
handleScaleChange: (e: React.ChangeEvent<HTMLSelectElement>) => void
debugInfo: DebugInfo
runtimeErrors: ReadyRuntimeError[]
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
buildError: OverlayState['buildError']
page: string
}) {
switch (activeTab) {
case 'settings':
return (
<SettingsTab
devToolsPosition={devToolsPosition}
scale={scale}
handlePositionChange={handlePositionChange}
handleScaleChange={handleScaleChange}
/>
)
case 'route':
return <SegmentsExplorerTab routerType={routerType} page={page} />
case 'issues':
return (
<IssuesTab
debugInfo={debugInfo}
runtimeErrors={runtimeErrors}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
buildError={buildError}
/>
)
default:
return null
}
}
import type { DebugInfo } from '../../../../../shared/types'
import type { ErrorType } from '../../../errors/error-type-label/error-type-label'
import { ErrorMessage } from '../../../errors/error-message/error-message'
import { ErrorOverlayToolbar } from '../../../errors/error-overlay-toolbar/error-overlay-toolbar'
import { ErrorTypeLabel } from '../../../errors/error-type-label/error-type-label'
import { EnvironmentNameLabel } from '../../../errors/environment-name-label/environment-name-label'
import { IssueFeedbackButton } from '../../../errors/error-overlay-toolbar/issue-feedback-button'
import { css } from '../../../../utils/css'
// This behaves like the ErrorOverlayLayout.
export function IssuesTabContentLayout({
error,
errorType,
message,
debugInfo,
children,
errorCode,
environmentName,
}: {
error: Error & { environmentName?: string }
errorType: ErrorType
message: string
debugInfo: DebugInfo
children: React.ReactNode
errorCode?: string | null
environmentName?: string
}) {
return (
<div data-nextjs-devtools-panel-tab-issues-content-layout>
<div className="nextjs-container-errors-header">
<div
className="nextjs__container_errors__error_title"
// allow assertion in tests before error rating is implemented
data-nextjs-error-code={errorCode}
>
<span data-nextjs-error-label-group>
<ErrorTypeLabel errorType={errorType} />
{environmentName && (
<EnvironmentNameLabel environmentName={environmentName} />
)}
</span>
<ErrorOverlayToolbar
error={error}
debugInfo={debugInfo}
// TODO: Move the button inside and remove the feedback on the footer of the error overlay.
feedbackButton={
errorCode && <IssueFeedbackButton errorCode={errorCode} />
}
/>
</div>
<ErrorMessage errorMessage={message} />
</div>
{children}
</div>
)
}
// The components in this file shares the style with the Error Overlay.
export const DEVTOOLS_PANEL_TAB_ISSUES_CONTENT_LAYOUT_STYLES = css`
[data-nextjs-devtools-panel-tab-issues-content-layout] {
flex: 1;
display: flex;
flex-direction: column;
overflow-y: auto;
min-height: 0;
padding: 14px;
}
`
import type { OverlayState } from '../../../../shared'
import type { ReadyRuntimeError } from '../../../../utils/get-error-by-type'
import { Suspense, useMemo, useState } from 'react'
import { Terminal } from '../../../terminal'
import { HotlinkedText } from '../../../hot-linked-text'
import { PseudoHtmlDiff } from '../../../../container/runtime-error/component-stack-pseudo-html'
import { useFrames } from '../../../../utils/get-error-by-type'
import { CodeFrame } from '../../../code-frame/code-frame'
import { CallStack } from '../../../call-stack/call-stack'
import { NEXTJS_HYDRATION_ERROR_LINK } from '../../../../../shared/react-19-hydration-error'
import { ErrorContentSkeleton } from '../../../../container/runtime-error/error-content-skeleton'
import { css } from '../../../../utils/css'
import { getErrorTextFromBuildErrorMessage } from '../../../../container/build-error'
import { IssuesTabContentLayout } from './issues-tab-content-layout'
import type { DebugInfo } from '../../../../../shared/types'
import type { ErrorType } from '../../../errors/error-type-label/error-type-label'
import { IssuesTabEmptyContent } from './issues-tab-empty-content'
// This consists of the Build Error, Runtime Error, etc.
export function IssuesTabContent({
notes,
buildError,
hydrationWarning,
errorDetails,
activeError,
errorType,
debugInfo,
errorCode,
}: {
notes: string | null
buildError: OverlayState['buildError']
hydrationWarning: string | null
errorDetails: {
hydrationWarning: string | null
notes: string | null
reactOutputComponentDiff: string | null
} | null
activeError: ReadyRuntimeError | null
errorType: ErrorType | null
debugInfo: DebugInfo
errorCode: string | null | undefined
}) {
if (buildError) {
return <BuildError message={buildError} debugInfo={debugInfo} />
}
return (
<ErrorContent
notes={notes}
hydrationWarning={hydrationWarning}
errorDetails={errorDetails}
activeError={activeError}
errorType={errorType}
debugInfo={debugInfo}
errorCode={errorCode}
/>
)
}
function ErrorContent({
notes,
hydrationWarning,
errorDetails,
activeError,
errorType,
debugInfo,
errorCode,
}: {
notes: string | null
hydrationWarning: string | null
errorDetails: {
hydrationWarning: string | null
notes: string | null
reactOutputComponentDiff: string | null
} | null
activeError: ReadyRuntimeError | null
errorType: ErrorType | null
debugInfo: DebugInfo
errorCode: string | null | undefined
}) {
if (!activeError || !errorType) {
return <IssuesTabEmptyContent />
}
return (
<IssuesTabContentLayout
error={activeError.error}
errorType={errorType}
message={activeError.error.message}
debugInfo={debugInfo}
errorCode={errorCode}
environmentName={activeError.error.environmentName}
>
<div className="error-overlay-notes-container">
{notes ? (
<>
<p
id="nextjs__container_errors__notes"
className="nextjs__container_errors__notes"
>
{notes}
</p>
</>
) : null}
{hydrationWarning ? (
<p
id="nextjs__container_errors__link"
className="nextjs__container_errors__link"
>
<HotlinkedText
text={`See more info here: ${NEXTJS_HYDRATION_ERROR_LINK}`}
/>
</p>
) : null}
</div>
{errorDetails?.reactOutputComponentDiff ? (
<PseudoHtmlDiff
reactOutputComponentDiff={errorDetails.reactOutputComponentDiff || ''}
/>
) : null}
<Suspense fallback={<ErrorContentSkeleton />}>
<RuntimeError key={activeError.id.toString()} error={activeError} />
</Suspense>
</IssuesTabContentLayout>
)
}
/* Ported the content from container/runtime-error/index.tsx */
function RuntimeError({ error }: { error: ReadyRuntimeError }) {
const [isIgnoreListOpen, setIsIgnoreListOpen] = useState(false)
const frames = useFrames(error)
const ignoredFramesTally = useMemo(() => {
return frames.reduce((tally, frame) => tally + (frame.ignored ? 1 : 0), 0)
}, [frames])
const firstFrame = useMemo(() => {
const firstFirstPartyFrameIndex = frames.findIndex(
(entry) =>
!entry.ignored &&
Boolean(entry.originalCodeFrame) &&
Boolean(entry.originalStackFrame)
)
return frames[firstFirstPartyFrameIndex] ?? null
}, [frames])
return (
<>
{firstFrame &&
firstFrame.originalStackFrame &&
firstFrame.originalCodeFrame && (
<CodeFrame
stackFrame={firstFrame.originalStackFrame}
codeFrame={firstFrame.originalCodeFrame}
/>
)}
{frames.length > 0 && (
<CallStack
frames={frames}
isIgnoreListOpen={isIgnoreListOpen}
onToggleIgnoreList={() => setIsIgnoreListOpen(!isIgnoreListOpen)}
ignoredFramesTally={ignoredFramesTally}
/>
)}
</>
)
}
function BuildError({
message,
debugInfo,
}: {
message: string
debugInfo: DebugInfo
}) {
const error = new Error(message)
const formattedMessage = useMemo(
() => getErrorTextFromBuildErrorMessage(message) || 'Failed to compile',
[message]
)
return (
<IssuesTabContentLayout
errorType={'Build Error'}
error={error}
message={formattedMessage}
debugInfo={debugInfo}
>
<Terminal content={message} />
</IssuesTabContentLayout>
)
}
// The components in this file shares the style with the Error Overlay.
export const DEVTOOLS_PANEL_TAB_ISSUES_CONTENT_STYLES = css``
import { Warning } from '../../../../icons/warning'
import { css } from '../../../../utils/css'
export function IssuesTabEmptyContent() {
return (
<div data-nextjs-devtools-panel-tab-issues-empty>
<div data-nextjs-devtools-panel-tab-issues-empty-content>
<div data-nextjs-devtools-panel-tab-issues-empty-icon>
<Warning width={16} height={16} />
</div>
<h3 data-nextjs-devtools-panel-tab-issues-empty-title>
No Issues Found
</h3>
<p data-nextjs-devtools-panel-tab-issues-empty-subtitle>
Issues will appear here when they occur.
</p>
</div>
</div>
)
}
export const DEVTOOLS_PANEL_TAB_ISSUES_EMPTY_CONTENT_STYLES = css`
[data-nextjs-devtools-panel-tab-issues-empty] {
display: flex;
flex: 1;
padding: 12px;
min-height: 0;
}
[data-nextjs-devtools-panel-tab-issues-empty-content] {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
flex: 1;
border: 1px dashed var(--color-gray-alpha-500);
border-radius: 4px;
}
[data-nextjs-devtools-panel-tab-issues-empty-icon] {
margin-bottom: 16px;
padding: 8px;
border: 1px solid var(--color-gray-alpha-400);
border-radius: 6px;
background-color: var(--color-background-100);
display: flex;
align-items: center;
justify-content: center;
}
[data-nextjs-devtools-panel-tab-issues-empty-title] {
color: var(--color-gray-1000);
font-size: 16px;
font-weight: 500;
line-height: var(--line-height-20);
}
[data-nextjs-devtools-panel-tab-issues-empty-subtitle] {
color: var(--color-gray-900);
font-size: 14px;
line-height: var(--line-height-21);
}
`
import { css } from '../../../../utils/css'
export function IssuesTabSidebarFrameSkeleton() {
return (
<>
<div data-nextjs-devtools-panel-tab-issues-sidebar-frame-skeleton-bar="1" />
<div data-nextjs-devtools-panel-tab-issues-sidebar-frame-skeleton-bar="2" />
</>
)
}
export const DEVTOOLS_PANEL_TAB_ISSUES_SIDEBAR_FRAME_SKELETON_STYLES = css`
[data-nextjs-devtools-panel-tab-issues-sidebar-frame-skeleton-bar] {
height: var(--size-12);
border-radius: 100px;
background: linear-gradient(
90deg,
var(--color-gray-200) 25%,
var(--color-gray-100) 50%,
var(--color-gray-200) 75%
);
background-size: 200% 100%;
animation: skeleton-shimmer 1.5s ease-in-out infinite;
}
[data-nextjs-devtools-panel-tab-issues-sidebar-frame-skeleton-bar='1'] {
width: 75%;
margin-bottom: 8px;
}
[data-nextjs-devtools-panel-tab-issues-sidebar-frame-skeleton-bar='2'] {
width: 36.5%;
}
@keyframes skeleton-shimmer {
0% {
background-position: -200% 0;
}
100% {
background-position: 200% 0;
}
}
/* Respect user's motion preferences */
@media (prefers-reduced-motion: reduce) {
[data-nextjs-devtools-panel-tab-issues-sidebar-frame-skeleton-bar='1'],
[data-nextjs-devtools-panel-tab-issues-sidebar-frame-skeleton-bar='2'] {
animation: none;
background: var(--color-gray-200);
}
}
`
import type { Meta, StoryObj } from '@storybook/react'
import { useState } from 'react'
import { IssuesTabSidebar } from './issues-tab-sidebar'
import { withShadowPortal } from '../../../../storybook/with-shadow-portal'
import { runtimeErrors } from '../../../../storybook/errors'
const meta: Meta<typeof IssuesTabSidebar> = {
component: IssuesTabSidebar,
parameters: {
layout: 'centered',
},
decorators: [withShadowPortal],
}
export default meta
type Story = StoryObj<typeof IssuesTabSidebar>
const SidebarWrapper = ({
runtimeErrors: errors,
errorType,
}: {
runtimeErrors: any[]
errorType: string | null
}) => {
const [activeIdx, setActiveIdx] = useState(0)
return (
<IssuesTabSidebar
runtimeErrors={errors}
errorType={errorType}
activeIdx={activeIdx}
setActiveIndex={setActiveIdx}
/>
)
}
export const Default: Story = {
render: () => (
<SidebarWrapper runtimeErrors={runtimeErrors} errorType="runtime" />
),
}
import type { ReadyRuntimeError } from '../../../../utils/get-error-by-type'
import { Suspense, useMemo, memo } from 'react'
import { css } from '../../../../utils/css'
import { getFrameSource } from '../../../../../shared/stack-frame'
import { useFrames } from '../../../../utils/get-error-by-type'
import { getErrorTypeLabel } from '../../../../container/errors'
import { IssuesTabSidebarFrameSkeleton } from './issues-tab-sidebar-frame-skeleton'
export function IssuesTabSidebar({
runtimeErrors,
activeIdx,
setActiveIndex,
}: {
runtimeErrors: ReadyRuntimeError[]
errorType: string | null
activeIdx: number
setActiveIndex: (idx: number) => void
}) {
if (runtimeErrors.length === 0) {
return null
}
return (
<aside data-nextjs-devtools-panel-tab-issues-sidebar>
{runtimeErrors.map((runtimeError, idx) => {
const isActive = idx === activeIdx
return (
<IssuesTabSidebarFrame
key={idx}
runtimeError={runtimeError}
idx={idx}
isActive={isActive}
setActiveIndex={setActiveIndex}
/>
)
})}
</aside>
)
}
const IssuesTabSidebarFrameItem = memo(function IssuesTabSidebarFrameItem({
runtimeError,
}: {
runtimeError: ReadyRuntimeError
}) {
const frames = useFrames(runtimeError)
const firstFrame = useMemo(() => {
const firstFirstPartyFrameIndex = frames.findIndex(
(entry) =>
!entry.ignored &&
Boolean(entry.originalCodeFrame) &&
Boolean(entry.originalStackFrame)
)
return frames[firstFirstPartyFrameIndex] ?? null
}, [frames])
if (!firstFrame?.originalStackFrame) {
return null
}
const errorType = getErrorTypeLabel(runtimeError.error, runtimeError.type)
const frameSource = getFrameSource(firstFrame.originalStackFrame)
return (
<>
<span data-nextjs-devtools-panel-tab-issues-sidebar-frame-error-type>
{errorType}
</span>
<span data-nextjs-devtools-panel-tab-issues-sidebar-frame-source>
{frameSource}
</span>
</>
)
})
const IssuesTabSidebarFrame = memo(function IssuesTabSidebarFrame({
runtimeError,
idx,
isActive,
setActiveIndex,
}: {
runtimeError: ReadyRuntimeError
idx: number
isActive: boolean
setActiveIndex: (idx: number) => void
}) {
return (
<button
data-nextjs-devtools-panel-tab-issues-sidebar-frame
data-nextjs-devtools-panel-tab-issues-sidebar-frame-active={isActive}
onClick={() => setActiveIndex(idx)}
>
<Suspense fallback={<IssuesTabSidebarFrameSkeleton />}>
<IssuesTabSidebarFrameItem runtimeError={runtimeError} />
</Suspense>
</button>
)
})
export const DEVTOOLS_PANEL_TAB_ISSUES_SIDEBAR_STYLES = css`
[data-nextjs-devtools-panel-tab-issues-sidebar] {
display: flex;
flex-direction: column;
gap: 4px;
padding: 8px;
border-right: 1px solid var(--color-gray-400);
overflow-y: auto;
min-height: 0;
@media (max-width: 575px) {
max-width: 112px;
}
@media (min-width: 576px) {
max-width: 138px;
width: 100%;
}
@media (min-width: 768px) {
max-width: 172.5px;
width: 100%;
}
@media (min-width: 992px) {
max-width: 230px;
width: 100%;
}
}
[data-nextjs-devtools-panel-tab-issues-sidebar-frame] {
display: flex;
flex-direction: column;
padding: 10px 8px;
border-radius: var(--rounded-lg);
transition: background-color 0.2s ease-in-out;
&:hover {
background-color: var(--color-gray-200);
}
&:active {
background-color: var(--color-gray-300);
}
}
[data-nextjs-devtools-panel-tab-issues-sidebar-frame-active='true'] {
background-color: var(--color-gray-100);
}
[data-nextjs-devtools-panel-tab-issues-sidebar-frame-error-type] {
display: inline-block;
align-self: flex-start;
color: var(--color-gray-1000);
font-size: var(--size-14);
font-weight: 500;
line-height: var(--size-20);
}
[data-nextjs-devtools-panel-tab-issues-sidebar-frame-source] {
display: inline-block;
align-self: flex-start;
color: var(--color-gray-900);
font-size: var(--size-13);
line-height: var(--size-18);
}
/* Ellipsis for long stack frame source or small devices. */
[data-nextjs-devtools-panel-tab-issues-sidebar-frame-error-type],
[data-nextjs-devtools-panel-tab-issues-sidebar-frame-source] {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100%;
}
`
import type { OverlayState } from '../../../../shared'
import type { DebugInfo } from '../../../../../shared/types'
import type { ReadyRuntimeError } from '../../../../utils/get-error-by-type'
import type { HydrationErrorState } from '../../../../../shared/hydration-error'
import { IssuesTabSidebar } from './issues-tab-sidebar'
import { IssuesTabContent } from './issues-tab-content'
import { css } from '../../../../utils/css'
import { useActiveRuntimeError } from '../../../../hooks/use-active-runtime-error'
export function IssuesTab({
debugInfo,
runtimeErrors,
getSquashedHydrationErrorDetails,
buildError,
}: {
debugInfo: DebugInfo
runtimeErrors: ReadyRuntimeError[]
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
buildError: OverlayState['buildError']
}) {
const {
errorCode,
errorType,
hydrationWarning,
activeError,
activeIdx,
setActiveIndex,
notes,
errorDetails,
} = useActiveRuntimeError({ runtimeErrors, getSquashedHydrationErrorDetails })
return (
<div data-nextjs-devtools-panel-tab-issues>
{buildError ? null : (
<IssuesTabSidebar
runtimeErrors={runtimeErrors}
errorType={errorType}
activeIdx={activeIdx}
setActiveIndex={setActiveIndex}
/>
)}
<IssuesTabContent
buildError={buildError}
notes={notes}
hydrationWarning={hydrationWarning}
errorDetails={errorDetails}
activeError={activeError}
errorType={errorType}
debugInfo={debugInfo}
errorCode={errorCode}
/>
</div>
)
}
export const DEVTOOLS_PANEL_TAB_ISSUES_STYLES = css`
[data-nextjs-devtools-panel-tab-issues] {
display: flex;
flex: 1;
min-height: 0;
}
`
const PageSegmentTree = process.env.__NEXT_DEVTOOL_SEGMENT_EXPLORER
? (
require('../../overview/segment-explorer') as typeof import('../../overview/segment-explorer')
).PageSegmentTree
: () => null
function SegmentsExplorer({
routerType,
page,
}: React.HTMLProps<HTMLDivElement> & {
routerType: 'app' | 'pages'
page: string
}) {
const isAppRouter = routerType === 'app'
return <PageSegmentTree isAppRouter={isAppRouter} page={page} />
}
export function SegmentsExplorerTab({
routerType,
page,
}: {
routerType: 'app' | 'pages'
page: string
}) {
return <SegmentsExplorer routerType={routerType} page={page} />
}
import type { Corners } from '../../../shared'
import { useTheme } from '../hooks/use-theme'
import { Select } from '../../select/select'
import { STORAGE_KEY_THEME, NEXT_DEV_TOOLS_SCALE } from '../../../shared'
import { css } from '../../../utils/css'
import LightIcon from '../../../icons/light-icon'
import DarkIcon from '../../../icons/dark-icon'
import SystemIcon from '../../../icons/system-icon'
import EyeIcon from '../../../icons/eye-icon'
function ThemeIcon({ theme }: { theme: 'dark' | 'light' | 'system' }) {
switch (theme) {
case 'system':
return <SystemIcon />
case 'dark':
return <DarkIcon />
case 'light':
return <LightIcon />
default:
return null
}
}
export function SettingsTab({
devToolsPosition,
scale,
handlePositionChange,
handleScaleChange,
}: {
devToolsPosition: Corners
scale: number
handlePositionChange: (e: React.ChangeEvent<HTMLSelectElement>) => void
handleScaleChange: (e: React.ChangeEvent<HTMLSelectElement>) => void
}) {
const [theme, setTheme] = useTheme()
const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const portal = document.querySelector('nextjs-portal')
if (!portal) return
setTheme(e.target.value)
if (e.target.value === 'system') {
portal.classList.remove('dark')
portal.classList.remove('light')
localStorage.removeItem(STORAGE_KEY_THEME)
return
}
if (e.target.value === 'dark') {
portal.classList.add('dark')
portal.classList.remove('light')
localStorage.setItem(STORAGE_KEY_THEME, 'dark')
} else {
portal.classList.remove('dark')
portal.classList.add('light')
localStorage.setItem(STORAGE_KEY_THEME, 'light')
}
}
function handleRestartDevServer(invalidatePersistentCache: boolean) {
let endpoint = '/__nextjs_restart_dev'
if (invalidatePersistentCache) {
endpoint = '/__nextjs_restart_dev?invalidatePersistentCache'
}
fetch(endpoint, {
method: 'POST',
}).then(() => {
// TODO: poll server status and reload when the server is back up.
// https://github.com/vercel/next.js/pull/80005
})
}
function hide() {
fetch('/__nextjs_disable_dev_indicator', {
method: 'POST',
})
}
return (
<div data-nextjs-devtools-panel-settings>
<div data-nextjs-devtools-panel-settings-section>
<div data-nextjs-devtools-panel-settings-section-header>
<label htmlFor="theme">Theme</label>
<p data-nextjs-devtools-panel-settings-section-description>
Select your theme preference.
</p>
</div>
<Select
id="theme"
name="theme"
prefix={<ThemeIcon theme={theme as 'dark' | 'light' | 'system'} />}
value={theme}
onChange={handleThemeChange}
>
<option value="system">System</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</Select>
</div>
<div data-nextjs-devtools-panel-settings-section>
<div data-nextjs-devtools-panel-settings-section-header>
<label htmlFor="position">Position</label>
<p data-nextjs-devtools-panel-settings-section-description>
Adjust the placement of your dev tools.
</p>
</div>
<Select
id="position"
name="position"
value={devToolsPosition}
onChange={handlePositionChange}
>
<option value="bottom-left">Bottom Left</option>
<option value="bottom-right">Bottom Right</option>
<option value="top-left">Top Left</option>
<option value="top-right">Top Right</option>
</Select>
</div>
<div data-nextjs-devtools-panel-settings-section>
<div data-nextjs-devtools-panel-settings-section-header>
<label htmlFor="size">Size</label>
<p data-nextjs-devtools-panel-settings-section-description>
Adjust the size of your dev tools.
</p>
</div>
<Select
id="size"
name="size"
value={scale}
onChange={handleScaleChange}
>
{Object.entries(NEXT_DEV_TOOLS_SCALE).map(([key, value]) => {
return (
<option value={value} key={key}>
{key}
</option>
)
})}
</Select>
</div>
<div data-nextjs-devtools-panel-settings-section>
<div data-nextjs-devtools-panel-settings-section-header>
<label id="hide-dev-tools">Hide Dev Tools for this session</label>
<p data-nextjs-devtools-panel-settings-section-description>
Hide Dev Tools until you restart your dev server, or 1 day.
</p>
</div>
<div>
<button
aria-describedby="hide-dev-tools"
name="hide-dev-tools"
data-hide-dev-tools
data-nextjs-devtools-panel-settings-section-action-button
onClick={hide}
>
<EyeIcon />
<span>Hide</span>
</button>
</div>
</div>
<div data-nextjs-devtools-panel-settings-section>
<div data-nextjs-devtools-panel-settings-section-header>
<label>Disable Dev Tools for this project</label>
<p data-nextjs-devtools-panel-settings-section-description>
To disable this UI completely, set{' '}
<code className="dev-tools-info-code">devIndicators: false</code> in
your <code className="dev-tools-info-code">next.config</code> file.
</p>
</div>
</div>
<div data-nextjs-devtools-panel-settings-section>
<div data-nextjs-devtools-panel-settings-section-header>
<label id="restart-dev-server">Restart Dev Server</label>
<p data-nextjs-devtools-panel-settings-section-description>
Restarts the development server without needing to leave the
browser.
</p>
</div>
<div>
<button
aria-describedby="restart-dev-server"
title="Restarts the development server without needing to leave the browser."
name="restart-dev-server"
data-restart-dev-server
data-nextjs-devtools-panel-settings-section-action-button
onClick={() =>
handleRestartDevServer(/*invalidatePersistentCache*/ false)
}
>
<span>Restart</span>
</button>
</div>
</div>
{process.env.__NEXT_TURBOPACK_PERSISTENT_CACHE ? (
<div data-nextjs-devtools-panel-settings-section>
<div data-nextjs-devtools-panel-settings-section-header>
<label id="reset-bundler-cache">Reset Bundler Cache</label>
<p data-nextjs-devtools-panel-settings-section-description>
Clears the bundler cache and restarts the dev server. Helpful if
you are seeing stale errors or changes are not appearing.
</p>
</div>
<div>
<button
aria-describedby="reset-bundler-cache"
title="Clears the bundler cache and restarts the dev server. Helpful if you are seeing stale errors or changes are not appearing."
name="reset-bundler-cache"
data-reset-bundler-cache
data-nextjs-devtools-panel-settings-section-action-button
onClick={() =>
handleRestartDevServer(/*invalidatePersistentCache*/ true)
}
>
<span>Reset Cache</span>
</button>
</div>
</div>
) : null}
</div>
)
}
export const DEVTOOLS_PANEL_TAB_SETTINGS_STYLES = css`
[data-nextjs-devtools-panel-settings] {
padding: 16px;
}
[data-nextjs-devtools-panel-settings-section]:first-child {
padding-top: 0;
}
[data-nextjs-devtools-panel-settings-section] {
padding: 12px 0;
border-bottom: 1px solid var(--color-gray-400);
display: flex;
justify-content: space-between;
align-items: center;
gap: 24px;
}
[data-nextjs-devtools-panel-settings-section]:last-child {
padding-bottom: 0;
border-bottom: none;
}
[data-nextjs-devtools-panel-settings-section-header] {
margin-bottom: 0;
flex: 1;
}
[data-nextjs-devtools-panel-settings-section-header] label {
font-size: var(--size-14);
font-weight: 500;
color: var(--color-gray-1000);
margin: 0;
}
[data-nextjs-devtools-panel-settings-section-description] {
color: var(--color-gray-900);
font-size: var(--size-14);
margin: 0;
}
[data-nextjs-select],
[data-nextjs-devtools-panel-settings-section-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;
&:hover {
background: var(--color-gray-100);
}
}
[data-nextjs-select] {
&:focus-within {
outline: var(--focus-ring);
}
select {
all: unset;
}
option {
color: var(--color-gray-1000);
background: var(--color-background-100);
}
}
:global(.icon) {
width: 18px;
height: 18px;
color: #666;
}
`
import type { Meta, StoryObj } from '@storybook/react'
import { DevToolsPanelVersionInfo } from './devtools-panel-version-info'
import { withShadowPortal } from '../../storybook/with-shadow-portal'
const meta: Meta<typeof DevToolsPanelVersionInfo> = {
component: DevToolsPanelVersionInfo,
parameters: {
layout: 'centered',
},
decorators: [withShadowPortal],
}
export default meta
type Story = StoryObj<typeof DevToolsPanelVersionInfo>
// Mock version info for different scenarios
const mockVersionInfo = {
fresh: {
installed: '15.0.0',
expected: '15.0.0',
staleness: 'fresh' as const,
},
stalePatch: {
installed: '15.0.0',
expected: '15.0.1',
staleness: 'stale-patch' as const,
},
staleMinor: {
installed: '15.0.0',
expected: '15.1.0',
staleness: 'stale-minor' as const,
},
staleMajor: {
installed: '14.0.0',
expected: '15.0.0',
staleness: 'stale-major' as const,
},
stalePrerelease: {
installed: '15.0.0-canary.0',
expected: '15.0.0-canary.1',
staleness: 'stale-prerelease' as const,
},
newerThanNpm: {
installed: '15.0.0-canary.1',
expected: '15.0.0-canary.0',
staleness: 'newer-than-npm' as const,
},
unknown: {
installed: '15.0.0',
expected: '15.0.0',
staleness: 'unknown' as const,
},
}
export const Fresh: Story = {
args: {
versionInfo: mockVersionInfo.fresh,
},
}
export const StalePatch: Story = {
args: {
versionInfo: mockVersionInfo.stalePatch,
},
}
export const StaleMinor: Story = {
args: {
versionInfo: mockVersionInfo.staleMinor,
},
}
export const StaleMajor: Story = {
args: {
versionInfo: mockVersionInfo.staleMajor,
},
}
export const StalePrerelease: Story = {
args: {
versionInfo: mockVersionInfo.stalePrerelease,
},
}
export const NewerThanNpm: Story = {
args: {
versionInfo: mockVersionInfo.newerThanNpm,
},
}
export const Unknown: Story = {
args: {
versionInfo: mockVersionInfo.unknown,
},
}
import type { OverlayState } from '../../shared'
import { EclipseIcon } from '../../icons/eclipse'
import { getStaleness } from '../../../shared/version-staleness'
import { css } from '../../utils/css'
export function DevToolsPanelVersionInfo({
versionInfo,
}: {
versionInfo: OverlayState['versionInfo']
}) {
const { staleness } = versionInfo
const { text, indicatorClass, title } = getStaleness(versionInfo)
const shouldBeLink = staleness.startsWith('stale')
if (shouldBeLink) {
return (
// TODO: Make it button-like and display radix-ui Tooltip on hover.
<a
data-nextjs-devtools-panel-footer-tab
target="_blank"
rel="noopener noreferrer"
href="https://nextjs.org/docs/messages/version-staleness"
title={title}
>
<EclipseIcon data-nextjs-version-staleness-indicator={indicatorClass} />
<span>{text}</span>
</a>
)
}
return (
<div data-nextjs-devtools-panel-footer-tab title={title}>
<EclipseIcon data-nextjs-version-staleness-indicator={indicatorClass} />
<span>{text}</span>
</div>
)
}
export const DEVTOOLS_PANEL_VERSION_INFO_STYLES = css`
[data-nextjs-version-staleness-indicator='fresh'] {
fill: var(--color-green-800);
stroke: var(--color-green-300);
}
[data-nextjs-version-staleness-indicator='stale'] {
fill: var(--color-amber-800);
stroke: var(--color-amber-300);
}
[data-nextjs-version-staleness-indicator='outdated'] {
fill: var(--color-red-800);
stroke: var(--color-red-300);
}
[data-nextjs-version-staleness-indicator='unknown'] {
fill: var(--color-gray-800);
stroke: var(--color-gray-300);
}
`
import type { Meta, StoryObj } from '@storybook/react'
import type { OverlayState } from '../../shared'
import { DevToolsPanel } from './devtools-panel'
import { INITIAL_OVERLAY_STATE } from '../../shared'
import { withShadowPortal } from '../../storybook/with-shadow-portal'
import { runtimeErrors } from '../../storybook/errors'
const meta: Meta<typeof DevToolsPanel> = {
component: DevToolsPanel,
parameters: {
layout: 'centered',
},
argTypes: {},
decorators: [withShadowPortal],
}
export default meta
type Story = StoryObj<typeof DevToolsPanel>
const state: OverlayState = {
...INITIAL_OVERLAY_STATE,
routerType: 'app',
isErrorOverlayOpen: false,
isDevToolsPanelOpen: true,
versionInfo: {
installed: '15.0.0',
expected: '15.0.0',
staleness: 'fresh',
},
}
export const Default: Story = {
args: {
state,
dispatch: () => {},
issueCount: 0,
runtimeErrors: [],
getSquashedHydrationErrorDetails: () => null,
},
}
export const WithIssues: Story = {
args: {
state,
dispatch: () => {},
issueCount: runtimeErrors.length,
runtimeErrors,
getSquashedHydrationErrorDetails: () => null,
},
}
export const Turbopack: Story = {
beforeEach: () => {
process.env.__NEXT_BUNDLER = 'Turbopack'
// clean up callback function
return () => {
delete process.env.__NEXT_BUNDLER
}
},
args: {
state,
dispatch: () => {},
issueCount: 0,
runtimeErrors: [],
getSquashedHydrationErrorDetails: () => null,
},
}
export const Rspack: Story = {
beforeEach: () => {
process.env.__NEXT_BUNDLER = 'Rspack'
// clean up callback function
return () => {
delete process.env.__NEXT_BUNDLER
}
},
args: {
state,
dispatch: () => {},
issueCount: 0,
runtimeErrors: [],
getSquashedHydrationErrorDetails: () => null,
},
}
import { useState, useEffect } from 'react'
export function useSessionState<T extends string>(
key: string,
initialValue: T
): [T, (value: T) => void] {
const [value, setValue] = useState<T>(() => {
if (
typeof window !== 'undefined' &&
typeof sessionStorage !== 'undefined'
) {
const stored = sessionStorage.getItem(key)
return (stored as T) ?? initialValue
}
return initialValue
})
useEffect(() => {
if (
typeof window !== 'undefined' &&
typeof sessionStorage !== 'undefined'
) {
sessionStorage.setItem(key, value)
}
}, [key, value])
return [value, setValue]
}
......@@ -15,19 +15,19 @@
/* immediately responsive so we don't need a bespoke curve */
transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
/* todo: better var? */
border: 1px solid var(--color-gray-100);
border: 1px solid var(--color-gray-400);
}
/* start really fast because we start super hidden initially behind the panel, otherwise feels like an unintended animation delay */
.resize-container:hover ~ .resize-line {
transition: transform 0.2s cubic-bezier(0.05, 0.9, 0.2, 1); /* Fast start for animate in */
transition: transform 0.25s cubic-bezier(0.23, 1, 0.32, 0.9);
}
.resize-container.right,
.resize-container.left {
top: 0;
height: 100%;
width: 25px;
width: 22px;
cursor: ew-resize;
}
......@@ -37,97 +37,97 @@
.resize-container.top {
left: 0;
width: 100%;
height: 25px;
height: 22px;
cursor: ns-resize;
}
.resize-container.top {
top: -12px;
top: -7px;
}
.resize-container.bottom {
bottom: -12px;
bottom: -7px;
}
.resize-container.left {
left: -12px;
left: -7px;
}
.resize-container.right {
right: -12px;
right: -7px;
}
.resize-container.top-left,
.resize-container.top-right,
.resize-container.bottom-left,
.resize-container.bottom-right {
width: 32px;
height: 32px;
width: 26px;
height: 26px;
z-index: 15;
}
.resize-container.top-left {
top: -16px;
left: -16px;
top: -5px;
left: -5px;
cursor: nwse-resize;
}
.resize-container.top-right {
top: -16px;
right: -16px;
top: -5px;
right: -5px;
cursor: nesw-resize;
}
.resize-container.bottom-left {
bottom: -16px;
left: -16px;
bottom: -5px;
left: -5px;
cursor: nesw-resize;
}
.resize-container.bottom-right {
bottom: -16px;
right: -16px;
bottom: -5px;
right: -5px;
cursor: nwse-resize;
}
.resize-line.top,
.resize-line.bottom {
height: 28px;
height: 18px;
width: 100%;
background-color: var(--color-background-100);
background-color: var(--color-background-200);
}
.resize-line.left,
.resize-line.right {
width: 28px;
width: 18px;
height: 100%;
background-color: var(--color-background-100);
background-color: var(--color-background-200);
}
.resize-line.top {
top: -12px;
top: -7px;
left: calc(-1 * var(--border-left, 2px));
width: calc(100% + var(--border-horizontal, 4px));
border-radius: var(--rounded-md) var(--rounded-md) 0 0;
transform: translateY(28px);
border-radius: var(--rounded-lg) var(--rounded-lg) 0 0;
transform: translateY(18px);
}
.resize-line.bottom {
bottom: -12px;
bottom: -7px;
left: calc(-1 * var(--border-left, 2px));
width: calc(100% + var(--border-horizontal, 4px));
border-radius: 0 0 var(--rounded-md) var(--rounded-md);
transform: translateY(-28px);
border-radius: 0 0 var(--rounded-lg) var(--rounded-lg);
transform: translateY(-18px);
}
.resize-line.left {
top: calc(-1 * var(--border-top, 2px));
left: -12px;
left: -7px;
height: calc(100% + var(--border-vertical, 4px));
border-radius: var(--rounded-md) 0 0 var(--rounded-md);
transform: translateX(28px);
border-radius: var(--rounded-lg) 0 0 var(--rounded-lg);
transform: translateX(18px);
}
.resize-line.right {
top: calc(-1 * var(--border-top, 2px));
right: -12px;
right: -7px;
height: calc(100% + var(--border-vertical, 4px));
border-radius: 0 var(--rounded-md) var(--rounded-md) 0;
transform: translateX(-28px);
border-radius: 0 var(--rounded-lg) var(--rounded-lg) 0;
transform: translateX(-18px);
}
.resize-container.right:hover ~ .resize-line.right,
......@@ -149,14 +149,14 @@
* regardless of hover state
*/
.resize-container.no-hover.right:hover ~ .resize-line.right {
transform: translateX(-28px);
transform: translateX(-20px);
}
.resize-container.no-hover.left:hover ~ .resize-line.left {
transform: translateX(28px);
transform: translateX(20px);
}
.resize-container.no-hover.bottom:hover ~ .resize-line.bottom {
transform: translateY(-28px);
transform: translateY(-20px);
}
.resize-container.no-hover.top:hover ~ .resize-line.top {
transform: translateY(28px);
transform: translateY(20px);
}
......@@ -3,14 +3,20 @@ import type { Corners } from '../../../shared'
import { useResize, type ResizeDirection } from './resize-provider'
import './resize-handle.css'
const STORAGE_KEY_DIMENSIONS = 'nextjs-devtools-dimensions'
export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => {
export const ResizeHandle = ({
direction,
position,
}: {
direction: ResizeDirection
position: Corners
}) => {
const {
resizeRef,
minWidth,
minHeight,
devToolsPosition,
maxWidth,
maxHeight,
storageKey,
draggingDirection,
setDraggingDirection,
} = useResize()
......@@ -44,13 +50,13 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => {
// we block the sides of the corner its in (bottom-left has bottom and left sides blocked from resizing)
// because there shouldn't be anywhere to resize, and if the user decides to resize from that point it
// would be unhandled/slightly janky (the component would have to re-magnetic-snap after the resize)
if (devToolsPosition.split('-').includes(direction)) return false
if (position.split('-').includes(direction)) return false
// same logic as above, but the only corner resize that makes
// sense is the corner fully exposed (the opposing corner)
const isCorner = direction.includes('-')
if (isCorner) {
const opposite = getOppositeCorner(devToolsPosition)
const opposite = getOppositeCorner(position)
return direction === opposite
}
......@@ -85,8 +91,6 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => {
const element = resizeRef.current
const initialRect = element.getBoundingClientRect()
const initialLeft = element.offsetLeft
const initialTop = element.offsetTop
const startX = mouseDownEvent.clientX
const startY = mouseDownEvent.clientY
......@@ -94,25 +98,22 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => {
const deltaX = mouseMoveEvent.clientX - startX
const deltaY = mouseMoveEvent.clientY - startY
const { newWidth, newHeight, newLeft, newTop } = getNewDimensions(
const { newWidth, newHeight } = getNewDimensions(
direction,
deltaX,
deltaY,
initialRect,
initialLeft,
initialTop,
minWidth,
minHeight
minHeight,
maxWidth,
maxHeight
)
element.style.width = `${newWidth}px`
element.style.height = `${newHeight}px`
if (direction.includes('left') || direction === 'left') {
element.style.left = `${newLeft}px`
if (newWidth !== undefined) {
element.style.width = `${newWidth}px`
}
if (direction.includes('top') || direction === 'top') {
element.style.top = `${newTop}px`
if (newHeight !== undefined) {
element.style.height = `${newHeight}px`
}
}
......@@ -120,13 +121,14 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => {
setDraggingDirection(null)
document.removeEventListener('mousemove', handleMouseMove)
document.removeEventListener('mouseup', handleMouseUp)
if (!resizeRef.current) {
// possible if the user closes during drag
return
}
// invariant ref exists
const { width, height } = resizeRef.current!.getBoundingClientRect()
localStorage.setItem(
STORAGE_KEY_DIMENSIONS,
JSON.stringify({ width, height })
)
const { width, height } = resizeRef.current.getBoundingClientRect()
localStorage.setItem(storageKey, JSON.stringify({ width, height }))
}
document.addEventListener('mousemove', handleMouseMove)
document.addEventListener('mouseup', handleMouseUp)
......@@ -176,37 +178,31 @@ const getNewDimensions = (
deltaX: number,
deltaY: number,
initialRect: DOMRect,
initialLeft: number,
initialTop: number,
minWidth: number,
minHeight: number
minHeight: number,
maxWidth?: number,
maxHeight?: number
) => {
const maxWidth = window.innerWidth * 0.95
const maxHeight = window.innerHeight * 0.95
const effectiveMaxWidth = maxWidth ?? window.innerWidth * 0.95
const effectiveMaxHeight = maxHeight ?? window.innerHeight * 0.95
switch (direction) {
case 'right':
return {
newWidth: Math.min(
maxWidth,
effectiveMaxWidth,
Math.max(minWidth, initialRect.width + deltaX)
),
newHeight: initialRect.height,
newLeft: initialLeft,
newTop: initialTop,
}
case 'left': {
const newWidth = Math.min(
maxWidth,
Math.max(minWidth, initialRect.width - deltaX)
)
const widthDiff = newWidth - initialRect.width
return {
newWidth,
newWidth: Math.min(
effectiveMaxWidth,
Math.max(minWidth, initialRect.width - deltaX)
),
newHeight: initialRect.height,
newLeft: initialLeft - widthDiff,
newTop: initialTop,
}
}
......@@ -214,92 +210,70 @@ const getNewDimensions = (
return {
newWidth: initialRect.width,
newHeight: Math.min(
maxHeight,
effectiveMaxHeight,
Math.max(minHeight, initialRect.height + deltaY)
),
newLeft: initialLeft,
newTop: initialTop,
}
case 'top': {
const newHeight = Math.min(
maxHeight,
Math.max(minHeight, initialRect.height - deltaY)
)
const heightDiff = newHeight - initialRect.height
return {
newWidth: initialRect.width,
newHeight,
newLeft: initialLeft,
newTop: initialTop - heightDiff,
newHeight: Math.min(
effectiveMaxHeight,
Math.max(minHeight, initialRect.height - deltaY)
),
}
}
case 'top-left': {
const newWidth = Math.min(
maxWidth,
Math.max(minWidth, initialRect.width - deltaX)
)
const newHeight = Math.min(
maxHeight,
Math.max(minHeight, initialRect.height - deltaY)
)
const widthDiff = newWidth - initialRect.width
const heightDiff = newHeight - initialRect.height
return {
newWidth,
newHeight,
newLeft: initialLeft - widthDiff,
newTop: initialTop - heightDiff,
newWidth: Math.min(
effectiveMaxWidth,
Math.max(minWidth, initialRect.width - deltaX)
),
newHeight: Math.min(
effectiveMaxHeight,
Math.max(minHeight, initialRect.height - deltaY)
),
}
}
case 'top-right': {
const newHeight = Math.min(
maxHeight,
Math.max(minHeight, initialRect.height - deltaY)
)
const heightDiff = newHeight - initialRect.height
return {
newWidth: Math.min(
maxWidth,
effectiveMaxWidth,
Math.max(minWidth, initialRect.width + deltaX)
),
newHeight,
newLeft: initialLeft,
newTop: initialTop - heightDiff,
newHeight: Math.min(
effectiveMaxHeight,
Math.max(minHeight, initialRect.height - deltaY)
),
}
}
case 'bottom-left': {
const newWidth = Math.min(
maxWidth,
Math.max(minWidth, initialRect.width - deltaX)
)
const widthDiff = newWidth - initialRect.width
return {
newWidth,
newWidth: Math.min(
effectiveMaxWidth,
Math.max(minWidth, initialRect.width - deltaX)
),
newHeight: Math.min(
maxHeight,
effectiveMaxHeight,
Math.max(minHeight, initialRect.height + deltaY)
),
newLeft: initialLeft - widthDiff,
newTop: initialTop,
}
}
case 'bottom-right':
return {
newWidth: Math.min(
maxWidth,
effectiveMaxWidth,
Math.max(minWidth, initialRect.width + deltaX)
),
newHeight: Math.min(
maxHeight,
effectiveMaxHeight,
Math.max(minHeight, initialRect.height + deltaY)
),
newLeft: initialLeft,
newTop: initialTop,
}
default: {
direction satisfies never
......
import {
createContext,
useCallback,
useContext,
useLayoutEffect,
useState,
type RefObject,
} from 'react'
import type { Corners } from '../../../shared'
const STORAGE_KEY_DIMENSIONS = 'nextjs-devtools-dimensions'
import { STORE_KEY_SHARED_PANEL_SIZE, type Corners } from '../../../shared'
export type ResizeDirection =
| 'top'
......@@ -22,9 +22,11 @@ interface ResizeContextValue {
resizeRef: RefObject<HTMLElement | null>
minWidth: number
minHeight: number
devToolsPosition: Corners
maxWidth?: number
maxHeight?: number
draggingDirection: ResizeDirection | null
setDraggingDirection: (direction: ResizeDirection | null) => void
storageKey: string
}
const ResizeContext = createContext<ResizeContextValue>(null!)
......@@ -44,8 +46,8 @@ const constrainDimensions = (params: {
}
}
const parseResizeLocalStorage = () => {
const savedDimensions = localStorage.getItem(STORAGE_KEY_DIMENSIONS)
const parseResizeLocalStorage = (key: string) => {
const savedDimensions = localStorage.getItem(key)
if (!savedDimensions) return null
try {
const parsed = JSON.parse(savedDimensions)
......@@ -59,7 +61,7 @@ const parseResizeLocalStorage = () => {
}
return null
} catch (e) {
localStorage.removeItem(STORAGE_KEY_DIMENSIONS)
localStorage.removeItem(key)
return null
}
}
......@@ -69,7 +71,11 @@ interface ResizeProviderProps {
resizeRef: RefObject<HTMLElement | null>
minWidth?: number
minHeight?: number
maxWidth?: number
maxHeight?: number
devToolsPosition: Corners
storageKey?: string
initialSize?: { height: number; width: number }
}
children: React.ReactNode
}
......@@ -77,40 +83,73 @@ interface ResizeProviderProps {
export const ResizeProvider = ({ value, children }: ResizeProviderProps) => {
const minWidth = value.minWidth ?? 100
const minHeight = value.minHeight ?? 80
const maxWidth = value.maxWidth
const maxHeight = value.maxHeight
const [draggingDirection, setDraggingDirection] =
useState<ResizeDirection | null>(null)
const storageKey = value.storageKey ?? STORE_KEY_SHARED_PANEL_SIZE
const applyConstrainedDimensions = useCallback(() => {
if (!value.resizeRef.current) return
// this feels weird to read local storage on resize, but we don't
// track the dimensions of the container, and this is better than
// getBoundingClientReact
// an optimization if this is too expensive is to maintain the current
// container size in a ref and update it on resize, which is essentially
// what we're doing here, just dumber
if (draggingDirection !== null) {
// Don't override live resizing operation with stale cached values.
return
}
const dim = parseResizeLocalStorage(storageKey)
if (!dim) {
return
}
const { height, width } = constrainDimensions({
...dim,
minWidth: minWidth ?? 100,
minHeight: minHeight ?? 80,
})
value.resizeRef.current.style.width = `${width}px`
value.resizeRef.current.style.height = `${height}px`
return true
}, [value.resizeRef, draggingDirection, storageKey, minWidth, minHeight])
useLayoutEffect(() => {
const applyConstrainedDimensions = () => {
if (!value.resizeRef.current) return
// this feels weird to read local storage on resize, but we don't
// track the dimensions of the container, and this is better than
// getBoundingClientReact
// an optimization if this is too expensive is to maintain the current
// container size in a ref and update it on resize, which is essentially
// what we're doing here, just dumber
const dim = parseResizeLocalStorage()
if (!dim) {
return
}
const applied = applyConstrainedDimensions()
if (
!applied &&
value.resizeRef.current &&
value.initialSize?.height &&
value.initialSize.width
) {
const { height, width } = constrainDimensions({
...dim,
height: value.initialSize.height,
width: value.initialSize.width,
minWidth: minWidth ?? 100,
minHeight: minHeight ?? 80,
})
value.resizeRef.current.style.width = `${width}px`
value.resizeRef.current.style.height = `${height}px`
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
applyConstrainedDimensions()
useLayoutEffect(() => {
window.addEventListener('resize', applyConstrainedDimensions)
return () =>
window.removeEventListener('resize', applyConstrainedDimensions)
}, [value.resizeRef, minWidth, minHeight])
}, [
applyConstrainedDimensions,
value.initialSize?.height,
value.initialSize?.width,
value.resizeRef,
])
return (
<ResizeContext.Provider
......@@ -118,9 +157,11 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => {
resizeRef: value.resizeRef,
minWidth,
minHeight,
devToolsPosition: value.devToolsPosition,
maxWidth,
maxHeight,
draggingDirection,
setDraggingDirection,
storageKey,
}}
>
{children}
......
import type { Meta, StoryObj } from '@storybook/react'
import { DevToolsIndicator } from './dev-tools-indicator'
import { DevOverlayStoryWrapper } from '../../../storybook/DevOverlayStoryWrapper'
import { withShadowPortal } from '../../../storybook/with-shadow-portal'
import type { VersionInfo } from '../../../../../server/dev/parse-version-info'
import type { OverlayState } from '../../../shared'
import {
getStoredPanelPosition,
STORE_KEY_SHARED_PANEL_LOCATION,
type OverlayState,
} from '../../../shared'
const meta: Meta<typeof DevToolsIndicator> = {
component: DevToolsIndicator,
const meta: Meta<typeof DevOverlayStoryWrapper> = {
component: DevOverlayStoryWrapper,
parameters: {
layout: 'centered',
},
......@@ -36,7 +40,7 @@ const meta: Meta<typeof DevToolsIndicator> = {
}
export default meta
type Story = StoryObj<typeof DevToolsIndicator>
type Story = StoryObj<typeof DevOverlayStoryWrapper>
// Mock version info for stories
const mockVersionInfo: VersionInfo = {
......@@ -46,6 +50,9 @@ const mockVersionInfo: VersionInfo = {
const state: OverlayState = {
routerType: 'app',
devToolsPanelPosition: {
[STORE_KEY_SHARED_PANEL_LOCATION]: getStoredPanelPosition(),
},
nextId: 1,
buildError: null,
errors: [],
......@@ -59,8 +66,6 @@ const state: OverlayState = {
staticIndicator: true,
debugInfo: { devtoolsFrontendUrl: undefined },
isErrorOverlayOpen: false,
// TODO: This will be handled on the next stack——with proper story.
isDevToolsPanelOpen: false,
showRestartServerButton: false,
devToolsPosition: 'bottom-left',
scale: 1,
......@@ -68,36 +73,31 @@ const state: OverlayState = {
}
export const StaticRoute: Story = {
args: {
errorCount: 0,
state,
dispatch: () => {},
},
render: () => (
<DevOverlayStoryWrapper initialState={state} runtimeErrors={[]} />
),
}
export const DynamicRoute: Story = {
args: {
errorCount: 0,
state: {
...state,
staticIndicator: false,
},
dispatch: () => {},
},
render: () => (
<DevOverlayStoryWrapper
initialState={{ ...state, staticIndicator: false }}
runtimeErrors={[]}
/>
),
}
export const SingleError: Story = {
args: {
errorCount: 1,
state,
dispatch: () => {},
},
render: () => (
<DevOverlayStoryWrapper initialState={state} runtimeErrors={[{} as any]} />
),
}
export const MultipleErrors: Story = {
args: {
errorCount: 3,
state,
dispatch: () => {},
},
render: () => (
<DevOverlayStoryWrapper
initialState={state}
runtimeErrors={[{}, {}, {}] as any}
/>
),
}
......@@ -18,7 +18,7 @@ import { UserPreferences } from './dev-tools-info/user-preferences'
import {
MENU_CURVE,
MENU_DURATION_MS,
useClickOutside,
useClickOutsideAndEscape,
useFocusTrap,
} from './utils'
import {
......@@ -77,12 +77,12 @@ export function DevToolsIndicator({
//////////////////////////////////////////////////////////////////////////////////////
interface C {
closeMenu: () => void
closeMenu?: () => void
selectedIndex: number
setSelectedIndex: Dispatch<SetStateAction<number>>
}
const Context = createContext({} as C)
export const MenuContext = createContext({} as C)
const OVERLAYS = {
Root: 'root',
......@@ -164,7 +164,7 @@ function DevToolsPopover({
// Features to make the menu accessible
useFocusTrap(menuRef, triggerRef, isMenuOpen)
useClickOutside(menuRef, triggerRef, menuMounted, closeMenu)
useClickOutsideAndEscape(menuRef, triggerRef, menuMounted, closeMenu)
useShortcuts(hideShortcut ? { [hideShortcut]: hideDevTools } : {}, triggerRef)
useEffect(() => {
......@@ -397,7 +397,7 @@ function DevToolsPopover({
data-rendered={menuRendered}
style={popover}
>
<Context.Provider
<MenuContext.Provider
value={{
closeMenu,
selectedIndex,
......@@ -457,7 +457,7 @@ function DevToolsPopover({
/>
) : null}
</div>
</Context.Provider>
</MenuContext.Provider>
</div>
)}
</Toast>
......@@ -483,7 +483,7 @@ function ChevronRight() {
)
}
function MenuItem({
export function MenuItem({
index,
label,
value,
......@@ -500,13 +500,13 @@ function MenuItem({
}) {
const isInteractive =
typeof onClick === 'function' || typeof href === 'string'
const { closeMenu, selectedIndex, setSelectedIndex } = useContext(Context)
const { closeMenu, selectedIndex, setSelectedIndex } = useContext(MenuContext)
const selected = selectedIndex === index
function click() {
if (isInteractive) {
onClick?.()
closeMenu()
closeMenu?.()
if (href) {
window.open(href, '_blank', 'noopener, noreferrer')
}
......
import React, { useLayoutEffect, useRef } from 'react'
import { usePanelRouterContext } from '../../../../menu/context'
import { css } from '../../../../utils/css'
interface DevToolsHeaderProps {
title: React.ReactNode
children?: React.ReactNode
}
export function DevToolsHeader({
title,
children,
ref,
}: DevToolsHeaderProps & { ref?: React.Ref<HTMLDivElement> }) {
const { setPanel } = usePanelRouterContext()
const buttonRef = useRef<HTMLButtonElement>(null)
useLayoutEffect(() => {
buttonRef.current?.focus()
}, [])
return (
<div
style={{
width: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '8px 20px',
userSelect: 'none',
WebkitUserSelect: 'none',
borderBottom: '1px solid var(--color-gray-alpha-400)',
}}
ref={ref}
>
<h3
style={{
margin: 0,
fontSize: '14px',
color: 'var(--color-text-primary)',
fontWeight: 'normal',
}}
>
{title}
</h3>
{children}
<button
ref={buttonRef}
id="_next-devtools-panel-close"
className="dev-tools-info-close-button"
onClick={() => {
setPanel('panel-selector')
}}
aria-label="Close devtools panel"
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
padding: '4px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: '4px',
color: 'var(--color-gray-900)',
}}
>
<XIcon />
</button>
<style>{css`
.dev-tools-info-close-button:focus-visible {
outline: var(--focus-ring);
}
`}</style>
</div>
)
}
function XIcon({ size = 22 }: { size?: number }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</svg>
)
}
import { useRef } from 'react'
import { MENU_DURATION_MS, useClickOutside, useFocusTrap } from '../utils'
import {
MENU_DURATION_MS,
useClickOutsideAndEscape,
useFocusTrap,
} from '../utils'
import { useDelayedRender } from '../../../../hooks/use-delayed-render'
import { css } from '../../../../utils/css'
export interface DevToolsInfoPropsCore {
isOpen: boolean
......@@ -37,7 +42,7 @@ export function DevToolsInfo({
// Bring focus to close button, so the user can easily close the overlay
closeButtonRef.current?.focus()
})
useClickOutside(ref, triggerRef, mounted, close)
useClickOutsideAndEscape(ref, triggerRef, mounted, close)
if (!mounted) {
return null
......@@ -84,7 +89,7 @@ export function DevToolsInfo({
)
}
export const DEV_TOOLS_INFO_STYLES = `
export const DEV_TOOLS_INFO_STYLES = css`
[data-info-popover] {
-webkit-font-smoothing: antialiased;
display: flex;
......@@ -135,7 +140,7 @@ export const DEV_TOOLS_INFO_STYLES = `
.dev-tools-info-close-button {
all: unset;
width: 20px;
height: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
......
import type { HTMLProps } from 'react'
import type { DevToolsInfoPropsCore } from './dev-tools-info'
import type { ComponentProps, HTMLProps, RefObject } from 'react'
import { DevToolsInfo } from './dev-tools-info'
function StaticRouteContent({ routerType }: { routerType: 'pages' | 'app' }) {
function StaticRouteContent({
routerType,
...props
}: { routerType: 'pages' | 'app' } & ComponentProps<'div'>) {
return (
<article className="dev-tools-info-article">
<article className="dev-tools-info-article" {...props}>
<p className="dev-tools-info-paragraph">
The path{' '}
<code className="dev-tools-info-code">{window.location.pathname}</code>{' '}
......@@ -37,9 +39,12 @@ function StaticRouteContent({ routerType }: { routerType: 'pages' | 'app' }) {
)
}
function DynamicRouteContent({ routerType }: { routerType: 'pages' | 'app' }) {
function DynamicRouteContent({
routerType,
...props
}: { routerType: 'pages' | 'app' } & ComponentProps<'div'>) {
return (
<article className="dev-tools-info-article">
<article className="dev-tools-info-article" {...props}>
<p className="dev-tools-info-paragraph">
The path{' '}
<code className="dev-tools-info-code">{window.location.pathname}</code>{' '}
......@@ -95,7 +100,7 @@ function DynamicRouteContent({ routerType }: { routerType: 'pages' | 'app' }) {
)
}
const learnMoreLink = {
export const learnMoreLink = {
pages: {
static:
'https://nextjs.org/docs/pages/building-your-application/rendering/static-site-generation',
......@@ -110,32 +115,50 @@ const learnMoreLink = {
},
} as const
export function RouteInfoBody({
routerType,
isStaticRoute,
...props
}: {
routerType: 'pages' | 'app'
isStaticRoute: boolean
} & ComponentProps<'div'>) {
return isStaticRoute ? (
<StaticRouteContent routerType={routerType} {...props} />
) : (
<DynamicRouteContent routerType={routerType} {...props} />
)
}
export function RouteInfo({
routeType,
isOpen,
close,
routerType,
routeType,
triggerRef,
...props
}: {
routeType: 'Static' | 'Dynamic'
isOpen: boolean
close: () => void
routerType: 'pages' | 'app'
} & DevToolsInfoPropsCore &
HTMLProps<HTMLDivElement>) {
routeType: 'Static' | 'Dynamic'
triggerRef: RefObject<HTMLButtonElement | null>
} & HTMLProps<HTMLDivElement>) {
const isStaticRoute = routeType === 'Static'
const learnMore = isStaticRoute
? learnMoreLink[routerType].static
: learnMoreLink[routerType].dynamic
return (
<DevToolsInfo
title={`${routeType} Route`}
learnMoreLink={learnMore}
close={close}
isOpen={isOpen}
triggerRef={triggerRef}
{...props}
>
{isStaticRoute ? (
<StaticRouteContent routerType={routerType} />
) : (
<DynamicRouteContent routerType={routerType} />
)}
<RouteInfoBody routerType={routerType} isStaticRoute={isStaticRoute} />
</DevToolsInfo>
)
}
......
......@@ -2,16 +2,10 @@ import { DevToolsInfo, type DevToolsInfoPropsCore } from './dev-tools-info'
import { CopyButton } from '../../../copy-button'
import type { HTMLProps } from 'react'
export function TurbopackInfo(
props: DevToolsInfoPropsCore & HTMLProps<HTMLDivElement>
) {
export function TurbopackInfoBody(props: React.ComponentProps<'div'>) {
return (
<DevToolsInfo
title="Turbopack"
learnMoreLink="https://nextjs.org/docs/app/api-reference/turbopack"
{...props}
>
<article className="dev-tools-info-article">
<>
<article className="dev-tools-info-article" {...props}>
<p className="dev-tools-info-paragraph">
Turbopack is an incremental bundler optimized for JavaScript and
TypeScript, written in Rust, and built into Next.js. Turbopack can be
......@@ -96,6 +90,20 @@ export function TurbopackInfo(
</pre>
</div>
</div>
</>
)
}
export function TurbopackInfo(
props: DevToolsInfoPropsCore & HTMLProps<HTMLDivElement>
) {
return (
<DevToolsInfo
title="Turbopack"
learnMoreLink="https://nextjs.org/docs/app/api-reference/turbopack"
{...props}
>
<TurbopackInfoBody />
</DevToolsInfo>
)
}
......
......@@ -19,25 +19,56 @@ import {
import { ShortcutRecorder } from './shortcut-recorder'
export function UserPreferences({
setPosition,
position,
hide,
scale,
setScale,
hideShortcut,
setHideShortcut,
setScale,
scale,
position,
setPosition,
...props
}: {
hide: () => void
hideShortcut: string | null
setHideShortcut: (value: string | null) => void
setPosition: (position: DevToolsIndicatorPosition) => void
position: DevToolsIndicatorPosition
scale: DevToolsScale
setScale: (value: DevToolsScale) => void
} & DevToolsInfoPropsCore &
Omit<HTMLProps<HTMLDivElement>, 'size'>) {
return (
<DevToolsInfo title="Preferences" {...props}>
<UserPreferencesBody
scale={scale}
position={position}
setPosition={setPosition}
setScale={setScale}
hide={hide}
hideShortcut={hideShortcut}
setHideShortcut={setHideShortcut}
/>
</DevToolsInfo>
)
}
export function UserPreferencesBody({
hide,
hideShortcut,
setHideShortcut,
scale,
setPosition,
setScale,
position,
}: {
hide: () => void
hideShortcut: string | null
setHideShortcut: (value: string | null) => void
} & DevToolsInfoPropsCore &
Omit<HTMLProps<HTMLDivElement>, 'size'>) {
// derive initial theme from system preference
setPosition: (position: DevToolsIndicatorPosition) => void
position: DevToolsIndicatorPosition
scale: DevToolsScale
setScale: (value: DevToolsScale) => void
}) {
const [theme, setTheme] = useState(getInitialTheme())
const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
......@@ -90,7 +121,7 @@ export function UserPreferences({
}
return (
<DevToolsInfo title="Preferences" {...props}>
<>
<h2 className="dev-tools-info-section-title">General</h2>
<div className="preferences-container">
<div className="preference-section">
......@@ -257,7 +288,7 @@ export function UserPreferences({
</div>
</div>
) : null}
</DevToolsInfo>
</>
)
}
......
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
type Ref,
type RefObject,
} from 'react'
interface DragContextValue {
register: (el: HTMLElement) => void
unregister: (el: HTMLElement) => void
handles: Set<HTMLElement>
disabled: boolean
}
const DragContext = createContext<DragContextValue | null>(null)
export function DragProvider({
children,
disabled = false,
}: {
children: React.ReactNode
disabled?: boolean
}) {
const handlesRef = useRef<Set<HTMLElement>>(new Set())
const register = useCallback((el: HTMLElement) => {
handlesRef.current.add(el)
}, [])
const unregister = useCallback((el: HTMLElement) => {
handlesRef.current.delete(el)
}, [])
const value = useMemo<DragContextValue>(
() => ({ register, unregister, handles: handlesRef.current, disabled }),
[register, unregister, disabled]
)
return <DragContext.Provider value={value}>{children}</DragContext.Provider>
}
export function useDragContext() {
return useContext(DragContext)
}
export function DragHandle({
children,
ref,
...props
}: React.HTMLAttributes<HTMLDivElement> & { ref?: Ref<HTMLDivElement> }) {
const internalRef = useRef<HTMLDivElement>(null)
const ctx = useDragContext()
const setRef = useCallback(
(node: HTMLDivElement | null) => {
internalRef.current = node ?? null
if (typeof ref === 'function') {
ref(node)
} else if (ref && typeof ref === 'object') {
;(ref as RefObject<HTMLDivElement | null>).current = node
}
},
[ref]
)
useEffect(() => {
if (!ctx || !internalRef.current || ctx.disabled) return
const el = internalRef.current
ctx.register(el)
return () => ctx.unregister(el)
}, [ctx])
return (
<div
ref={setRef}
{...props}
style={{
cursor: ctx?.disabled ? 'default' : 'grab',
...(props.style || {}),
}}
>
{children}
</div>
)
}
import type { Corners } from '../../../shared'
import { useCallback, useLayoutEffect, useRef } from 'react'
import { useDragContext } from './drag-context'
interface Point {
x: number
......@@ -19,6 +20,7 @@ export function Draggable({
onDragStart,
dragHandleSelector,
disableDrag = false,
avoidZone,
...props
}: {
children: React.ReactElement
......@@ -28,9 +30,16 @@ export function Draggable({
onDragStart?: () => void
dragHandleSelector?: string
disableDrag?: boolean
style?: React.CSSProperties
avoidZone?: {
square: number
corner: Corners
padding: number
}
}) {
const { ref, animate, ...drag } = useDrag({
disabled: disableDrag,
handles: useDragContext()?.handles,
threshold: 5,
onDragStart,
onDragEnd,
......@@ -56,7 +65,6 @@ export function Draggable({
}
function onAnimationEnd({ corner }: Corner) {
// Unset drag translation
setTimeout(() => {
ref.current?.style.removeProperty('translate')
setCurrentCorner(corner)
......@@ -74,7 +82,7 @@ export function Draggable({
const min = Math.min(...distances.map((d) => d.distance))
const nearest = distances.find((d) => d.distance === min)
if (!nearest) {
// Safety fallback
// this should be guarded by an invariant, shouldn't ever happen
return { corner: currentCorner, translation: allCorners[currentCorner] }
}
return {
......@@ -94,49 +102,58 @@ export function Draggable({
const isRight = corner.includes('right')
const isBottom = corner.includes('bottom')
return {
x: isRight
? window.innerWidth - scrollbarWidth - offset - triggerWidth
: 0,
y: isBottom ? window.innerHeight - offset - triggerHeight : 0,
// Base positions flush against the chosen corner
let x = isRight
? window.innerWidth - scrollbarWidth - offset - triggerWidth
: 0
let y = isBottom ? window.innerHeight - offset - triggerHeight : 0
// Apply avoidZone offset if this corner is occupied. We only move along
// the vertical axis to keep the panel within the viewport. For bottom
// corners we move the panel up, for top corners we move it down.
if (avoidZone && avoidZone.corner === corner) {
const delta = avoidZone.square + avoidZone.padding
if (isBottom) {
// move up
y -= delta
} else {
// move down
y += delta
}
}
return { x, y }
}
const basePosition = getAbsolutePosition(currentCorner)
// Calculate all corner positions relative to the current corner
function rel(pos: Point): Point {
return {
x: pos.x - basePosition.x,
y: pos.y - basePosition.y,
}
}
return {
'top-left': {
x: 0 - basePosition.x,
y: 0 - basePosition.y,
},
'top-right': {
x:
window.innerWidth -
scrollbarWidth -
offset -
triggerWidth -
basePosition.x,
y: 0 - basePosition.y,
},
'bottom-left': {
x: 0 - basePosition.x,
y: window.innerHeight - offset - triggerHeight - basePosition.y,
},
'bottom-right': {
x:
window.innerWidth -
scrollbarWidth -
offset -
triggerWidth -
basePosition.x,
y: window.innerHeight - offset - triggerHeight - basePosition.y,
},
'top-left': rel(getAbsolutePosition('top-left')),
'top-right': rel(getAbsolutePosition('top-right')),
'bottom-left': rel(getAbsolutePosition('bottom-left')),
'bottom-right': rel(getAbsolutePosition('bottom-right')),
}
}
return (
<div {...props} ref={ref} {...drag} style={{ touchAction: 'none' }}>
<div
{...props}
ref={ref}
{...drag}
style={{
touchAction: 'none',
userSelect: 'none',
WebkitUserSelect: 'none',
...props.style,
}}
>
{children}
</div>
)
......@@ -150,6 +167,7 @@ interface UseDragOptions {
onAnimationEnd?: (corner: Corner) => void
threshold: number // Minimum movement before drag starts
dragHandleSelector?: string
handles?: Set<HTMLElement>
}
interface Velocity {
......@@ -190,6 +208,8 @@ export function useDrag(options: UseDragOptions) {
velocities.current = []
ref.current?.classList.remove('dev-tools-grabbing')
document.body.style.removeProperty('user-select')
document.body.style.removeProperty('-webkit-user-select')
}, [])
useLayoutEffect(() => {
......@@ -234,18 +254,23 @@ export function useDrag(options: UseDragOptions) {
}
function isValidDragHandle(target: EventTarget | null): boolean {
if (!options.dragHandleSelector || !ref.current || !target) {
return true // If no selector provided, entire element is draggable
}
if (!target || !ref.current) return true
const element = target as Element
if (!element.matches) {
if (options.handles && options.handles.size > 0) {
let node: HTMLElement | null = target as HTMLElement
while (node && node !== ref.current) {
if (options.handles.has(node)) return true
node = node.parentElement
}
return false
}
// Check if the target element directly matches the drag handle selector
// This excludes children elements, only allowing drag from the exact element
return element.matches(options.dragHandleSelector)
if (options.dragHandleSelector) {
const element = target as Element
return element.closest(options.dragHandleSelector) !== null
}
return true
}
function onPointerDown(e: React.PointerEvent) {
......@@ -285,6 +310,8 @@ export function useDrag(options: UseDragOptions) {
machine.current = { state: 'drag', pointerId: e.pointerId }
ref.current?.setPointerCapture(e.pointerId)
ref.current?.classList.add('dev-tools-grabbing')
document.body.style.userSelect = 'none'
document.body.style.webkitUserSelect = 'none'
options.onDragStart?.()
}
}
......@@ -328,6 +355,13 @@ export function useDrag(options: UseDragOptions) {
options.onDragEnd?.(translation.current, velocity)
}
if (options.disabled) {
return {
ref,
animate,
}
}
return {
ref,
onPointerDown,
......
import { useEffect } from 'react'
export const getShadowRoot = () => {
const portal = document.querySelector('nextjs-portal')
return portal?.shadowRoot
}
export function useFocusTrap(
rootRef: React.RefObject<HTMLElement | null>,
triggerRef: React.RefObject<HTMLButtonElement | null> | null,
......@@ -80,11 +85,12 @@ function getFocusableNodes(node: HTMLElement): [HTMLElement, HTMLElement] | [] {
//////////////////////////////////////////////////////////////////////////////////////
export function useClickOutside(
// TODO: split up escape and click outside logic
export function useClickOutsideAndEscape(
rootRef: React.RefObject<HTMLElement | null>,
triggerRef: React.RefObject<HTMLButtonElement | null>,
active: boolean,
close: () => void,
close: (reason: 'escape' | 'outside') => void,
ownerDocument?: Document
) {
useEffect(() => {
......@@ -100,32 +106,42 @@ export function useClickOutside(
return
}
const cushion = 10
if (
!(rootRef.current?.getBoundingClientRect()
? event.clientX >= rootRef.current.getBoundingClientRect()!.left &&
event.clientX <= rootRef.current.getBoundingClientRect()!.right &&
event.clientY >= rootRef.current.getBoundingClientRect()!.top &&
event.clientY <= rootRef.current.getBoundingClientRect()!.bottom
? event.clientX >=
rootRef.current.getBoundingClientRect()!.left - cushion &&
event.clientX <=
rootRef.current.getBoundingClientRect()!.right + cushion &&
event.clientY >=
rootRef.current.getBoundingClientRect()!.top - cushion &&
event.clientY <=
rootRef.current.getBoundingClientRect()!.bottom + cushion
: false) &&
!(triggerRef.current?.getBoundingClientRect()
? event.clientX >= triggerRef.current.getBoundingClientRect()!.left &&
? event.clientX >=
triggerRef.current.getBoundingClientRect()!.left - cushion &&
event.clientX <=
triggerRef.current.getBoundingClientRect()!.right &&
event.clientY >= triggerRef.current.getBoundingClientRect()!.top &&
event.clientY <= triggerRef.current.getBoundingClientRect()!.bottom
triggerRef.current.getBoundingClientRect()!.right + cushion &&
event.clientY >=
triggerRef.current.getBoundingClientRect()!.top - cushion &&
event.clientY <=
triggerRef.current.getBoundingClientRect()!.bottom + cushion
: false)
) {
close()
close('outside')
}
}
function handleKeyDown(event: KeyboardEvent) {
if (event.key === 'Escape') {
close()
close('escape')
}
}
ownerDocumentEl?.addEventListener('mousedown', handleClickOutside)
ownerDocumentEl?.addEventListener('keydown', handleKeyDown)
return () => {
......
import { css } from '../../../utils/css'
import { Overlay, type OverlayProps } from '../../overlay/overlay'
export function ErrorOverlayOverlay({ children, ...props }: OverlayProps) {
return <Overlay {...props}>{children}</Overlay>
}
export const OVERLAY_STYLES = `
export const OVERLAY_STYLES = css`
[data-nextjs-dialog-overlay] {
padding: initial;
top: 10vh;
......
const styles = `
import { css } from '../../utils/css'
const styles = css`
[data-nextjs-dialog-overlay] {
position: fixed;
top: 0;
......
......@@ -3,7 +3,7 @@ import { useCallback, useState, useRef, useMemo } from 'react'
import { Menu } from '@base-ui-components/react/menu'
import type { SegmentNodeState } from '../../../userspace/app/segment-explorer-node'
import { normalizeBoundaryFilename } from '../../../../server/app-render/segment-explorer-path'
import { useClickOutside } from '../errors/dev-tools-indicator/utils'
import { useClickOutsideAndEscape } from '../errors/dev-tools-indicator/utils'
const composeRefs = (...refs: (React.Ref<HTMLButtonElement> | undefined)[]) => {
return (node: HTMLButtonElement | null) => {
......@@ -39,7 +39,7 @@ export function SegmentBoundaryTrigger({
const popupRef = useRef<HTMLDivElement>(null)
// Click outside of popup should close the menu
useClickOutside(
useClickOutsideAndEscape(
popupRef,
triggerRef,
isOpen,
......
.segment-explorer-content {
font-size: var(--size-14);
padding: 0 8px;
width: 700px;
height: 400px;
max-width: calc(100vw - 40px);
max-height: calc(100vh - 240px);
width: 100%;
height: 100%;
overflow: auto;
}
.segment-explorer-page-route-bar {
......@@ -132,7 +131,6 @@
.segment-explorer-footer {
padding: 8px;
border-top: 1px solid var(--color-gray-400);
background-color: var(--color-background-100);
user-select: none;
}
......
......@@ -118,11 +118,22 @@ export function PageSegmentTree({
}, [tree, isAppRouter])
return (
<div data-nextjs-devtools-panel-segments-explorer>
<div
data-nextjs-devtools-panel-segments-explorer
style={{
display: 'flex',
flexDirection: 'column',
height: '100%',
}}
>
{isAppRouter && <PageRouteBar page={page} />}
<div
className="segment-explorer-content"
data-nextjs-devtool-segment-explorer
style={{
flex: '1 1 auto',
overflow: 'auto',
}}
>
{isAppRouter ? (
<PageSegmentTreeLayerPresentation node={tree} level={0} segment="" />
......
......@@ -16,6 +16,7 @@ const meta: Meta<typeof Errors> = {
export default meta
type Story = StoryObj<typeof Errors>
// todo: update the stories to be wrapped in context providers necessary, instead of passing props directly, before they expected props
export const Default: Story = {
args: {
getSquashedHydrationErrorDetails: () => null,
......
......@@ -10,6 +10,8 @@ import {
storybookDefaultOverlayState,
useStorybookOverlayReducer,
} from './storybook/use-overlay-reducer'
import { DevOverlayContext } from '../dev-overlay.browser'
import { getSquashedHydrationErrorDetails } from '../userspace/pages/hydration-error-state'
const meta: Meta<typeof DevOverlay> = {
component: DevOverlay,
......@@ -39,14 +41,20 @@ function getNoSquashedHydrationErrorDetails() {
const initialState: OverlayState = {
...storybookDefaultOverlayState,
errors,
errors: errors,
}
export const Default: Story = {
render: function DevOverlayStory() {
const [state, dispatch] = useStorybookOverlayReducer(initialState)
return (
<>
<div
style={{
height: '100vh',
backgroundColor: 'black',
}}
>
{/* TODO: get lots of real hard examples so we have better debug */}
<img
src={imgApp}
style={{
......@@ -55,19 +63,26 @@ export const Default: Story = {
objectFit: 'contain',
}}
/>
<DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={
// Testing like App Router where we no longer quash hydration errors
getNoSquashedHydrationErrorDetails
}
/>
</>
<DevOverlayContext
value={{
dispatch,
getSquashedHydrationErrorDetails:
getNoSquashedHydrationErrorDetails,
state,
}}
>
<DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
/>
</DevOverlayContext>
</div>
)
},
}
// todo: fix story with "Context arg provider" wrapper
export const WithPanel: Story = {
beforeEach: () => {
process.env.__NEXT_DEVTOOL_NEW_PANEL_UI = 'true'
......@@ -89,14 +104,20 @@ export const WithPanel: Story = {
objectFit: 'contain',
}}
/>
<DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={
// Testing like App Router where we no longer quash hydration errors
getNoSquashedHydrationErrorDetails
}
/>
<DevOverlayContext
value={{
dispatch,
getSquashedHydrationErrorDetails:
getNoSquashedHydrationErrorDetails,
state,
}}
>
<DevOverlay
dispatch={dispatch}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
state={state}
/>
</DevOverlayContext>
</>
)
},
......
import {
ACTION_DEVTOOLS_PANEL_OPEN,
ACTION_ERROR_OVERLAY_OPEN,
type OverlayDispatch,
type OverlayState,
} from './shared'
import { useState } from 'react'
import { createContext, useContext, useRef, useState } from 'react'
import { ShadowPortal } from './components/shadow-portal'
import { Base } from './styles/base'
import { ComponentStyles } from './styles/component-styles'
......@@ -18,8 +10,18 @@ import { RenderError } from './container/runtime-error/render-error'
import { DarkTheme } from './styles/dark-theme'
import { useDevToolsScale } from './components/errors/dev-tools-indicator/dev-tools-info/preferences'
import type { HydrationErrorState } from '../shared/hydration-error'
import { DevToolsIndicator as DevToolsIndicatorNew } from './components/devtools-indicator/devtools-indicator'
import { DevToolsPanel } from './components/devtools-panel/devtools-panel'
import type { ReadyRuntimeError } from './utils/get-error-by-type'
import { DevToolsIndicatorNew } from './components/devtools-indicator/devtools-indicator'
import { PanelRouter } from './menu/panel-router'
import { PanelRouterContext, type PanelStateKind } from './menu/context'
import type { OverlayState, OverlayDispatch } from './shared'
export const RenderErrorContext = createContext<{
runtimeErrors: ReadyRuntimeError[]
totalErrorCount: number
}>(null!)
export const useRenderErrorContext = () => useContext(RenderErrorContext)
export function DevOverlay({
state,
......@@ -31,23 +33,11 @@ export function DevOverlay({
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
}) {
const [scale, setScale] = useDevToolsScale()
const [isPrevBuildError, setIsPrevBuildError] = useState(false)
const [panel, setPanel] = useState<null | PanelStateKind>(null)
const isBuildError = state.buildError !== null
const [selectedIndex, setSelectedIndex] = useState(-1)
if (
process.env.__NEXT_DEVTOOL_NEW_PANEL_UI &&
isBuildError !== isPrevBuildError
) {
// If the build error is set, enable the devtools panel as the error overlay mode,
// and the rest actions (close, minimize, fullscreen) can be handled by the user.
if (isBuildError) {
dispatch({ type: ACTION_DEVTOOLS_PANEL_OPEN })
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
}
setIsPrevBuildError(isBuildError)
}
const triggerRef = useRef<HTMLButtonElement>(null)
return (
<ShadowPortal>
<CssReset />
......@@ -63,50 +53,56 @@ export function DevOverlay({
return (
<>
{state.showIndicator &&
(process.env.__NEXT_DEVTOOL_NEW_PANEL_UI ? (
<>
<DevToolsIndicatorNew
state={state}
dispatch={dispatch}
errorCount={totalErrorCount}
isBuildError={isBuildError}
/>
{(state.isDevToolsPanelOpen ||
state.isErrorOverlayOpen) && (
<DevToolsPanel
process.env.__NEXT_DEVTOOL_NEW_PANEL_UI ? (
<>
<RenderErrorContext
value={{ runtimeErrors, totalErrorCount }}
>
<PanelRouterContext
value={{
panel,
setPanel,
triggerRef,
selectedIndex,
setSelectedIndex,
}}
>
<ErrorOverlay
state={state}
dispatch={dispatch}
issueCount={totalErrorCount}
runtimeErrors={runtimeErrors}
getSquashedHydrationErrorDetails={
getSquashedHydrationErrorDetails
}
runtimeErrors={runtimeErrors}
errorCount={totalErrorCount}
/>
)}
</>
) : (
<>
<DevToolsIndicator
scale={scale}
setScale={setScale}
state={state}
dispatch={dispatch}
errorCount={totalErrorCount}
isBuildError={isBuildError}
/>
<PanelRouter />
<DevToolsIndicatorNew />
</PanelRouterContext>
</RenderErrorContext>
</>
) : (
<>
<DevToolsIndicator
scale={scale}
setScale={setScale}
state={state}
dispatch={dispatch}
errorCount={totalErrorCount}
isBuildError={isBuildError}
/>
<ErrorOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={
getSquashedHydrationErrorDetails
}
runtimeErrors={runtimeErrors}
errorCount={totalErrorCount}
/>
</>
))}
<ErrorOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={
getSquashedHydrationErrorDetails
}
runtimeErrors={runtimeErrors}
errorCount={totalErrorCount}
/>
</>
)}
</>
)
}}
......
......@@ -39,7 +39,9 @@ export function useShortcuts(
}, [shortcuts])
}
function isFocusedOnElement(rootRef: React.RefObject<HTMLElement | null>) {
export function isFocusedOnElement(
rootRef: React.RefObject<HTMLElement | null>
) {
const el = getActiveElement(rootRef.current)
if (!el) return false
......
import {
createContext,
useContext,
type Dispatch,
type SetStateAction,
} from 'react'
export type PanelStateKind =
| 'preferences'
| 'route-type'
| 'segment-explorer'
| 'panel-selector'
| 'turbo-info'
export const PanelRouterContext = createContext<{
panel: PanelStateKind | null
setPanel: Dispatch<SetStateAction<PanelStateKind | null>>
triggerRef: React.RefObject<HTMLButtonElement | null>
selectedIndex: number
setSelectedIndex: Dispatch<SetStateAction<number>>
}>(null!)
export const usePanelRouterContext = () => useContext(PanelRouterContext)
import { useDevOverlayContext } from '../../dev-overlay.browser'
import { useClickOutsideAndEscape } from '../components/errors/dev-tools-indicator/utils'
import { useLayoutEffect, useRef, type CSSProperties } from 'react'
import { getIndicatorOffset } from '../utils/indicator-metrics'
import { INDICATOR_PADDING } from '../components/devtools-indicator/devtools-indicator'
import {
MenuContext,
MenuItem,
} from '../components/errors/dev-tools-indicator/dev-tools-indicator'
import { usePanelRouterContext } from './context'
import { usePanelContext } from './panel-router'
export const DevtoolMenu = ({
closeOnClickOutside = true,
items,
}: {
closeOnClickOutside?: boolean
items: Array<
| false
| undefined
| null
| {
onClick?: () => void
title?: string
label: string
value: React.ReactNode
attributes?: Record<string, string | boolean>
footer?: boolean
}
>
}) => {
const { state } = useDevOverlayContext()
const { setPanel, triggerRef, setSelectedIndex, selectedIndex } =
usePanelRouterContext()
const { mounted } = usePanelContext()
const [vertical, horizontal] = state.devToolsPosition.split('-', 2)
const menuRef = useRef<HTMLDivElement>(null)
useClickOutsideAndEscape(
menuRef,
triggerRef,
closeOnClickOutside && mounted,
(reason) => {
switch (reason) {
case 'escape': {
setPanel(null)
setSelectedIndex(-1)
return
}
case 'outside': {
if (!closeOnClickOutside) {
return
}
setPanel(null)
setSelectedIndex(-1)
return
}
default: {
return null!
}
}
}
)
useLayoutEffect(() => {
menuRef.current?.focus() // allows keydown to be captured
selectMenuItem({
index: selectedIndex === -1 ? 'first' : selectedIndex,
menuRef,
setSelectedIndex,
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const indicatorOffset = getIndicatorOffset(state)
const [indicatorVertical, indicatorHorizontal] = state.devToolsPosition.split(
'-',
2
)
const verticalOffset =
vertical === indicatorVertical && horizontal === indicatorHorizontal
? indicatorOffset
: INDICATOR_PADDING
const positionStyle = {
[vertical]: `${verticalOffset}px`,
[horizontal]: `${INDICATOR_PADDING}px`,
[vertical === 'top' ? 'bottom' : 'top']: 'auto',
[horizontal === 'left' ? 'right' : 'left']: 'auto',
} as CSSProperties
const definedItems = items.filter((item) => !!item)
const itemsAboveFooter = definedItems.filter((item) => !item.footer)
const itemsBelowFooter = definedItems.filter((item) => item.footer)
function onMenuKeydown(e: React.KeyboardEvent<HTMLDivElement | null>) {
e.preventDefault()
const clickableItems = definedItems.filter((item) => item.onClick)
const totalClickableItems = clickableItems.length
switch (e.key) {
case 'ArrowDown':
const next =
selectedIndex >= totalClickableItems - 1 ? 0 : selectedIndex + 1
selectMenuItem({ index: next, menuRef, setSelectedIndex })
break
case 'ArrowUp':
const prev =
selectedIndex <= 0 ? totalClickableItems - 1 : selectedIndex - 1
selectMenuItem({ index: prev, menuRef, setSelectedIndex })
break
case 'Home':
selectMenuItem({ index: 'first', menuRef, setSelectedIndex })
break
case 'End':
selectMenuItem({ index: 'last', menuRef, setSelectedIndex })
break
case 'n':
if (e.ctrlKey) {
const nextCtrl =
selectedIndex >= totalClickableItems - 1 ? 0 : selectedIndex + 1
selectMenuItem({ index: nextCtrl, menuRef, setSelectedIndex })
}
break
case 'p':
if (e.ctrlKey) {
const prevCtrl =
selectedIndex <= 0 ? totalClickableItems - 1 : selectedIndex - 1
selectMenuItem({ index: prevCtrl, menuRef, setSelectedIndex })
}
break
default:
break
}
}
return (
<div
ref={menuRef}
onKeyDown={onMenuKeydown}
id="nextjs-dev-tools-menu"
role="menu"
dir="ltr"
aria-orientation="vertical"
aria-label="Next.js Dev Tools Items"
tabIndex={-1}
style={{
outline: 0,
WebkitFontSmoothing: 'antialiased',
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
background: 'var(--color-background-100)',
backgroundClip: 'padding-box',
boxShadow: 'var(--shadow-menu)',
borderRadius: 'var(--rounded-xl)',
position: 'fixed',
fontFamily: 'var(--font-stack-sans)',
zIndex: 3,
overflow: 'hidden',
opacity: 1,
minWidth: '248px',
transition:
'opacity var(--animate-out-duration-ms) var(--animate-out-timing-function)',
border: '1px solid var(--color-gray-alpha-400)',
...positionStyle,
}}
>
<MenuContext
value={{
selectedIndex,
setSelectedIndex,
}}
>
<div style={{ padding: '6px', width: '100%' }}>
{itemsAboveFooter.map((item, index) => (
<MenuItem
key={item.label}
title={item.title}
label={item.label}
value={item.value}
onClick={item.onClick}
index={
item.onClick
? getAdjustedIndex(itemsAboveFooter, index)
: undefined
}
{...item.attributes}
/>
))}
</div>
<div className="dev-tools-indicator-footer">
{itemsBelowFooter.map((item, index) => (
<MenuItem
key={item.label}
title={item.title}
label={item.label}
value={item.value}
onClick={item.onClick}
{...item.attributes}
index={
item.onClick
? getAdjustedIndex(itemsBelowFooter, index) +
getClickableItemsCount(itemsAboveFooter)
: undefined
}
/>
))}
</div>
</MenuContext>
</div>
)
}
export function getAdjustedIndex(
items: Array<{ onClick?: () => void }>,
targetIndex: number
): number {
let adjustedIndex = 0
for (let i = 0; i <= targetIndex && i < items.length; i++) {
if (items[i].onClick) {
if (i === targetIndex) {
return adjustedIndex
}
adjustedIndex++
}
}
return adjustedIndex
}
export function getClickableItemsCount(
items: Array<{ onClick?: () => void }>
): number {
return items.filter((item) => item.onClick).length
}
export function IssueCount({ children }: { children: number }) {
return (
<span
className="dev-tools-indicator-issue-count"
data-has-issues={children > 0}
>
<span className="dev-tools-indicator-issue-count-indicator" />
{children}
</span>
)
}
export function ChevronRight() {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
>
<path
fill="#666"
fillRule="evenodd"
clipRule="evenodd"
d="M5.50011 1.93945L6.03044 2.46978L10.8537 7.293C11.2442 7.68353 11.2442 8.31669 10.8537 8.70722L6.03044 13.5304L5.50011 14.0608L4.43945 13.0001L4.96978 12.4698L9.43945 8.00011L4.96978 3.53044L4.43945 3.00011L5.50011 1.93945Z"
/>
</svg>
)
}
export function selectMenuItem({
index,
menuRef,
setSelectedIndex,
}: {
index: number | 'first' | 'last'
menuRef: React.RefObject<HTMLDivElement | null>
setSelectedIndex: (index: number) => void
}) {
if (index === 'first') {
setTimeout(() => {
const all = menuRef.current?.querySelectorAll('[role="menuitem"]')
if (all) {
const firstIndex = all[0].getAttribute('data-index')
selectMenuItem({ index: Number(firstIndex), menuRef, setSelectedIndex })
}
})
return
}
if (index === 'last') {
setTimeout(() => {
const all = menuRef.current?.querySelectorAll('[role="menuitem"]')
if (all) {
const lastIndex = all.length - 1
selectMenuItem({ index: lastIndex, menuRef, setSelectedIndex })
}
})
return
}
const el = menuRef.current?.querySelector(
`[data-index="${index}"]`
) as HTMLElement
if (el) {
setSelectedIndex(index)
el?.focus()
}
}
......@@ -47,11 +47,12 @@ export interface OverlayState {
* which is viewing the "Issues Tab" as a fullscreen.
*/
isErrorOverlayOpen: boolean
isDevToolsPanelOpen: boolean
devToolsPosition: Corners
devToolsPanelPosition: Record<DevtoolsPanelName, Corners>
scale: number
page: string
}
type DevtoolsPanelName = string
export type OverlayDispatch = React.Dispatch<DispatcherEvent>
export const ACTION_STATIC_INDICATOR = 'static-indicator'
......@@ -64,6 +65,7 @@ export const ACTION_UNHANDLED_ERROR = 'unhandled-error'
export const ACTION_UNHANDLED_REJECTION = 'unhandled-rejection'
export const ACTION_DEBUG_INFO = 'debug-info'
export const ACTION_DEV_INDICATOR = 'dev-indicator'
export const ACTION_DEV_INDICATOR_SET = 'dev-indicator-disable'
export const ACTION_ERROR_OVERLAY_OPEN = 'error-overlay-open'
export const ACTION_ERROR_OVERLAY_CLOSE = 'error-overlay-close'
......@@ -79,11 +81,20 @@ export const ACTION_DEVTOOLS_PANEL_CLOSE = 'devtools-panel-close'
export const ACTION_DEVTOOLS_PANEL_TOGGLE = 'devtools-panel-toggle'
export const ACTION_DEVTOOLS_POSITION = 'devtools-position'
export const ACTION_DEVTOOLS_PANEL_POSITION = 'devtools-panel-position'
export const ACTION_DEVTOOLS_PANEL_SIZE = 'devtools-panel-size'
export const ACTION_DEVTOOLS_SCALE = 'devtools-scale'
export const ACTION_RESTART_SERVER_BUTTON = 'restart-server-button'
export const STORAGE_KEY_THEME = '__nextjs-dev-tools-theme'
export const STORAGE_KEY_POSITION = '__nextjs-dev-tools-position'
export const STORAGE_KEY_PANEL_POSITION_PREFIX =
'__nextjs-dev-tools-panel-position'
export const STORE_KEY_PANEL_SIZE_PREFIX = '__nextjs-dev-tools-panel-size'
export const STORE_KEY_SHARED_PANEL_SIZE =
'__nextjs-dev-tools-shared-panel-size'
export const STORE_KEY_SHARED_PANEL_LOCATION =
'__nextjs-dev-tools-shared-panel-location'
export const STORAGE_KEY_SCALE = '__nextjs-dev-tools-scale'
export const STORAGE_KEY_ACTIVE_TAB = '__nextjs-devtools-active-tab'
......@@ -133,6 +144,11 @@ interface DevIndicatorAction {
devIndicator: DevIndicatorServerState
}
interface DevIndicatorSetAction {
type: typeof ACTION_DEV_INDICATOR_SET
disabled: boolean
}
export interface ErrorOverlayOpenAction {
type: typeof ACTION_ERROR_OVERLAY_OPEN
}
......@@ -157,21 +173,17 @@ export interface RenderingIndicatorHideAction {
type: typeof ACTION_RENDERING_INDICATOR_HIDE
}
export interface DevToolsPanelOpenAction {
type: typeof ACTION_DEVTOOLS_PANEL_OPEN
}
export interface DevToolsPanelCloseAction {
type: typeof ACTION_DEVTOOLS_PANEL_CLOSE
}
export interface DevToolsPanelToggleAction {
type: typeof ACTION_DEVTOOLS_PANEL_TOGGLE
}
export interface DevToolsIndicatorPositionAction {
type: typeof ACTION_DEVTOOLS_POSITION
devToolsPosition: Corners
}
export interface DevToolsPanelPositionAction {
type: typeof ACTION_DEVTOOLS_PANEL_POSITION
key: string
devToolsPanelPosition: Corners
}
export interface DevToolsScaleAction {
type: typeof ACTION_DEVTOOLS_SCALE
scale: number
......@@ -205,13 +217,12 @@ export type DispatcherEvent =
| BuildingIndicatorHideAction
| RenderingIndicatorShowAction
| RenderingIndicatorHideAction
| DevToolsPanelOpenAction
| DevToolsPanelCloseAction
| DevToolsPanelToggleAction
| DevToolsIndicatorPositionAction
| DevToolsPanelPositionAction
| DevToolsScaleAction
| DevToolUpdateRouteStateAction
| RestartServerButtonAction
| DevIndicatorSetAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: new frame + v8
......@@ -231,6 +242,41 @@ function getStackIgnoringStrictMode(stack: string | undefined) {
const shouldDisableDevIndicator =
process.env.__NEXT_DEV_INDICATOR?.toString() === 'false'
// TODO: change local storage impl
function getStoredPosition(): Corners {
if (typeof localStorage === 'undefined') {
return 'bottom-left' as const
}
const stored = localStorage.getItem(STORAGE_KEY_POSITION)
if (
stored &&
['top-left', 'top-right', 'bottom-left', 'bottom-right'].includes(stored)
) {
return stored as Corners
} else {
localStorage.removeItem(STORAGE_KEY_POSITION)
}
// we give priority to local storage over next.config
return (process.env.__NEXT_DEV_INDICATOR_POSITION ?? 'bottom-left') as Corners
}
export function getStoredPanelPosition() {
if (typeof localStorage === 'undefined') {
return 'bottom-left' as const
}
const stored = localStorage.getItem(STORE_KEY_SHARED_PANEL_LOCATION)
if (
stored &&
['top-left', 'top-right', 'bottom-left', 'bottom-right'].includes(stored)
) {
return stored as Corners
} else {
localStorage.removeItem(STORE_KEY_SHARED_PANEL_LOCATION)
}
return 'bottom-left' as const
}
export const INITIAL_OVERLAY_STATE: Omit<
OverlayState,
'isErrorOverlayOpen' | 'routerType'
......@@ -252,9 +298,12 @@ export const INITIAL_OVERLAY_STATE: Omit<
refreshState: { type: 'idle' },
versionInfo: { installed: '0.0.0', staleness: 'unknown' },
debugInfo: { devtoolsFrontendUrl: undefined },
isDevToolsPanelOpen: false,
showRestartServerButton: false,
devToolsPosition: 'bottom-left',
devToolsPosition: getStoredPosition(),
devToolsPanelPosition: {
[STORE_KEY_SHARED_PANEL_LOCATION]: getStoredPanelPosition(),
},
scale: NEXT_DEV_TOOLS_SCALE.Medium,
page: '',
}
......@@ -390,6 +439,9 @@ export function useErrorOverlayReducer(
case ACTION_VERSION_INFO: {
return { ...state, versionInfo: action.versionInfo }
}
case ACTION_DEV_INDICATOR_SET: {
return { ...state, disableDevIndicator: action.disabled }
}
case ACTION_DEV_INDICATOR: {
return {
...state,
......@@ -419,18 +471,20 @@ export function useErrorOverlayReducer(
case ACTION_RENDERING_INDICATOR_HIDE: {
return { ...state, renderingIndicator: false }
}
case ACTION_DEVTOOLS_PANEL_OPEN: {
return { ...state, isDevToolsPanelOpen: true }
}
case ACTION_DEVTOOLS_PANEL_CLOSE: {
return { ...state, isDevToolsPanelOpen: false }
}
case ACTION_DEVTOOLS_PANEL_TOGGLE: {
return { ...state, isDevToolsPanelOpen: !state.isDevToolsPanelOpen }
}
case ACTION_DEVTOOLS_POSITION: {
return { ...state, devToolsPosition: action.devToolsPosition }
}
case ACTION_DEVTOOLS_PANEL_POSITION: {
return {
...state,
devToolsPanelPosition: {
...state.devToolsPanelPosition,
[action.key]: action.devToolsPanelPosition,
},
}
}
case ACTION_DEVTOOLS_SCALE: {
return { ...state, scale: action.scale }
}
......
import { DevOverlay } from '../dev-overlay'
import { DevOverlayContext } from '../../dev-overlay.browser'
import {
useStorybookOverlayReducer,
storybookDefaultOverlayState,
} from './use-overlay-reducer'
import type { OverlayState } from '../shared'
import type { ReadyRuntimeError } from '../utils/get-error-by-type'
type WrapperProps = {
initialState?: Partial<OverlayState>
runtimeErrors?: ReadyRuntimeError[]
children?: never
}
// todo: wrap stories in this so props are configurable
export function DevOverlayStoryWrapper({ initialState }: WrapperProps) {
const mergedState: OverlayState = {
...storybookDefaultOverlayState,
...initialState,
} as OverlayState
const [state, dispatch] = useStorybookOverlayReducer(mergedState)
return (
<DevOverlayContext
value={{ state, dispatch, getSquashedHydrationErrorDetails: () => null }}
>
<DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={() => null}
/>
</DevOverlayContext>
)
}
This diff is collapsed.
export default function Loading() {
return <p>Loading...</p>
}
This diff is collapsed.
This diff is collapsed.
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