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' ...@@ -9,6 +9,8 @@ import { fileURLToPath } from 'url'
function getAbsolutePath(value: string): any { function getAbsolutePath(value: string): any {
return dirname(require.resolve(join(value, 'package.json'))) return dirname(require.resolve(join(value, 'package.json')))
} }
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
const config: StorybookConfig = { const config: StorybookConfig = {
stories: ['../src/next-devtools/**/*.stories.tsx'], stories: ['../src/next-devtools/**/*.stories.tsx'],
......
...@@ -18,9 +18,17 @@ import { ...@@ -18,9 +18,17 @@ import {
ACTION_RENDERING_INDICATOR_HIDE, ACTION_RENDERING_INDICATOR_HIDE,
ACTION_RENDERING_INDICATOR_SHOW, ACTION_RENDERING_INDICATOR_SHOW,
ACTION_DEVTOOL_UPDATE_ROUTE_STATE, ACTION_DEVTOOL_UPDATE_ROUTE_STATE,
type OverlayState,
type DispatcherEvent,
} from './dev-overlay/shared' } 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 { createRoot } from 'react-dom/client'
import { FontStyles } from './dev-overlay/font/font-styles' import { FontStyles } from './dev-overlay/font/font-styles'
import type { HydrationErrorState } from './shared/hydration-error' import type { HydrationErrorState } from './shared/hydration-error'
...@@ -208,14 +216,31 @@ function DevOverlayRoot({ ...@@ -208,14 +216,31 @@ function DevOverlayRoot({
<> <>
{/* Fonts can only be loaded outside the Shadow DOM. */} {/* Fonts can only be loaded outside the Shadow DOM. */}
<FontStyles /> <FontStyles />
<DevOverlay <DevOverlayContext
state={state} value={{
dispatch={dispatch} dispatch,
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails} 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 isPagesMounted = false
let isAppMounted = false let isAppMounted = false
......
import type { Meta, StoryObj } from '@storybook/react' import type { Meta, StoryObj } from '@storybook/react'
import type { OverlayState } from '../../shared' import type { OverlayState } from '../../shared'
import { DevToolsIndicator } from './devtools-indicator' import { DevToolsIndicatorNew } from './devtools-indicator'
import { INITIAL_OVERLAY_STATE } from '../../shared' import { INITIAL_OVERLAY_STATE } from '../../shared'
import { withShadowPortal } from '../../storybook/with-shadow-portal' import { withShadowPortal } from '../../storybook/with-shadow-portal'
const meta: Meta<typeof DevToolsIndicator> = { const meta: Meta<typeof DevToolsIndicatorNew> = {
component: DevToolsIndicator, component: DevToolsIndicatorNew,
parameters: { parameters: {
layout: 'centered', layout: 'centered',
}, },
...@@ -37,7 +37,7 @@ const meta: Meta<typeof DevToolsIndicator> = { ...@@ -37,7 +37,7 @@ const meta: Meta<typeof DevToolsIndicator> = {
} }
export default meta export default meta
type Story = StoryObj<typeof DevToolsIndicator> type Story = StoryObj<typeof DevToolsIndicatorNew>
const state: OverlayState = { const state: OverlayState = {
...INITIAL_OVERLAY_STATE, ...INITIAL_OVERLAY_STATE,
......
import type { CSSProperties } from 'react' import type { CSSProperties } from 'react'
import type { OverlayState, OverlayDispatch } from '../../shared'
import { useState } from 'react' import { NextLogoNew } from './next-logo'
import { NextLogo } from './next-logo'
import { Toast } from '../toast' import { Toast } from '../toast'
import { import {
MENU_CURVE, MENU_CURVE,
MENU_DURATION_MS, MENU_DURATION_MS,
} from '../errors/dev-tools-indicator/utils' } from '../errors/dev-tools-indicator/utils'
import { import {
ACTION_DEVTOOLS_PANEL_TOGGLE,
STORAGE_KEY_POSITION, STORAGE_KEY_POSITION,
ACTION_DEVTOOLS_POSITION, ACTION_DEVTOOLS_POSITION,
ACTION_DEVTOOLS_PANEL_OPEN, STORE_KEY_SHARED_PANEL_LOCATION,
ACTION_ERROR_OVERLAY_OPEN, STORAGE_KEY_PANEL_POSITION_PREFIX,
ACTION_DEVTOOLS_PANEL_POSITION,
} from '../../shared' } from '../../shared'
import { Draggable } from '../errors/dev-tools-indicator/draggable' 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 const INDICATOR_PADDING = 20
export function DevToolsIndicator({ export function DevToolsIndicatorNew() {
state, const { state, dispatch } = useDevOverlayContext()
dispatch, const { panel, setPanel, setSelectedIndex } = usePanelRouterContext()
errorCount, const updateAllPanelPositions = useUpdateAllPanelPositions()
isBuildError,
}: {
state: OverlayState
dispatch: OverlayDispatch
errorCount: number
isBuildError: boolean
}) {
const [open, setOpen] = useState(false)
const [vertical, horizontal] = state.devToolsPosition.split('-', 2) 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 ( return (
// TODO: why is this called a toast
<Toast <Toast
id="devtools-indicator"
data-nextjs-toast data-nextjs-toast
style={ style={
{ {
...@@ -54,16 +39,14 @@ export function DevToolsIndicator({ ...@@ -54,16 +39,14 @@ export function DevToolsIndicator({
boxShadow: 'none', boxShadow: 'none',
[vertical]: `${INDICATOR_PADDING}px`, [vertical]: `${INDICATOR_PADDING}px`,
[horizontal]: `${INDICATOR_PADDING}px`, [horizontal]: `${INDICATOR_PADDING}px`,
visibility: visibility: state.isErrorOverlayOpen ? 'hidden' : 'visible',
state.isDevToolsPanelOpen || state.isErrorOverlayOpen
? 'hidden'
: 'visible',
} as CSSProperties } as CSSProperties
} }
> >
<Draggable <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} padding={INDICATOR_PADDING}
onDragStart={() => setOpen(false)}
position={state.devToolsPosition} position={state.devToolsPosition}
setPosition={(p) => { setPosition={(p) => {
dispatch({ dispatch({
...@@ -71,25 +54,54 @@ export function DevToolsIndicator({ ...@@ -71,25 +54,54 @@ export function DevToolsIndicator({
devToolsPosition: p, devToolsPosition: p,
}) })
localStorage.setItem(STORAGE_KEY_POSITION, p) localStorage.setItem(STORAGE_KEY_POSITION, p)
updateAllPanelPositions(p)
}} }}
> >
{/* Trigger */} <NextLogoNew
<NextLogo onTriggerClick={() => {
aria-haspopup="menu" const newPanel =
aria-expanded={open} panel === 'panel-selector' ? null : 'panel-selector'
aria-controls="nextjs-dev-tools-menu" setPanel(newPanel)
aria-label={`${open ? 'Close' : 'Open'} Next.js Dev Tools`} if (!newPanel) {
data-nextjs-dev-tools-button setSelectedIndex(-1)
disabled={state.disableDevIndicator} return
issueCount={errorCount} }
onTriggerClick={toggleDevToolsPanel} }}
toggleErrorOverlay={enableErrorOverlayMode}
isDevBuilding={state.buildingIndicator}
isDevRendering={state.renderingIndicator}
isBuildError={isBuildError}
scale={state.scale}
/> />
</Draggable> </Draggable>
</Toast> </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 type { Meta, StoryObj } from '@storybook/react'
import { NextLogo } from './next-logo' import { NextLogoNew } from './next-logo'
import { withShadowPortal } from '../../storybook/with-shadow-portal' 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> = { const meta: Meta<typeof StoryBookNextLogo> = {
component: NextLogo, component: StoryBookNextLogo,
parameters: { parameters: {
layout: 'centered', layout: 'centered',
}, },
args: { args: {
'aria-label': 'Open Next.js DevTools', 'aria-label': 'Open Next.js DevTools',
onClick: () => console.log('Clicked!'),
}, },
decorators: [withShadowPortal], decorators: [withShadowPortal],
} }
export default meta export default meta
type Story = StoryObj<typeof NextLogo> type Story = StoryObj<typeof StoryBookNextLogo>
export const NoIssues: Story = { export const NoIssues: Story = {
args: { args: {
......
import type { DevToolsScale } from '../errors/dev-tools-indicator/dev-tools-info/preferences'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { useUpdateAnimation } from './hooks/use-update-animation' import { useUpdateAnimation } from './hooks/use-update-animation'
import { useMeasureWidth } from './hooks/use-measure-width' import { useMeasureWidth } from './hooks/use-measure-width'
...@@ -7,45 +5,39 @@ import { useMinimumLoadingTimeMultiple } from './hooks/use-minimum-loading-time- ...@@ -7,45 +5,39 @@ import { useMinimumLoadingTimeMultiple } from './hooks/use-minimum-loading-time-
import { Cross } from '../../icons/cross' import { Cross } from '../../icons/cross'
import { Warning } from '../../icons/warning' import { Warning } from '../../icons/warning'
import { css } from '../../utils/css' import { css } from '../../utils/css'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
interface Props extends React.ComponentProps<'button'> { import { useRenderErrorContext } from '../../dev-overlay'
issueCount: number import { ACTION_ERROR_OVERLAY_OPEN } from '../../shared'
isDevBuilding: boolean import { usePanelRouterContext } from '../../menu/context'
isDevRendering: boolean import { BASE_LOGO_SIZE } from '../../utils/indicator-metrics'
isBuildError: boolean
onTriggerClick: () => void
toggleErrorOverlay: () => void
scale: DevToolsScale
}
const SHORT_DURATION_MS = 150 const SHORT_DURATION_MS = 150
export function NextLogo({ export function NextLogoNew({
disabled,
issueCount,
isDevBuilding,
isDevRendering,
isBuildError,
onTriggerClick, onTriggerClick,
toggleErrorOverlay, ...buttonProps
scale = 1, }: { onTriggerClick: () => void } & React.ComponentProps<'button'>) {
...props const { state, dispatch } = useDevOverlayContext()
}: Props) { const { totalErrorCount } = useRenderErrorContext()
const SIZE = 36 / scale const SIZE = BASE_LOGO_SIZE / state.scale
const { panel, triggerRef, setPanel } = usePanelRouterContext()
const hasError = issueCount > 0 const isMenuOpen = panel === 'panel-selector'
const hasError = totalErrorCount > 0
const [isErrorExpanded, setIsErrorExpanded] = useState(hasError) const [isErrorExpanded, setIsErrorExpanded] = useState(hasError)
const [dismissed, setDismissed] = useState(false) 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 ref = useRef<HTMLDivElement | null>(null)
const measuredWidth = useMeasureWidth(ref) const measuredWidth = useMeasureWidth(ref)
const isLoading = useMinimumLoadingTimeMultiple( const isLoading = useMinimumLoadingTimeMultiple(
isDevBuilding || isDevRendering state.buildingIndicator || state.renderingIndicator
) )
const isExpanded = isErrorExpanded || disabled const isExpanded = isErrorExpanded || state.disableDevIndicator
const width = measuredWidth === 0 ? 'auto' : measuredWidth const width = measuredWidth === 0 ? 'auto' : measuredWidth
useEffect(() => { useEffect(() => {
...@@ -61,7 +53,10 @@ export function NextLogo({ ...@@ -61,7 +53,10 @@ export function NextLogo({
'--duration-short': `${SHORT_DURATION_MS}ms`, '--duration-short': `${SHORT_DURATION_MS}ms`,
// if the indicator is disabled, hide the badge // if the indicator is disabled, hide the badge
// also allow the "disabled" state be dismissed, as long as there are no build errors // 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 } as React.CSSProperties
} }
> >
...@@ -396,15 +391,25 @@ export function NextLogo({ ...@@ -396,15 +391,25 @@ export function NextLogo({
> >
<div ref={ref}> <div ref={ref}>
{/* Children */} {/* Children */}
{!disabled && ( {!state.disableDevIndicator && (
<button <button
id="next-logo"
ref={triggerRef} ref={triggerRef}
data-next-mark data-next-mark
data-next-mark-loading={isLoading} data-next-mark-loading={isLoading}
onClick={onTriggerClick} 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> </button>
)} )}
{isExpanded && ( {isExpanded && (
...@@ -412,42 +417,46 @@ export function NextLogo({ ...@@ -412,42 +417,46 @@ export function NextLogo({
<button <button
data-issues-open data-issues-open
aria-label="Open issues overlay" 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> <div data-disabled-icon>
<Warning /> <Warning />
</div> </div>
)} )}
<AnimateCount <AnimateCount
// Used the key to force a re-render when the count changes. // Used the key to force a re-render when the count changes.
key={issueCount} key={totalErrorCount}
animate={newErrorDetected} animate={newErrorDetected}
data-issues-count-animation data-issues-count-animation
> >
{issueCount} {totalErrorCount}
</AnimateCount>{' '} </AnimateCount>{' '}
<div> <div>
Issue Issue
{issueCount > 1 && ( {totalErrorCount > 1 && (
<span <span
aria-hidden aria-hidden
data-issues-count-plural data-issues-count-plural
// This only needs to animate once the count changes from 1 -> 2, // This only needs to animate once the count changes from 1 -> 2,
// otherwise it should stay static between re-renders. // otherwise it should stay static between re-renders.
data-animate={newErrorDetected && issueCount === 2} data-animate={newErrorDetected && totalErrorCount === 2}
> >
s s
</span> </span>
)} )}
</div> </div>
</button> </button>
{!isBuildError && ( {!state.buildError && (
<button <button
data-issues-collapse data-issues-collapse
aria-label="Collapse issues badge" aria-label="Collapse issues badge"
onClick={() => { onClick={() => {
if (disabled) { if (state.disableDevIndicator) {
setDismissed(true) setDismissed(true)
} else { } else {
setIsErrorExpanded(false) 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 @@ ...@@ -15,19 +15,19 @@
/* immediately responsive so we don't need a bespoke curve */ /* immediately responsive so we don't need a bespoke curve */
transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1); transition: transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
/* todo: better var? */ /* 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 */ /* start really fast because we start super hidden initially behind the panel, otherwise feels like an unintended animation delay */
.resize-container:hover ~ .resize-line { .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.right,
.resize-container.left { .resize-container.left {
top: 0; top: 0;
height: 100%; height: 100%;
width: 25px; width: 22px;
cursor: ew-resize; cursor: ew-resize;
} }
...@@ -37,97 +37,97 @@ ...@@ -37,97 +37,97 @@
.resize-container.top { .resize-container.top {
left: 0; left: 0;
width: 100%; width: 100%;
height: 25px; height: 22px;
cursor: ns-resize; cursor: ns-resize;
} }
.resize-container.top { .resize-container.top {
top: -12px; top: -7px;
} }
.resize-container.bottom { .resize-container.bottom {
bottom: -12px; bottom: -7px;
} }
.resize-container.left { .resize-container.left {
left: -12px; left: -7px;
} }
.resize-container.right { .resize-container.right {
right: -12px; right: -7px;
} }
.resize-container.top-left, .resize-container.top-left,
.resize-container.top-right, .resize-container.top-right,
.resize-container.bottom-left, .resize-container.bottom-left,
.resize-container.bottom-right { .resize-container.bottom-right {
width: 32px; width: 26px;
height: 32px; height: 26px;
z-index: 15; z-index: 15;
} }
.resize-container.top-left { .resize-container.top-left {
top: -16px; top: -5px;
left: -16px; left: -5px;
cursor: nwse-resize; cursor: nwse-resize;
} }
.resize-container.top-right { .resize-container.top-right {
top: -16px; top: -5px;
right: -16px; right: -5px;
cursor: nesw-resize; cursor: nesw-resize;
} }
.resize-container.bottom-left { .resize-container.bottom-left {
bottom: -16px; bottom: -5px;
left: -16px; left: -5px;
cursor: nesw-resize; cursor: nesw-resize;
} }
.resize-container.bottom-right { .resize-container.bottom-right {
bottom: -16px; bottom: -5px;
right: -16px; right: -5px;
cursor: nwse-resize; cursor: nwse-resize;
} }
.resize-line.top, .resize-line.top,
.resize-line.bottom { .resize-line.bottom {
height: 28px; height: 18px;
width: 100%; width: 100%;
background-color: var(--color-background-100); background-color: var(--color-background-200);
} }
.resize-line.left, .resize-line.left,
.resize-line.right { .resize-line.right {
width: 28px; width: 18px;
height: 100%; height: 100%;
background-color: var(--color-background-100); background-color: var(--color-background-200);
} }
.resize-line.top { .resize-line.top {
top: -12px; top: -7px;
left: calc(-1 * var(--border-left, 2px)); left: calc(-1 * var(--border-left, 2px));
width: calc(100% + var(--border-horizontal, 4px)); width: calc(100% + var(--border-horizontal, 4px));
border-radius: var(--rounded-md) var(--rounded-md) 0 0; border-radius: var(--rounded-lg) var(--rounded-lg) 0 0;
transform: translateY(28px); transform: translateY(18px);
} }
.resize-line.bottom { .resize-line.bottom {
bottom: -12px; bottom: -7px;
left: calc(-1 * var(--border-left, 2px)); left: calc(-1 * var(--border-left, 2px));
width: calc(100% + var(--border-horizontal, 4px)); width: calc(100% + var(--border-horizontal, 4px));
border-radius: 0 0 var(--rounded-md) var(--rounded-md); border-radius: 0 0 var(--rounded-lg) var(--rounded-lg);
transform: translateY(-28px); transform: translateY(-18px);
} }
.resize-line.left { .resize-line.left {
top: calc(-1 * var(--border-top, 2px)); top: calc(-1 * var(--border-top, 2px));
left: -12px; left: -7px;
height: calc(100% + var(--border-vertical, 4px)); height: calc(100% + var(--border-vertical, 4px));
border-radius: var(--rounded-md) 0 0 var(--rounded-md); border-radius: var(--rounded-lg) 0 0 var(--rounded-lg);
transform: translateX(28px); transform: translateX(18px);
} }
.resize-line.right { .resize-line.right {
top: calc(-1 * var(--border-top, 2px)); top: calc(-1 * var(--border-top, 2px));
right: -12px; right: -7px;
height: calc(100% + var(--border-vertical, 4px)); height: calc(100% + var(--border-vertical, 4px));
border-radius: 0 var(--rounded-md) var(--rounded-md) 0; border-radius: 0 var(--rounded-lg) var(--rounded-lg) 0;
transform: translateX(-28px); transform: translateX(-18px);
} }
.resize-container.right:hover ~ .resize-line.right, .resize-container.right:hover ~ .resize-line.right,
...@@ -149,14 +149,14 @@ ...@@ -149,14 +149,14 @@
* regardless of hover state * regardless of hover state
*/ */
.resize-container.no-hover.right:hover ~ .resize-line.right { .resize-container.no-hover.right:hover ~ .resize-line.right {
transform: translateX(-28px); transform: translateX(-20px);
} }
.resize-container.no-hover.left:hover ~ .resize-line.left { .resize-container.no-hover.left:hover ~ .resize-line.left {
transform: translateX(28px); transform: translateX(20px);
} }
.resize-container.no-hover.bottom:hover ~ .resize-line.bottom { .resize-container.no-hover.bottom:hover ~ .resize-line.bottom {
transform: translateY(-28px); transform: translateY(-20px);
} }
.resize-container.no-hover.top:hover ~ .resize-line.top { .resize-container.no-hover.top:hover ~ .resize-line.top {
transform: translateY(28px); transform: translateY(20px);
} }
...@@ -3,14 +3,20 @@ import type { Corners } from '../../../shared' ...@@ -3,14 +3,20 @@ import type { Corners } from '../../../shared'
import { useResize, type ResizeDirection } from './resize-provider' import { useResize, type ResizeDirection } from './resize-provider'
import './resize-handle.css' import './resize-handle.css'
const STORAGE_KEY_DIMENSIONS = 'nextjs-devtools-dimensions' export const ResizeHandle = ({
direction,
export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => { position,
}: {
direction: ResizeDirection
position: Corners
}) => {
const { const {
resizeRef, resizeRef,
minWidth, minWidth,
minHeight, minHeight,
devToolsPosition, maxWidth,
maxHeight,
storageKey,
draggingDirection, draggingDirection,
setDraggingDirection, setDraggingDirection,
} = useResize() } = useResize()
...@@ -44,13 +50,13 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => { ...@@ -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) // 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 // 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) // 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 // same logic as above, but the only corner resize that makes
// sense is the corner fully exposed (the opposing corner) // sense is the corner fully exposed (the opposing corner)
const isCorner = direction.includes('-') const isCorner = direction.includes('-')
if (isCorner) { if (isCorner) {
const opposite = getOppositeCorner(devToolsPosition) const opposite = getOppositeCorner(position)
return direction === opposite return direction === opposite
} }
...@@ -85,8 +91,6 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => { ...@@ -85,8 +91,6 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => {
const element = resizeRef.current const element = resizeRef.current
const initialRect = element.getBoundingClientRect() const initialRect = element.getBoundingClientRect()
const initialLeft = element.offsetLeft
const initialTop = element.offsetTop
const startX = mouseDownEvent.clientX const startX = mouseDownEvent.clientX
const startY = mouseDownEvent.clientY const startY = mouseDownEvent.clientY
...@@ -94,25 +98,22 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => { ...@@ -94,25 +98,22 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => {
const deltaX = mouseMoveEvent.clientX - startX const deltaX = mouseMoveEvent.clientX - startX
const deltaY = mouseMoveEvent.clientY - startY const deltaY = mouseMoveEvent.clientY - startY
const { newWidth, newHeight, newLeft, newTop } = getNewDimensions( const { newWidth, newHeight } = getNewDimensions(
direction, direction,
deltaX, deltaX,
deltaY, deltaY,
initialRect, initialRect,
initialLeft,
initialTop,
minWidth, minWidth,
minHeight minHeight,
maxWidth,
maxHeight
) )
element.style.width = `${newWidth}px` if (newWidth !== undefined) {
element.style.height = `${newHeight}px` element.style.width = `${newWidth}px`
if (direction.includes('left') || direction === 'left') {
element.style.left = `${newLeft}px`
} }
if (direction.includes('top') || direction === 'top') { if (newHeight !== undefined) {
element.style.top = `${newTop}px` element.style.height = `${newHeight}px`
} }
} }
...@@ -120,13 +121,14 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => { ...@@ -120,13 +121,14 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => {
setDraggingDirection(null) setDraggingDirection(null)
document.removeEventListener('mousemove', handleMouseMove) document.removeEventListener('mousemove', handleMouseMove)
document.removeEventListener('mouseup', handleMouseUp) document.removeEventListener('mouseup', handleMouseUp)
if (!resizeRef.current) {
// possible if the user closes during drag
return
}
// invariant ref exists const { width, height } = resizeRef.current.getBoundingClientRect()
const { width, height } = resizeRef.current!.getBoundingClientRect()
localStorage.setItem( localStorage.setItem(storageKey, JSON.stringify({ width, height }))
STORAGE_KEY_DIMENSIONS,
JSON.stringify({ width, height })
)
} }
document.addEventListener('mousemove', handleMouseMove) document.addEventListener('mousemove', handleMouseMove)
document.addEventListener('mouseup', handleMouseUp) document.addEventListener('mouseup', handleMouseUp)
...@@ -176,37 +178,31 @@ const getNewDimensions = ( ...@@ -176,37 +178,31 @@ const getNewDimensions = (
deltaX: number, deltaX: number,
deltaY: number, deltaY: number,
initialRect: DOMRect, initialRect: DOMRect,
initialLeft: number,
initialTop: number,
minWidth: number, minWidth: number,
minHeight: number minHeight: number,
maxWidth?: number,
maxHeight?: number
) => { ) => {
const maxWidth = window.innerWidth * 0.95 const effectiveMaxWidth = maxWidth ?? window.innerWidth * 0.95
const maxHeight = window.innerHeight * 0.95 const effectiveMaxHeight = maxHeight ?? window.innerHeight * 0.95
switch (direction) { switch (direction) {
case 'right': case 'right':
return { return {
newWidth: Math.min( newWidth: Math.min(
maxWidth, effectiveMaxWidth,
Math.max(minWidth, initialRect.width + deltaX) Math.max(minWidth, initialRect.width + deltaX)
), ),
newHeight: initialRect.height, newHeight: initialRect.height,
newLeft: initialLeft,
newTop: initialTop,
} }
case 'left': { case 'left': {
const newWidth = Math.min(
maxWidth,
Math.max(minWidth, initialRect.width - deltaX)
)
const widthDiff = newWidth - initialRect.width
return { return {
newWidth, newWidth: Math.min(
effectiveMaxWidth,
Math.max(minWidth, initialRect.width - deltaX)
),
newHeight: initialRect.height, newHeight: initialRect.height,
newLeft: initialLeft - widthDiff,
newTop: initialTop,
} }
} }
...@@ -214,92 +210,70 @@ const getNewDimensions = ( ...@@ -214,92 +210,70 @@ const getNewDimensions = (
return { return {
newWidth: initialRect.width, newWidth: initialRect.width,
newHeight: Math.min( newHeight: Math.min(
maxHeight, effectiveMaxHeight,
Math.max(minHeight, initialRect.height + deltaY) Math.max(minHeight, initialRect.height + deltaY)
), ),
newLeft: initialLeft,
newTop: initialTop,
} }
case 'top': { case 'top': {
const newHeight = Math.min(
maxHeight,
Math.max(minHeight, initialRect.height - deltaY)
)
const heightDiff = newHeight - initialRect.height
return { return {
newWidth: initialRect.width, newWidth: initialRect.width,
newHeight, newHeight: Math.min(
newLeft: initialLeft, effectiveMaxHeight,
newTop: initialTop - heightDiff, Math.max(minHeight, initialRect.height - deltaY)
),
} }
} }
case 'top-left': { 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 { return {
newWidth, newWidth: Math.min(
newHeight, effectiveMaxWidth,
newLeft: initialLeft - widthDiff, Math.max(minWidth, initialRect.width - deltaX)
newTop: initialTop - heightDiff, ),
newHeight: Math.min(
effectiveMaxHeight,
Math.max(minHeight, initialRect.height - deltaY)
),
} }
} }
case 'top-right': { case 'top-right': {
const newHeight = Math.min(
maxHeight,
Math.max(minHeight, initialRect.height - deltaY)
)
const heightDiff = newHeight - initialRect.height
return { return {
newWidth: Math.min( newWidth: Math.min(
maxWidth, effectiveMaxWidth,
Math.max(minWidth, initialRect.width + deltaX) Math.max(minWidth, initialRect.width + deltaX)
), ),
newHeight, newHeight: Math.min(
newLeft: initialLeft, effectiveMaxHeight,
newTop: initialTop - heightDiff, Math.max(minHeight, initialRect.height - deltaY)
),
} }
} }
case 'bottom-left': { case 'bottom-left': {
const newWidth = Math.min(
maxWidth,
Math.max(minWidth, initialRect.width - deltaX)
)
const widthDiff = newWidth - initialRect.width
return { return {
newWidth, newWidth: Math.min(
effectiveMaxWidth,
Math.max(minWidth, initialRect.width - deltaX)
),
newHeight: Math.min( newHeight: Math.min(
maxHeight, effectiveMaxHeight,
Math.max(minHeight, initialRect.height + deltaY) Math.max(minHeight, initialRect.height + deltaY)
), ),
newLeft: initialLeft - widthDiff,
newTop: initialTop,
} }
} }
case 'bottom-right': case 'bottom-right':
return { return {
newWidth: Math.min( newWidth: Math.min(
maxWidth, effectiveMaxWidth,
Math.max(minWidth, initialRect.width + deltaX) Math.max(minWidth, initialRect.width + deltaX)
), ),
newHeight: Math.min( newHeight: Math.min(
maxHeight, effectiveMaxHeight,
Math.max(minHeight, initialRect.height + deltaY) Math.max(minHeight, initialRect.height + deltaY)
), ),
newLeft: initialLeft,
newTop: initialTop,
} }
default: { default: {
direction satisfies never direction satisfies never
......
import { import {
createContext, createContext,
useCallback,
useContext, useContext,
useLayoutEffect, useLayoutEffect,
useState, useState,
type RefObject, type RefObject,
} from 'react' } from 'react'
import type { Corners } from '../../../shared' import { STORE_KEY_SHARED_PANEL_SIZE, type Corners } from '../../../shared'
const STORAGE_KEY_DIMENSIONS = 'nextjs-devtools-dimensions'
export type ResizeDirection = export type ResizeDirection =
| 'top' | 'top'
...@@ -22,9 +22,11 @@ interface ResizeContextValue { ...@@ -22,9 +22,11 @@ interface ResizeContextValue {
resizeRef: RefObject<HTMLElement | null> resizeRef: RefObject<HTMLElement | null>
minWidth: number minWidth: number
minHeight: number minHeight: number
devToolsPosition: Corners maxWidth?: number
maxHeight?: number
draggingDirection: ResizeDirection | null draggingDirection: ResizeDirection | null
setDraggingDirection: (direction: ResizeDirection | null) => void setDraggingDirection: (direction: ResizeDirection | null) => void
storageKey: string
} }
const ResizeContext = createContext<ResizeContextValue>(null!) const ResizeContext = createContext<ResizeContextValue>(null!)
...@@ -44,8 +46,8 @@ const constrainDimensions = (params: { ...@@ -44,8 +46,8 @@ const constrainDimensions = (params: {
} }
} }
const parseResizeLocalStorage = () => { const parseResizeLocalStorage = (key: string) => {
const savedDimensions = localStorage.getItem(STORAGE_KEY_DIMENSIONS) const savedDimensions = localStorage.getItem(key)
if (!savedDimensions) return null if (!savedDimensions) return null
try { try {
const parsed = JSON.parse(savedDimensions) const parsed = JSON.parse(savedDimensions)
...@@ -59,7 +61,7 @@ const parseResizeLocalStorage = () => { ...@@ -59,7 +61,7 @@ const parseResizeLocalStorage = () => {
} }
return null return null
} catch (e) { } catch (e) {
localStorage.removeItem(STORAGE_KEY_DIMENSIONS) localStorage.removeItem(key)
return null return null
} }
} }
...@@ -69,7 +71,11 @@ interface ResizeProviderProps { ...@@ -69,7 +71,11 @@ interface ResizeProviderProps {
resizeRef: RefObject<HTMLElement | null> resizeRef: RefObject<HTMLElement | null>
minWidth?: number minWidth?: number
minHeight?: number minHeight?: number
maxWidth?: number
maxHeight?: number
devToolsPosition: Corners devToolsPosition: Corners
storageKey?: string
initialSize?: { height: number; width: number }
} }
children: React.ReactNode children: React.ReactNode
} }
...@@ -77,40 +83,73 @@ interface ResizeProviderProps { ...@@ -77,40 +83,73 @@ interface ResizeProviderProps {
export const ResizeProvider = ({ value, children }: ResizeProviderProps) => { export const ResizeProvider = ({ value, children }: ResizeProviderProps) => {
const minWidth = value.minWidth ?? 100 const minWidth = value.minWidth ?? 100
const minHeight = value.minHeight ?? 80 const minHeight = value.minHeight ?? 80
const maxWidth = value.maxWidth
const maxHeight = value.maxHeight
const [draggingDirection, setDraggingDirection] = const [draggingDirection, setDraggingDirection] =
useState<ResizeDirection | null>(null) 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(() => { useLayoutEffect(() => {
const applyConstrainedDimensions = () => { const applied = applyConstrainedDimensions()
if (!value.resizeRef.current) return if (
!applied &&
// this feels weird to read local storage on resize, but we don't value.resizeRef.current &&
// track the dimensions of the container, and this is better than value.initialSize?.height &&
// getBoundingClientReact value.initialSize.width
) {
// 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 { height, width } = constrainDimensions({ const { height, width } = constrainDimensions({
...dim, height: value.initialSize.height,
width: value.initialSize.width,
minWidth: minWidth ?? 100, minWidth: minWidth ?? 100,
minHeight: minHeight ?? 80, minHeight: minHeight ?? 80,
}) })
value.resizeRef.current.style.width = `${width}px` value.resizeRef.current.style.width = `${width}px`
value.resizeRef.current.style.height = `${height}px` value.resizeRef.current.style.height = `${height}px`
} }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
applyConstrainedDimensions() useLayoutEffect(() => {
window.addEventListener('resize', applyConstrainedDimensions) window.addEventListener('resize', applyConstrainedDimensions)
return () => return () =>
window.removeEventListener('resize', applyConstrainedDimensions) window.removeEventListener('resize', applyConstrainedDimensions)
}, [value.resizeRef, minWidth, minHeight]) }, [
applyConstrainedDimensions,
value.initialSize?.height,
value.initialSize?.width,
value.resizeRef,
])
return ( return (
<ResizeContext.Provider <ResizeContext.Provider
...@@ -118,9 +157,11 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => { ...@@ -118,9 +157,11 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => {
resizeRef: value.resizeRef, resizeRef: value.resizeRef,
minWidth, minWidth,
minHeight, minHeight,
devToolsPosition: value.devToolsPosition, maxWidth,
maxHeight,
draggingDirection, draggingDirection,
setDraggingDirection, setDraggingDirection,
storageKey,
}} }}
> >
{children} {children}
......
import type { Meta, StoryObj } from '@storybook/react' 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 { withShadowPortal } from '../../../storybook/with-shadow-portal'
import type { VersionInfo } from '../../../../../server/dev/parse-version-info' 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> = { const meta: Meta<typeof DevOverlayStoryWrapper> = {
component: DevToolsIndicator, component: DevOverlayStoryWrapper,
parameters: { parameters: {
layout: 'centered', layout: 'centered',
}, },
...@@ -36,7 +40,7 @@ const meta: Meta<typeof DevToolsIndicator> = { ...@@ -36,7 +40,7 @@ const meta: Meta<typeof DevToolsIndicator> = {
} }
export default meta export default meta
type Story = StoryObj<typeof DevToolsIndicator> type Story = StoryObj<typeof DevOverlayStoryWrapper>
// Mock version info for stories // Mock version info for stories
const mockVersionInfo: VersionInfo = { const mockVersionInfo: VersionInfo = {
...@@ -46,6 +50,9 @@ const mockVersionInfo: VersionInfo = { ...@@ -46,6 +50,9 @@ const mockVersionInfo: VersionInfo = {
const state: OverlayState = { const state: OverlayState = {
routerType: 'app', routerType: 'app',
devToolsPanelPosition: {
[STORE_KEY_SHARED_PANEL_LOCATION]: getStoredPanelPosition(),
},
nextId: 1, nextId: 1,
buildError: null, buildError: null,
errors: [], errors: [],
...@@ -59,8 +66,6 @@ const state: OverlayState = { ...@@ -59,8 +66,6 @@ const state: OverlayState = {
staticIndicator: true, staticIndicator: true,
debugInfo: { devtoolsFrontendUrl: undefined }, debugInfo: { devtoolsFrontendUrl: undefined },
isErrorOverlayOpen: false, isErrorOverlayOpen: false,
// TODO: This will be handled on the next stack——with proper story.
isDevToolsPanelOpen: false,
showRestartServerButton: false, showRestartServerButton: false,
devToolsPosition: 'bottom-left', devToolsPosition: 'bottom-left',
scale: 1, scale: 1,
...@@ -68,36 +73,31 @@ const state: OverlayState = { ...@@ -68,36 +73,31 @@ const state: OverlayState = {
} }
export const StaticRoute: Story = { export const StaticRoute: Story = {
args: { render: () => (
errorCount: 0, <DevOverlayStoryWrapper initialState={state} runtimeErrors={[]} />
state, ),
dispatch: () => {},
},
} }
export const DynamicRoute: Story = { export const DynamicRoute: Story = {
args: { render: () => (
errorCount: 0, <DevOverlayStoryWrapper
state: { initialState={{ ...state, staticIndicator: false }}
...state, runtimeErrors={[]}
staticIndicator: false, />
}, ),
dispatch: () => {},
},
} }
export const SingleError: Story = { export const SingleError: Story = {
args: { render: () => (
errorCount: 1, <DevOverlayStoryWrapper initialState={state} runtimeErrors={[{} as any]} />
state, ),
dispatch: () => {},
},
} }
export const MultipleErrors: Story = { export const MultipleErrors: Story = {
args: { render: () => (
errorCount: 3, <DevOverlayStoryWrapper
state, initialState={state}
dispatch: () => {}, runtimeErrors={[{}, {}, {}] as any}
}, />
),
} }
...@@ -18,7 +18,7 @@ import { UserPreferences } from './dev-tools-info/user-preferences' ...@@ -18,7 +18,7 @@ import { UserPreferences } from './dev-tools-info/user-preferences'
import { import {
MENU_CURVE, MENU_CURVE,
MENU_DURATION_MS, MENU_DURATION_MS,
useClickOutside, useClickOutsideAndEscape,
useFocusTrap, useFocusTrap,
} from './utils' } from './utils'
import { import {
...@@ -77,12 +77,12 @@ export function DevToolsIndicator({ ...@@ -77,12 +77,12 @@ export function DevToolsIndicator({
////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////
interface C { interface C {
closeMenu: () => void closeMenu?: () => void
selectedIndex: number selectedIndex: number
setSelectedIndex: Dispatch<SetStateAction<number>> setSelectedIndex: Dispatch<SetStateAction<number>>
} }
const Context = createContext({} as C) export const MenuContext = createContext({} as C)
const OVERLAYS = { const OVERLAYS = {
Root: 'root', Root: 'root',
...@@ -164,7 +164,7 @@ function DevToolsPopover({ ...@@ -164,7 +164,7 @@ function DevToolsPopover({
// Features to make the menu accessible // Features to make the menu accessible
useFocusTrap(menuRef, triggerRef, isMenuOpen) useFocusTrap(menuRef, triggerRef, isMenuOpen)
useClickOutside(menuRef, triggerRef, menuMounted, closeMenu) useClickOutsideAndEscape(menuRef, triggerRef, menuMounted, closeMenu)
useShortcuts(hideShortcut ? { [hideShortcut]: hideDevTools } : {}, triggerRef) useShortcuts(hideShortcut ? { [hideShortcut]: hideDevTools } : {}, triggerRef)
useEffect(() => { useEffect(() => {
...@@ -397,7 +397,7 @@ function DevToolsPopover({ ...@@ -397,7 +397,7 @@ function DevToolsPopover({
data-rendered={menuRendered} data-rendered={menuRendered}
style={popover} style={popover}
> >
<Context.Provider <MenuContext.Provider
value={{ value={{
closeMenu, closeMenu,
selectedIndex, selectedIndex,
...@@ -457,7 +457,7 @@ function DevToolsPopover({ ...@@ -457,7 +457,7 @@ function DevToolsPopover({
/> />
) : null} ) : null}
</div> </div>
</Context.Provider> </MenuContext.Provider>
</div> </div>
)} )}
</Toast> </Toast>
...@@ -483,7 +483,7 @@ function ChevronRight() { ...@@ -483,7 +483,7 @@ function ChevronRight() {
) )
} }
function MenuItem({ export function MenuItem({
index, index,
label, label,
value, value,
...@@ -500,13 +500,13 @@ function MenuItem({ ...@@ -500,13 +500,13 @@ function MenuItem({
}) { }) {
const isInteractive = const isInteractive =
typeof onClick === 'function' || typeof href === 'string' typeof onClick === 'function' || typeof href === 'string'
const { closeMenu, selectedIndex, setSelectedIndex } = useContext(Context) const { closeMenu, selectedIndex, setSelectedIndex } = useContext(MenuContext)
const selected = selectedIndex === index const selected = selectedIndex === index
function click() { function click() {
if (isInteractive) { if (isInteractive) {
onClick?.() onClick?.()
closeMenu() closeMenu?.()
if (href) { if (href) {
window.open(href, '_blank', 'noopener, noreferrer') 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 { 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 { useDelayedRender } from '../../../../hooks/use-delayed-render'
import { css } from '../../../../utils/css'
export interface DevToolsInfoPropsCore { export interface DevToolsInfoPropsCore {
isOpen: boolean isOpen: boolean
...@@ -37,7 +42,7 @@ export function DevToolsInfo({ ...@@ -37,7 +42,7 @@ export function DevToolsInfo({
// Bring focus to close button, so the user can easily close the overlay // Bring focus to close button, so the user can easily close the overlay
closeButtonRef.current?.focus() closeButtonRef.current?.focus()
}) })
useClickOutside(ref, triggerRef, mounted, close) useClickOutsideAndEscape(ref, triggerRef, mounted, close)
if (!mounted) { if (!mounted) {
return null return null
...@@ -84,7 +89,7 @@ export function DevToolsInfo({ ...@@ -84,7 +89,7 @@ export function DevToolsInfo({
) )
} }
export const DEV_TOOLS_INFO_STYLES = ` export const DEV_TOOLS_INFO_STYLES = css`
[data-info-popover] { [data-info-popover] {
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
display: flex; display: flex;
...@@ -135,7 +140,7 @@ export const DEV_TOOLS_INFO_STYLES = ` ...@@ -135,7 +140,7 @@ export const DEV_TOOLS_INFO_STYLES = `
.dev-tools-info-close-button { .dev-tools-info-close-button {
all: unset; all: unset;
width: 20px; width: 20px;
height: 20px; height: 20px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
......
import type { HTMLProps } from 'react' import type { ComponentProps, HTMLProps, RefObject } from 'react'
import type { DevToolsInfoPropsCore } from './dev-tools-info'
import { DevToolsInfo } from './dev-tools-info' import { DevToolsInfo } from './dev-tools-info'
function StaticRouteContent({ routerType }: { routerType: 'pages' | 'app' }) { function StaticRouteContent({
routerType,
...props
}: { routerType: 'pages' | 'app' } & ComponentProps<'div'>) {
return ( return (
<article className="dev-tools-info-article"> <article className="dev-tools-info-article" {...props}>
<p className="dev-tools-info-paragraph"> <p className="dev-tools-info-paragraph">
The path{' '} The path{' '}
<code className="dev-tools-info-code">{window.location.pathname}</code>{' '} <code className="dev-tools-info-code">{window.location.pathname}</code>{' '}
...@@ -37,9 +39,12 @@ function StaticRouteContent({ routerType }: { routerType: 'pages' | 'app' }) { ...@@ -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 ( return (
<article className="dev-tools-info-article"> <article className="dev-tools-info-article" {...props}>
<p className="dev-tools-info-paragraph"> <p className="dev-tools-info-paragraph">
The path{' '} The path{' '}
<code className="dev-tools-info-code">{window.location.pathname}</code>{' '} <code className="dev-tools-info-code">{window.location.pathname}</code>{' '}
...@@ -95,7 +100,7 @@ function DynamicRouteContent({ routerType }: { routerType: 'pages' | 'app' }) { ...@@ -95,7 +100,7 @@ function DynamicRouteContent({ routerType }: { routerType: 'pages' | 'app' }) {
) )
} }
const learnMoreLink = { export const learnMoreLink = {
pages: { pages: {
static: static:
'https://nextjs.org/docs/pages/building-your-application/rendering/static-site-generation', 'https://nextjs.org/docs/pages/building-your-application/rendering/static-site-generation',
...@@ -110,32 +115,50 @@ const learnMoreLink = { ...@@ -110,32 +115,50 @@ const learnMoreLink = {
}, },
} as const } 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({ export function RouteInfo({
routeType, isOpen,
close,
routerType, routerType,
routeType,
triggerRef,
...props ...props
}: { }: {
routeType: 'Static' | 'Dynamic' isOpen: boolean
close: () => void
routerType: 'pages' | 'app' routerType: 'pages' | 'app'
} & DevToolsInfoPropsCore & routeType: 'Static' | 'Dynamic'
HTMLProps<HTMLDivElement>) { triggerRef: RefObject<HTMLButtonElement | null>
} & HTMLProps<HTMLDivElement>) {
const isStaticRoute = routeType === 'Static' const isStaticRoute = routeType === 'Static'
const learnMore = isStaticRoute const learnMore = isStaticRoute
? learnMoreLink[routerType].static ? learnMoreLink[routerType].static
: learnMoreLink[routerType].dynamic : learnMoreLink[routerType].dynamic
return ( return (
<DevToolsInfo <DevToolsInfo
title={`${routeType} Route`} title={`${routeType} Route`}
learnMoreLink={learnMore} learnMoreLink={learnMore}
close={close}
isOpen={isOpen}
triggerRef={triggerRef}
{...props} {...props}
> >
{isStaticRoute ? ( <RouteInfoBody routerType={routerType} isStaticRoute={isStaticRoute} />
<StaticRouteContent routerType={routerType} />
) : (
<DynamicRouteContent routerType={routerType} />
)}
</DevToolsInfo> </DevToolsInfo>
) )
} }
......
...@@ -2,16 +2,10 @@ import { DevToolsInfo, type DevToolsInfoPropsCore } from './dev-tools-info' ...@@ -2,16 +2,10 @@ import { DevToolsInfo, type DevToolsInfoPropsCore } from './dev-tools-info'
import { CopyButton } from '../../../copy-button' import { CopyButton } from '../../../copy-button'
import type { HTMLProps } from 'react' import type { HTMLProps } from 'react'
export function TurbopackInfo( export function TurbopackInfoBody(props: React.ComponentProps<'div'>) {
props: DevToolsInfoPropsCore & HTMLProps<HTMLDivElement>
) {
return ( return (
<DevToolsInfo <>
title="Turbopack" <article className="dev-tools-info-article" {...props}>
learnMoreLink="https://nextjs.org/docs/app/api-reference/turbopack"
{...props}
>
<article className="dev-tools-info-article">
<p className="dev-tools-info-paragraph"> <p className="dev-tools-info-paragraph">
Turbopack is an incremental bundler optimized for JavaScript and Turbopack is an incremental bundler optimized for JavaScript and
TypeScript, written in Rust, and built into Next.js. Turbopack can be TypeScript, written in Rust, and built into Next.js. Turbopack can be
...@@ -96,6 +90,20 @@ export function TurbopackInfo( ...@@ -96,6 +90,20 @@ export function TurbopackInfo(
</pre> </pre>
</div> </div>
</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> </DevToolsInfo>
) )
} }
......
...@@ -19,25 +19,56 @@ import { ...@@ -19,25 +19,56 @@ import {
import { ShortcutRecorder } from './shortcut-recorder' import { ShortcutRecorder } from './shortcut-recorder'
export function UserPreferences({ export function UserPreferences({
setPosition,
position,
hide, hide,
scale,
setScale,
hideShortcut, hideShortcut,
setHideShortcut, setHideShortcut,
setScale,
scale,
position,
setPosition,
...props ...props
}: { }: {
hide: () => void
hideShortcut: string | null
setHideShortcut: (value: string | null) => void
setPosition: (position: DevToolsIndicatorPosition) => void setPosition: (position: DevToolsIndicatorPosition) => void
position: DevToolsIndicatorPosition position: DevToolsIndicatorPosition
scale: DevToolsScale scale: DevToolsScale
setScale: (value: DevToolsScale) => void 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 hide: () => void
hideShortcut: string | null hideShortcut: string | null
setHideShortcut: (value: string | null) => void setHideShortcut: (value: string | null) => void
} & DevToolsInfoPropsCore & setPosition: (position: DevToolsIndicatorPosition) => void
Omit<HTMLProps<HTMLDivElement>, 'size'>) { position: DevToolsIndicatorPosition
// derive initial theme from system preference scale: DevToolsScale
setScale: (value: DevToolsScale) => void
}) {
const [theme, setTheme] = useState(getInitialTheme()) const [theme, setTheme] = useState(getInitialTheme())
const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
...@@ -90,7 +121,7 @@ export function UserPreferences({ ...@@ -90,7 +121,7 @@ export function UserPreferences({
} }
return ( return (
<DevToolsInfo title="Preferences" {...props}> <>
<h2 className="dev-tools-info-section-title">General</h2> <h2 className="dev-tools-info-section-title">General</h2>
<div className="preferences-container"> <div className="preferences-container">
<div className="preference-section"> <div className="preference-section">
...@@ -257,7 +288,7 @@ export function UserPreferences({ ...@@ -257,7 +288,7 @@ export function UserPreferences({
</div> </div>
</div> </div>
) : null} ) : 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 type { Corners } from '../../../shared'
import { useCallback, useLayoutEffect, useRef } from 'react' import { useCallback, useLayoutEffect, useRef } from 'react'
import { useDragContext } from './drag-context'
interface Point { interface Point {
x: number x: number
...@@ -19,6 +20,7 @@ export function Draggable({ ...@@ -19,6 +20,7 @@ export function Draggable({
onDragStart, onDragStart,
dragHandleSelector, dragHandleSelector,
disableDrag = false, disableDrag = false,
avoidZone,
...props ...props
}: { }: {
children: React.ReactElement children: React.ReactElement
...@@ -28,9 +30,16 @@ export function Draggable({ ...@@ -28,9 +30,16 @@ export function Draggable({
onDragStart?: () => void onDragStart?: () => void
dragHandleSelector?: string dragHandleSelector?: string
disableDrag?: boolean disableDrag?: boolean
style?: React.CSSProperties
avoidZone?: {
square: number
corner: Corners
padding: number
}
}) { }) {
const { ref, animate, ...drag } = useDrag({ const { ref, animate, ...drag } = useDrag({
disabled: disableDrag, disabled: disableDrag,
handles: useDragContext()?.handles,
threshold: 5, threshold: 5,
onDragStart, onDragStart,
onDragEnd, onDragEnd,
...@@ -56,7 +65,6 @@ export function Draggable({ ...@@ -56,7 +65,6 @@ export function Draggable({
} }
function onAnimationEnd({ corner }: Corner) { function onAnimationEnd({ corner }: Corner) {
// Unset drag translation
setTimeout(() => { setTimeout(() => {
ref.current?.style.removeProperty('translate') ref.current?.style.removeProperty('translate')
setCurrentCorner(corner) setCurrentCorner(corner)
...@@ -74,7 +82,7 @@ export function Draggable({ ...@@ -74,7 +82,7 @@ export function Draggable({
const min = Math.min(...distances.map((d) => d.distance)) const min = Math.min(...distances.map((d) => d.distance))
const nearest = distances.find((d) => d.distance === min) const nearest = distances.find((d) => d.distance === min)
if (!nearest) { if (!nearest) {
// Safety fallback // this should be guarded by an invariant, shouldn't ever happen
return { corner: currentCorner, translation: allCorners[currentCorner] } return { corner: currentCorner, translation: allCorners[currentCorner] }
} }
return { return {
...@@ -94,49 +102,58 @@ export function Draggable({ ...@@ -94,49 +102,58 @@ export function Draggable({
const isRight = corner.includes('right') const isRight = corner.includes('right')
const isBottom = corner.includes('bottom') const isBottom = corner.includes('bottom')
return { // Base positions flush against the chosen corner
x: isRight let x = isRight
? window.innerWidth - scrollbarWidth - offset - triggerWidth ? window.innerWidth - scrollbarWidth - offset - triggerWidth
: 0, : 0
y: isBottom ? window.innerHeight - offset - triggerHeight : 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) 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 { return {
'top-left': { 'top-left': rel(getAbsolutePosition('top-left')),
x: 0 - basePosition.x, 'top-right': rel(getAbsolutePosition('top-right')),
y: 0 - basePosition.y, 'bottom-left': rel(getAbsolutePosition('bottom-left')),
}, 'bottom-right': rel(getAbsolutePosition('bottom-right')),
'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,
},
} }
} }
return ( return (
<div {...props} ref={ref} {...drag} style={{ touchAction: 'none' }}> <div
{...props}
ref={ref}
{...drag}
style={{
touchAction: 'none',
userSelect: 'none',
WebkitUserSelect: 'none',
...props.style,
}}
>
{children} {children}
</div> </div>
) )
...@@ -150,6 +167,7 @@ interface UseDragOptions { ...@@ -150,6 +167,7 @@ interface UseDragOptions {
onAnimationEnd?: (corner: Corner) => void onAnimationEnd?: (corner: Corner) => void
threshold: number // Minimum movement before drag starts threshold: number // Minimum movement before drag starts
dragHandleSelector?: string dragHandleSelector?: string
handles?: Set<HTMLElement>
} }
interface Velocity { interface Velocity {
...@@ -190,6 +208,8 @@ export function useDrag(options: UseDragOptions) { ...@@ -190,6 +208,8 @@ export function useDrag(options: UseDragOptions) {
velocities.current = [] velocities.current = []
ref.current?.classList.remove('dev-tools-grabbing') ref.current?.classList.remove('dev-tools-grabbing')
document.body.style.removeProperty('user-select')
document.body.style.removeProperty('-webkit-user-select')
}, []) }, [])
useLayoutEffect(() => { useLayoutEffect(() => {
...@@ -234,18 +254,23 @@ export function useDrag(options: UseDragOptions) { ...@@ -234,18 +254,23 @@ export function useDrag(options: UseDragOptions) {
} }
function isValidDragHandle(target: EventTarget | null): boolean { function isValidDragHandle(target: EventTarget | null): boolean {
if (!options.dragHandleSelector || !ref.current || !target) { if (!target || !ref.current) return true
return true // If no selector provided, entire element is draggable
}
const element = target as Element if (options.handles && options.handles.size > 0) {
if (!element.matches) { let node: HTMLElement | null = target as HTMLElement
while (node && node !== ref.current) {
if (options.handles.has(node)) return true
node = node.parentElement
}
return false return false
} }
// Check if the target element directly matches the drag handle selector if (options.dragHandleSelector) {
// This excludes children elements, only allowing drag from the exact element const element = target as Element
return element.matches(options.dragHandleSelector) return element.closest(options.dragHandleSelector) !== null
}
return true
} }
function onPointerDown(e: React.PointerEvent) { function onPointerDown(e: React.PointerEvent) {
...@@ -285,6 +310,8 @@ export function useDrag(options: UseDragOptions) { ...@@ -285,6 +310,8 @@ export function useDrag(options: UseDragOptions) {
machine.current = { state: 'drag', pointerId: e.pointerId } machine.current = { state: 'drag', pointerId: e.pointerId }
ref.current?.setPointerCapture(e.pointerId) ref.current?.setPointerCapture(e.pointerId)
ref.current?.classList.add('dev-tools-grabbing') ref.current?.classList.add('dev-tools-grabbing')
document.body.style.userSelect = 'none'
document.body.style.webkitUserSelect = 'none'
options.onDragStart?.() options.onDragStart?.()
} }
} }
...@@ -328,6 +355,13 @@ export function useDrag(options: UseDragOptions) { ...@@ -328,6 +355,13 @@ export function useDrag(options: UseDragOptions) {
options.onDragEnd?.(translation.current, velocity) options.onDragEnd?.(translation.current, velocity)
} }
if (options.disabled) {
return {
ref,
animate,
}
}
return { return {
ref, ref,
onPointerDown, onPointerDown,
......
import { useEffect } from 'react' import { useEffect } from 'react'
export const getShadowRoot = () => {
const portal = document.querySelector('nextjs-portal')
return portal?.shadowRoot
}
export function useFocusTrap( export function useFocusTrap(
rootRef: React.RefObject<HTMLElement | null>, rootRef: React.RefObject<HTMLElement | null>,
triggerRef: React.RefObject<HTMLButtonElement | null> | null, triggerRef: React.RefObject<HTMLButtonElement | null> | null,
...@@ -80,11 +85,12 @@ function getFocusableNodes(node: HTMLElement): [HTMLElement, HTMLElement] | [] { ...@@ -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>, rootRef: React.RefObject<HTMLElement | null>,
triggerRef: React.RefObject<HTMLButtonElement | null>, triggerRef: React.RefObject<HTMLButtonElement | null>,
active: boolean, active: boolean,
close: () => void, close: (reason: 'escape' | 'outside') => void,
ownerDocument?: Document ownerDocument?: Document
) { ) {
useEffect(() => { useEffect(() => {
...@@ -100,32 +106,42 @@ export function useClickOutside( ...@@ -100,32 +106,42 @@ export function useClickOutside(
return return
} }
const cushion = 10
if ( if (
!(rootRef.current?.getBoundingClientRect() !(rootRef.current?.getBoundingClientRect()
? event.clientX >= rootRef.current.getBoundingClientRect()!.left && ? event.clientX >=
event.clientX <= rootRef.current.getBoundingClientRect()!.right && rootRef.current.getBoundingClientRect()!.left - cushion &&
event.clientY >= rootRef.current.getBoundingClientRect()!.top && event.clientX <=
event.clientY <= rootRef.current.getBoundingClientRect()!.bottom rootRef.current.getBoundingClientRect()!.right + cushion &&
event.clientY >=
rootRef.current.getBoundingClientRect()!.top - cushion &&
event.clientY <=
rootRef.current.getBoundingClientRect()!.bottom + cushion
: false) && : false) &&
!(triggerRef.current?.getBoundingClientRect() !(triggerRef.current?.getBoundingClientRect()
? event.clientX >= triggerRef.current.getBoundingClientRect()!.left && ? event.clientX >=
triggerRef.current.getBoundingClientRect()!.left - cushion &&
event.clientX <= event.clientX <=
triggerRef.current.getBoundingClientRect()!.right && triggerRef.current.getBoundingClientRect()!.right + cushion &&
event.clientY >= triggerRef.current.getBoundingClientRect()!.top && event.clientY >=
event.clientY <= triggerRef.current.getBoundingClientRect()!.bottom triggerRef.current.getBoundingClientRect()!.top - cushion &&
event.clientY <=
triggerRef.current.getBoundingClientRect()!.bottom + cushion
: false) : false)
) { ) {
close() close('outside')
} }
} }
function handleKeyDown(event: KeyboardEvent) { function handleKeyDown(event: KeyboardEvent) {
if (event.key === 'Escape') { if (event.key === 'Escape') {
close() close('escape')
} }
} }
ownerDocumentEl?.addEventListener('mousedown', handleClickOutside) ownerDocumentEl?.addEventListener('mousedown', handleClickOutside)
ownerDocumentEl?.addEventListener('keydown', handleKeyDown) ownerDocumentEl?.addEventListener('keydown', handleKeyDown)
return () => { return () => {
......
import { css } from '../../../utils/css'
import { Overlay, type OverlayProps } from '../../overlay/overlay' import { Overlay, type OverlayProps } from '../../overlay/overlay'
export function ErrorOverlayOverlay({ children, ...props }: OverlayProps) { export function ErrorOverlayOverlay({ children, ...props }: OverlayProps) {
return <Overlay {...props}>{children}</Overlay> return <Overlay {...props}>{children}</Overlay>
} }
export const OVERLAY_STYLES = ` export const OVERLAY_STYLES = css`
[data-nextjs-dialog-overlay] { [data-nextjs-dialog-overlay] {
padding: initial; padding: initial;
top: 10vh; top: 10vh;
......
const styles = ` import { css } from '../../utils/css'
const styles = css`
[data-nextjs-dialog-overlay] { [data-nextjs-dialog-overlay] {
position: fixed; position: fixed;
top: 0; top: 0;
......
...@@ -3,7 +3,7 @@ import { useCallback, useState, useRef, useMemo } from 'react' ...@@ -3,7 +3,7 @@ import { useCallback, useState, useRef, useMemo } from 'react'
import { Menu } from '@base-ui-components/react/menu' import { Menu } from '@base-ui-components/react/menu'
import type { SegmentNodeState } from '../../../userspace/app/segment-explorer-node' import type { SegmentNodeState } from '../../../userspace/app/segment-explorer-node'
import { normalizeBoundaryFilename } from '../../../../server/app-render/segment-explorer-path' 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)[]) => { const composeRefs = (...refs: (React.Ref<HTMLButtonElement> | undefined)[]) => {
return (node: HTMLButtonElement | null) => { return (node: HTMLButtonElement | null) => {
...@@ -39,7 +39,7 @@ export function SegmentBoundaryTrigger({ ...@@ -39,7 +39,7 @@ export function SegmentBoundaryTrigger({
const popupRef = useRef<HTMLDivElement>(null) const popupRef = useRef<HTMLDivElement>(null)
// Click outside of popup should close the menu // Click outside of popup should close the menu
useClickOutside( useClickOutsideAndEscape(
popupRef, popupRef,
triggerRef, triggerRef,
isOpen, isOpen,
......
.segment-explorer-content { .segment-explorer-content {
font-size: var(--size-14); font-size: var(--size-14);
padding: 0 8px; padding: 0 8px;
width: 700px; width: 100%;
height: 400px; height: 100%;
max-width: calc(100vw - 40px); overflow: auto;
max-height: calc(100vh - 240px);
} }
.segment-explorer-page-route-bar { .segment-explorer-page-route-bar {
...@@ -132,7 +131,6 @@ ...@@ -132,7 +131,6 @@
.segment-explorer-footer { .segment-explorer-footer {
padding: 8px; padding: 8px;
border-top: 1px solid var(--color-gray-400); border-top: 1px solid var(--color-gray-400);
background-color: var(--color-background-100);
user-select: none; user-select: none;
} }
......
...@@ -118,11 +118,22 @@ export function PageSegmentTree({ ...@@ -118,11 +118,22 @@ export function PageSegmentTree({
}, [tree, isAppRouter]) }, [tree, isAppRouter])
return ( 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} />} {isAppRouter && <PageRouteBar page={page} />}
<div <div
className="segment-explorer-content" className="segment-explorer-content"
data-nextjs-devtool-segment-explorer data-nextjs-devtool-segment-explorer
style={{
flex: '1 1 auto',
overflow: 'auto',
}}
> >
{isAppRouter ? ( {isAppRouter ? (
<PageSegmentTreeLayerPresentation node={tree} level={0} segment="" /> <PageSegmentTreeLayerPresentation node={tree} level={0} segment="" />
......
...@@ -16,6 +16,7 @@ const meta: Meta<typeof Errors> = { ...@@ -16,6 +16,7 @@ const meta: Meta<typeof Errors> = {
export default meta export default meta
type Story = StoryObj<typeof Errors> 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 = { export const Default: Story = {
args: { args: {
getSquashedHydrationErrorDetails: () => null, getSquashedHydrationErrorDetails: () => null,
......
...@@ -10,6 +10,8 @@ import { ...@@ -10,6 +10,8 @@ import {
storybookDefaultOverlayState, storybookDefaultOverlayState,
useStorybookOverlayReducer, useStorybookOverlayReducer,
} from './storybook/use-overlay-reducer' } from './storybook/use-overlay-reducer'
import { DevOverlayContext } from '../dev-overlay.browser'
import { getSquashedHydrationErrorDetails } from '../userspace/pages/hydration-error-state'
const meta: Meta<typeof DevOverlay> = { const meta: Meta<typeof DevOverlay> = {
component: DevOverlay, component: DevOverlay,
...@@ -39,14 +41,20 @@ function getNoSquashedHydrationErrorDetails() { ...@@ -39,14 +41,20 @@ function getNoSquashedHydrationErrorDetails() {
const initialState: OverlayState = { const initialState: OverlayState = {
...storybookDefaultOverlayState, ...storybookDefaultOverlayState,
errors, errors: errors,
} }
export const Default: Story = { export const Default: Story = {
render: function DevOverlayStory() { render: function DevOverlayStory() {
const [state, dispatch] = useStorybookOverlayReducer(initialState) const [state, dispatch] = useStorybookOverlayReducer(initialState)
return ( return (
<> <div
style={{
height: '100vh',
backgroundColor: 'black',
}}
>
{/* TODO: get lots of real hard examples so we have better debug */}
<img <img
src={imgApp} src={imgApp}
style={{ style={{
...@@ -55,19 +63,26 @@ export const Default: Story = { ...@@ -55,19 +63,26 @@ export const Default: Story = {
objectFit: 'contain', objectFit: 'contain',
}} }}
/> />
<DevOverlay <DevOverlayContext
state={state} value={{
dispatch={dispatch} dispatch,
getSquashedHydrationErrorDetails={ getSquashedHydrationErrorDetails:
// Testing like App Router where we no longer quash hydration errors getNoSquashedHydrationErrorDetails,
getNoSquashedHydrationErrorDetails state,
} }}
/> >
</> <DevOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
/>
</DevOverlayContext>
</div>
) )
}, },
} }
// todo: fix story with "Context arg provider" wrapper
export const WithPanel: Story = { export const WithPanel: Story = {
beforeEach: () => { beforeEach: () => {
process.env.__NEXT_DEVTOOL_NEW_PANEL_UI = 'true' process.env.__NEXT_DEVTOOL_NEW_PANEL_UI = 'true'
...@@ -89,14 +104,20 @@ export const WithPanel: Story = { ...@@ -89,14 +104,20 @@ export const WithPanel: Story = {
objectFit: 'contain', objectFit: 'contain',
}} }}
/> />
<DevOverlay <DevOverlayContext
state={state} value={{
dispatch={dispatch} dispatch,
getSquashedHydrationErrorDetails={ getSquashedHydrationErrorDetails:
// Testing like App Router where we no longer quash hydration errors getNoSquashedHydrationErrorDetails,
getNoSquashedHydrationErrorDetails state,
} }}
/> >
<DevOverlay
dispatch={dispatch}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
state={state}
/>
</DevOverlayContext>
</> </>
) )
}, },
......
import { import { createContext, useContext, useRef, useState } from 'react'
ACTION_DEVTOOLS_PANEL_OPEN,
ACTION_ERROR_OVERLAY_OPEN,
type OverlayDispatch,
type OverlayState,
} from './shared'
import { useState } from 'react'
import { ShadowPortal } from './components/shadow-portal' import { ShadowPortal } from './components/shadow-portal'
import { Base } from './styles/base' import { Base } from './styles/base'
import { ComponentStyles } from './styles/component-styles' import { ComponentStyles } from './styles/component-styles'
...@@ -18,8 +10,18 @@ import { RenderError } from './container/runtime-error/render-error' ...@@ -18,8 +10,18 @@ import { RenderError } from './container/runtime-error/render-error'
import { DarkTheme } from './styles/dark-theme' import { DarkTheme } from './styles/dark-theme'
import { useDevToolsScale } from './components/errors/dev-tools-indicator/dev-tools-info/preferences' import { useDevToolsScale } from './components/errors/dev-tools-indicator/dev-tools-info/preferences'
import type { HydrationErrorState } from '../shared/hydration-error' import type { HydrationErrorState } from '../shared/hydration-error'
import { DevToolsIndicator as DevToolsIndicatorNew } from './components/devtools-indicator/devtools-indicator' import type { ReadyRuntimeError } from './utils/get-error-by-type'
import { DevToolsPanel } from './components/devtools-panel/devtools-panel' 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({ export function DevOverlay({
state, state,
...@@ -31,23 +33,11 @@ export function DevOverlay({ ...@@ -31,23 +33,11 @@ export function DevOverlay({
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
}) { }) {
const [scale, setScale] = useDevToolsScale() const [scale, setScale] = useDevToolsScale()
const [isPrevBuildError, setIsPrevBuildError] = useState(false) const [panel, setPanel] = useState<null | PanelStateKind>(null)
const isBuildError = state.buildError !== null const isBuildError = state.buildError !== null
const [selectedIndex, setSelectedIndex] = useState(-1)
if ( const triggerRef = useRef<HTMLButtonElement>(null)
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)
}
return ( return (
<ShadowPortal> <ShadowPortal>
<CssReset /> <CssReset />
...@@ -63,50 +53,56 @@ export function DevOverlay({ ...@@ -63,50 +53,56 @@ export function DevOverlay({
return ( return (
<> <>
{state.showIndicator && {state.showIndicator &&
(process.env.__NEXT_DEVTOOL_NEW_PANEL_UI ? ( process.env.__NEXT_DEVTOOL_NEW_PANEL_UI ? (
<> <>
<DevToolsIndicatorNew <RenderErrorContext
state={state} value={{ runtimeErrors, totalErrorCount }}
dispatch={dispatch} >
errorCount={totalErrorCount} <PanelRouterContext
isBuildError={isBuildError} value={{
/> panel,
setPanel,
{(state.isDevToolsPanelOpen || triggerRef,
state.isErrorOverlayOpen) && ( selectedIndex,
<DevToolsPanel setSelectedIndex,
}}
>
<ErrorOverlay
state={state} state={state}
dispatch={dispatch} dispatch={dispatch}
issueCount={totalErrorCount}
runtimeErrors={runtimeErrors}
getSquashedHydrationErrorDetails={ getSquashedHydrationErrorDetails={
getSquashedHydrationErrorDetails getSquashedHydrationErrorDetails
} }
runtimeErrors={runtimeErrors}
errorCount={totalErrorCount}
/> />
)} <PanelRouter />
</> <DevToolsIndicatorNew />
) : ( </PanelRouterContext>
<> </RenderErrorContext>
<DevToolsIndicator </>
scale={scale} ) : (
setScale={setScale} <>
state={state} <DevToolsIndicator
dispatch={dispatch} scale={scale}
errorCount={totalErrorCount} setScale={setScale}
isBuildError={isBuildError} state={state}
/> dispatch={dispatch}
errorCount={totalErrorCount}
isBuildError={isBuildError}
/>
<ErrorOverlay <ErrorOverlay
state={state} state={state}
dispatch={dispatch} dispatch={dispatch}
getSquashedHydrationErrorDetails={ getSquashedHydrationErrorDetails={
getSquashedHydrationErrorDetails getSquashedHydrationErrorDetails
} }
runtimeErrors={runtimeErrors} runtimeErrors={runtimeErrors}
errorCount={totalErrorCount} errorCount={totalErrorCount}
/> />
</> </>
))} )}
</> </>
) )
}} }}
......
...@@ -39,7 +39,9 @@ export function useShortcuts( ...@@ -39,7 +39,9 @@ export function useShortcuts(
}, [shortcuts]) }, [shortcuts])
} }
function isFocusedOnElement(rootRef: React.RefObject<HTMLElement | null>) { export function isFocusedOnElement(
rootRef: React.RefObject<HTMLElement | null>
) {
const el = getActiveElement(rootRef.current) const el = getActiveElement(rootRef.current)
if (!el) return false 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 { ...@@ -47,11 +47,12 @@ export interface OverlayState {
* which is viewing the "Issues Tab" as a fullscreen. * which is viewing the "Issues Tab" as a fullscreen.
*/ */
isErrorOverlayOpen: boolean isErrorOverlayOpen: boolean
isDevToolsPanelOpen: boolean
devToolsPosition: Corners devToolsPosition: Corners
devToolsPanelPosition: Record<DevtoolsPanelName, Corners>
scale: number scale: number
page: string page: string
} }
type DevtoolsPanelName = string
export type OverlayDispatch = React.Dispatch<DispatcherEvent> export type OverlayDispatch = React.Dispatch<DispatcherEvent>
export const ACTION_STATIC_INDICATOR = 'static-indicator' export const ACTION_STATIC_INDICATOR = 'static-indicator'
...@@ -64,6 +65,7 @@ export const ACTION_UNHANDLED_ERROR = 'unhandled-error' ...@@ -64,6 +65,7 @@ export const ACTION_UNHANDLED_ERROR = 'unhandled-error'
export const ACTION_UNHANDLED_REJECTION = 'unhandled-rejection' export const ACTION_UNHANDLED_REJECTION = 'unhandled-rejection'
export const ACTION_DEBUG_INFO = 'debug-info' export const ACTION_DEBUG_INFO = 'debug-info'
export const ACTION_DEV_INDICATOR = 'dev-indicator' 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_OPEN = 'error-overlay-open'
export const ACTION_ERROR_OVERLAY_CLOSE = 'error-overlay-close' export const ACTION_ERROR_OVERLAY_CLOSE = 'error-overlay-close'
...@@ -79,11 +81,20 @@ export const ACTION_DEVTOOLS_PANEL_CLOSE = 'devtools-panel-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_PANEL_TOGGLE = 'devtools-panel-toggle'
export const ACTION_DEVTOOLS_POSITION = 'devtools-position' 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_DEVTOOLS_SCALE = 'devtools-scale'
export const ACTION_RESTART_SERVER_BUTTON = 'restart-server-button' export const ACTION_RESTART_SERVER_BUTTON = 'restart-server-button'
export const STORAGE_KEY_THEME = '__nextjs-dev-tools-theme' export const STORAGE_KEY_THEME = '__nextjs-dev-tools-theme'
export const STORAGE_KEY_POSITION = '__nextjs-dev-tools-position' 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_SCALE = '__nextjs-dev-tools-scale'
export const STORAGE_KEY_ACTIVE_TAB = '__nextjs-devtools-active-tab' export const STORAGE_KEY_ACTIVE_TAB = '__nextjs-devtools-active-tab'
...@@ -133,6 +144,11 @@ interface DevIndicatorAction { ...@@ -133,6 +144,11 @@ interface DevIndicatorAction {
devIndicator: DevIndicatorServerState devIndicator: DevIndicatorServerState
} }
interface DevIndicatorSetAction {
type: typeof ACTION_DEV_INDICATOR_SET
disabled: boolean
}
export interface ErrorOverlayOpenAction { export interface ErrorOverlayOpenAction {
type: typeof ACTION_ERROR_OVERLAY_OPEN type: typeof ACTION_ERROR_OVERLAY_OPEN
} }
...@@ -157,21 +173,17 @@ export interface RenderingIndicatorHideAction { ...@@ -157,21 +173,17 @@ export interface RenderingIndicatorHideAction {
type: typeof ACTION_RENDERING_INDICATOR_HIDE 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 { export interface DevToolsIndicatorPositionAction {
type: typeof ACTION_DEVTOOLS_POSITION type: typeof ACTION_DEVTOOLS_POSITION
devToolsPosition: Corners devToolsPosition: Corners
} }
export interface DevToolsPanelPositionAction {
type: typeof ACTION_DEVTOOLS_PANEL_POSITION
key: string
devToolsPanelPosition: Corners
}
export interface DevToolsScaleAction { export interface DevToolsScaleAction {
type: typeof ACTION_DEVTOOLS_SCALE type: typeof ACTION_DEVTOOLS_SCALE
scale: number scale: number
...@@ -205,13 +217,12 @@ export type DispatcherEvent = ...@@ -205,13 +217,12 @@ export type DispatcherEvent =
| BuildingIndicatorHideAction | BuildingIndicatorHideAction
| RenderingIndicatorShowAction | RenderingIndicatorShowAction
| RenderingIndicatorHideAction | RenderingIndicatorHideAction
| DevToolsPanelOpenAction
| DevToolsPanelCloseAction
| DevToolsPanelToggleAction
| DevToolsIndicatorPositionAction | DevToolsIndicatorPositionAction
| DevToolsPanelPositionAction
| DevToolsScaleAction | DevToolsScaleAction
| DevToolUpdateRouteStateAction | DevToolUpdateRouteStateAction
| RestartServerButtonAction | RestartServerButtonAction
| DevIndicatorSetAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: new frame + v8 // 1st group: new frame + v8
...@@ -231,6 +242,41 @@ function getStackIgnoringStrictMode(stack: string | undefined) { ...@@ -231,6 +242,41 @@ function getStackIgnoringStrictMode(stack: string | undefined) {
const shouldDisableDevIndicator = const shouldDisableDevIndicator =
process.env.__NEXT_DEV_INDICATOR?.toString() === 'false' 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< export const INITIAL_OVERLAY_STATE: Omit<
OverlayState, OverlayState,
'isErrorOverlayOpen' | 'routerType' 'isErrorOverlayOpen' | 'routerType'
...@@ -252,9 +298,12 @@ export const INITIAL_OVERLAY_STATE: Omit< ...@@ -252,9 +298,12 @@ export const INITIAL_OVERLAY_STATE: Omit<
refreshState: { type: 'idle' }, refreshState: { type: 'idle' },
versionInfo: { installed: '0.0.0', staleness: 'unknown' }, versionInfo: { installed: '0.0.0', staleness: 'unknown' },
debugInfo: { devtoolsFrontendUrl: undefined }, debugInfo: { devtoolsFrontendUrl: undefined },
isDevToolsPanelOpen: false,
showRestartServerButton: false, showRestartServerButton: false,
devToolsPosition: 'bottom-left', devToolsPosition: getStoredPosition(),
devToolsPanelPosition: {
[STORE_KEY_SHARED_PANEL_LOCATION]: getStoredPanelPosition(),
},
scale: NEXT_DEV_TOOLS_SCALE.Medium, scale: NEXT_DEV_TOOLS_SCALE.Medium,
page: '', page: '',
} }
...@@ -390,6 +439,9 @@ export function useErrorOverlayReducer( ...@@ -390,6 +439,9 @@ export function useErrorOverlayReducer(
case ACTION_VERSION_INFO: { case ACTION_VERSION_INFO: {
return { ...state, versionInfo: action.versionInfo } return { ...state, versionInfo: action.versionInfo }
} }
case ACTION_DEV_INDICATOR_SET: {
return { ...state, disableDevIndicator: action.disabled }
}
case ACTION_DEV_INDICATOR: { case ACTION_DEV_INDICATOR: {
return { return {
...state, ...state,
...@@ -419,18 +471,20 @@ export function useErrorOverlayReducer( ...@@ -419,18 +471,20 @@ export function useErrorOverlayReducer(
case ACTION_RENDERING_INDICATOR_HIDE: { case ACTION_RENDERING_INDICATOR_HIDE: {
return { ...state, renderingIndicator: false } 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: { case ACTION_DEVTOOLS_POSITION: {
return { ...state, devToolsPosition: action.devToolsPosition } return { ...state, devToolsPosition: action.devToolsPosition }
} }
case ACTION_DEVTOOLS_PANEL_POSITION: {
return {
...state,
devToolsPanelPosition: {
...state.devToolsPanelPosition,
[action.key]: action.devToolsPanelPosition,
},
}
}
case ACTION_DEVTOOLS_SCALE: { case ACTION_DEVTOOLS_SCALE: {
return { ...state, scale: action.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