Commit a358d2ab authored by RobPruzan's avatar RobPruzan

backwards compatible

parent d2207067
This diff is collapsed.
import type { StorybookConfig } from '@storybook/react-webpack5' import type { StorybookConfig } from '@storybook/react-webpack5'
import { join, dirname } from 'path' import { join, dirname, resolve } from 'path'
import { fileURLToPath } from 'url'
/** /**
* This function is used to resolve the absolute path of a package. * This function is used to resolve the absolute path of a package.
* It is needed in projects that use Yarn PnP or are set up within a monorepo. * It is needed in projects that use Yarn PnP or are set up within a monorepo.
...@@ -7,6 +9,9 @@ import { join, dirname } from 'path' ...@@ -7,6 +9,9 @@ import { join, dirname } from 'path'
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'],
addons: [ addons: [
...@@ -32,5 +37,48 @@ const config: StorybookConfig = { ...@@ -32,5 +37,48 @@ const config: StorybookConfig = {
}, },
}, },
}), }),
webpackFinal: async (config) => {
// Find and override CSS rule to use the devtool style injection
const cssRule = config.module?.rules?.find((rule) => {
if (typeof rule !== 'object' || !rule) return false
if ('test' in rule && rule.test instanceof RegExp) {
return rule.test.test('.css')
}
return false
})
if (
cssRule &&
typeof cssRule === 'object' &&
'use' in cssRule &&
Array.isArray(cssRule.use)
) {
// Find the style-loader in the use array
const styleLoaderIndex = cssRule.use.findIndex((loader) => {
if (typeof loader === 'string') return loader.includes('style-loader')
if (typeof loader === 'object' && loader && 'loader' in loader) {
return loader.loader?.includes('style-loader')
}
return false
})
if (styleLoaderIndex !== -1) {
// Replace with our custom configuration
cssRule.use[styleLoaderIndex] = {
loader: require.resolve('style-loader'),
options: {
injectType: 'styleTag',
insert: resolve(
dirname(fileURLToPath(import.meta.url)),
'../src/build/webpack/loaders/devtool/devtool-style-inject.js'
),
},
}
}
}
return config
},
} }
export default config export default config
...@@ -7,7 +7,7 @@ type TooltipDirection = 'top' | 'bottom' | 'left' | 'right' ...@@ -7,7 +7,7 @@ type TooltipDirection = 'top' | 'bottom' | 'left' | 'right'
interface TooltipProps { interface TooltipProps {
children: React.ReactNode children: React.ReactNode
title: string title: string | null
direction?: TooltipDirection direction?: TooltipDirection
container?: HTMLElement | React.RefObject<HTMLElement> container?: HTMLElement | React.RefObject<HTMLElement>
arrowSize?: number arrowSize?: number
...@@ -32,6 +32,9 @@ export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>( ...@@ -32,6 +32,9 @@ export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>(
}, },
ref ref
) { ) {
if (!title) {
return children
}
return ( return (
<BaseTooltip.Provider> <BaseTooltip.Provider>
<BaseTooltip.Root delay={0}> <BaseTooltip.Root delay={0}>
......
...@@ -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,26 @@ function DevOverlayRoot({ ...@@ -208,14 +216,26 @@ 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 />
</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,
......
...@@ -16,35 +16,23 @@ import { ...@@ -16,35 +16,23 @@ import {
ACTION_ERROR_OVERLAY_OPEN, ACTION_ERROR_OVERLAY_OPEN,
} 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 { useRenderErrorContext } from '../../dev-overlay'
import { usePanelContext } from '../../menu/context'
export const INDICATOR_PADDING = 20 export const INDICATOR_PADDING = 20
export function DevToolsIndicator({ export function DevToolsIndicatorNew() {
state, const { state, dispatch } = useDevOverlayContext()
dispatch, const { setOpen, triggerRef, setPanel } = usePanelContext()
errorCount,
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 = () => { // console.log('rendering next logo')
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 (
// what is this toast doing??
// why are u hiding my precious
<Toast <Toast
data-nextjs-toast data-nextjs-toast
style={ style={
...@@ -54,16 +42,17 @@ export function DevToolsIndicator({ ...@@ -54,16 +42,17 @@ 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.isDevToolsPanelOpen || state.isErrorOverlayOpen // state.isDevToolsPanelOpen || state.isErrorOverlayOpen
? 'hidden' // ? 'hidden'
: 'visible', // : 'visible' <-- todo add hiding,
} as CSSProperties } as CSSProperties
} }
> >
<Draggable <Draggable
padding={INDICATOR_PADDING} padding={INDICATOR_PADDING}
onDragStart={() => setOpen(false)} // er i don't think this makes sense in the context of the refactor, come back to this
onDragStart={() => setOpen(null)}
position={state.devToolsPosition} position={state.devToolsPosition}
setPosition={(p) => { setPosition={(p) => {
dispatch({ dispatch({
...@@ -75,19 +64,12 @@ export function DevToolsIndicator({ ...@@ -75,19 +64,12 @@ export function DevToolsIndicator({
> >
{/* Trigger */} {/* Trigger */}
<NextLogo <NextLogo
aria-haspopup="menu" onTriggerClick={() => {
aria-expanded={open} // dispatch({ type: ACTION_DEVTOOLS_PANEL_TOGGLE })
aria-controls="nextjs-dev-tools-menu" // onTriggerClick()
aria-label={`${open ? 'Close' : 'Open'} Next.js Dev Tools`} setPanel(prev => prev === 'panel-selector' ? null : 'panel-selector')
data-nextjs-dev-tools-button }}
disabled={state.disableDevIndicator} ref={triggerRef}
issueCount={errorCount}
onTriggerClick={toggleDevToolsPanel}
toggleErrorOverlay={enableErrorOverlayMode}
isDevBuilding={state.buildingIndicator}
isDevRendering={state.renderingIndicator}
isBuildError={isBuildError}
scale={state.scale}
/> />
</Draggable> </Draggable>
</Toast> </Toast>
......
...@@ -7,50 +7,51 @@ import { useMinimumLoadingTimeMultiple } from './hooks/use-minimum-loading-time- ...@@ -7,50 +7,51 @@ 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 {
isDevBuilding: boolean ACTION_DEVTOOLS_PANEL_OPEN,
isDevRendering: boolean ACTION_DEVTOOLS_PANEL_TOGGLE,
isBuildError: boolean ACTION_ERROR_OVERLAY_OPEN,
onTriggerClick: () => void } from '../../shared'
toggleErrorOverlay: () => void import { usePanelContext } from '../../menu/context'
scale: DevToolsScale import { OVERLAYS } from '../errors/dev-tools-indicator/dev-tools-indicator'
}
const SHORT_DURATION_MS = 150 const SHORT_DURATION_MS = 150
export function NextLogo({ export function NextLogo({onTriggerClick, ...buttonProps}: {onTriggerClick: () => void} &React.ComponentProps<'button'>) {
disabled, const { state, dispatch } = useDevOverlayContext()
issueCount, const { totalErrorCount } = useRenderErrorContext()
isDevBuilding, const SIZE = 36 / state.scale
isDevRendering, // const [open, setOpen] = useState(false)
isBuildError, // todo: rename better: its indicator menu open something something
onTriggerClick, // also wait we are duplicating this totally need to dedupe
toggleErrorOverlay, const { open, setOpen, setPanel } = usePanelContext()
scale = 1, const isMenuOpen = open === OVERLAYS.Root
...props
}: Props) { const hasError = totalErrorCount > 0
const SIZE = 36 / scale
const hasError = issueCount > 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 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(() => {
setIsErrorExpanded(hasError) setIsErrorExpanded(hasError)
}, [hasError]) }, [hasError])
console.log('its time for next logo',state.disableDevIndicator);
return ( return (
<div <div
...@@ -61,7 +62,10 @@ export function NextLogo({ ...@@ -61,7 +62,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 +400,31 @@ export function NextLogo({ ...@@ -396,15 +400,31 @@ 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={() => {
{...props}
onTriggerClick()
// this is really stupid, especially with setOpen
// setPanel(prev => prev === 'panel-selector' ? null : 'panel-selector')
// dispatch({ type: ACTION_DEVTOOLS_PANEL_TOGGLE })
}}
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 +432,46 @@ export function NextLogo({ ...@@ -412,42 +432,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={() => {
dispatch({ type: ACTION_ERROR_OVERLAY_OPEN })
// Open the DevTools panel to view as error overlay mode.
dispatch({ type: ACTION_DEVTOOLS_PANEL_OPEN })
}}
> >
{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)
......
...@@ -37,10 +37,6 @@ export function DevToolsPanelTab({ ...@@ -37,10 +37,6 @@ export function DevToolsPanelTab({
case 'settings': case 'settings':
return ( return (
<SettingsTab <SettingsTab
devToolsPosition={devToolsPosition}
scale={scale}
handlePositionChange={handlePositionChange}
handleScaleChange={handleScaleChange}
/> />
) )
case 'route': case 'route':
......
...@@ -7,8 +7,7 @@ function SegmentsExplorer({ ...@@ -7,8 +7,7 @@ function SegmentsExplorer({
routerType: 'app' | 'pages' routerType: 'app' | 'pages'
page: string page: string
}) { }) {
const isAppRouter = routerType === 'app' return <PageSegmentTree />
return <PageSegmentTree isAppRouter={isAppRouter} page={page} />
} }
export function SegmentsExplorerTab({ export function SegmentsExplorerTab({
......
...@@ -2,12 +2,20 @@ import type { Corners } from '../../../shared' ...@@ -2,12 +2,20 @@ import type { Corners } from '../../../shared'
import { useTheme } from '../hooks/use-theme' import { useTheme } from '../hooks/use-theme'
import { Select } from '../../select/select' import { Select } from '../../select/select'
import { STORAGE_KEY_THEME, NEXT_DEV_TOOLS_SCALE } from '../../../shared' import {
STORAGE_KEY_THEME,
NEXT_DEV_TOOLS_SCALE,
ACTION_DEVTOOLS_POSITION,
STORAGE_KEY_POSITION,
ACTION_DEVTOOLS_SCALE,
STORAGE_KEY_SCALE,
} from '../../../shared'
import { css } from '../../../utils/css' import { css } from '../../../utils/css'
import LightIcon from '../../../icons/light-icon' import LightIcon from '../../../icons/light-icon'
import DarkIcon from '../../../icons/dark-icon' import DarkIcon from '../../../icons/dark-icon'
import SystemIcon from '../../../icons/system-icon' import SystemIcon from '../../../icons/system-icon'
import EyeIcon from '../../../icons/eye-icon' import EyeIcon from '../../../icons/eye-icon'
import { useDevOverlayContext } from '../../../../dev-overlay.browser'
function ThemeIcon({ theme }: { theme: 'dark' | 'light' | 'system' }) { function ThemeIcon({ theme }: { theme: 'dark' | 'light' | 'system' }) {
switch (theme) { switch (theme) {
...@@ -22,17 +30,7 @@ function ThemeIcon({ theme }: { theme: 'dark' | 'light' | 'system' }) { ...@@ -22,17 +30,7 @@ function ThemeIcon({ theme }: { theme: 'dark' | 'light' | 'system' }) {
} }
} }
export function SettingsTab({ 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 [theme, setTheme] = useTheme()
const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
...@@ -73,6 +71,7 @@ export function SettingsTab({ ...@@ -73,6 +71,7 @@ export function SettingsTab({
// https://github.com/vercel/next.js/pull/80005 // https://github.com/vercel/next.js/pull/80005
}) })
} }
const { dispatch, state } = useDevOverlayContext()
function hide() { function hide() {
fetch('/__nextjs_disable_dev_indicator', { fetch('/__nextjs_disable_dev_indicator', {
...@@ -112,8 +111,14 @@ export function SettingsTab({ ...@@ -112,8 +111,14 @@ export function SettingsTab({
<Select <Select
id="position" id="position"
name="position" name="position"
value={devToolsPosition} value={state.devToolsPosition}
onChange={handlePositionChange} onChange={(e: React.ChangeEvent<HTMLSelectElement>) => {
dispatch({
type: ACTION_DEVTOOLS_POSITION,
devToolsPosition: e.target.value as Corners,
})
localStorage.setItem(STORAGE_KEY_POSITION, e.target.value)
}}
> >
<option value="bottom-left">Bottom Left</option> <option value="bottom-left">Bottom Left</option>
<option value="bottom-right">Bottom Right</option> <option value="bottom-right">Bottom Right</option>
...@@ -132,8 +137,14 @@ export function SettingsTab({ ...@@ -132,8 +137,14 @@ export function SettingsTab({
<Select <Select
id="size" id="size"
name="size" name="size"
value={scale} value={state.scale}
onChange={handleScaleChange} onChange={(e: React.ChangeEvent<HTMLSelectElement>) => {
dispatch({
type: ACTION_DEVTOOLS_SCALE,
scale: Number(e.target.value),
})
localStorage.setItem(STORAGE_KEY_SCALE, e.target.value)
}}
> >
{Object.entries(NEXT_DEV_TOOLS_SCALE).map(([key, value]) => { {Object.entries(NEXT_DEV_TOOLS_SCALE).map(([key, value]) => {
return ( return (
......
...@@ -252,14 +252,38 @@ export function DevToolsPanel({ ...@@ -252,14 +252,38 @@ export function DevToolsPanel({
{!isFullscreen && ( {!isFullscreen && (
<> <>
<ResizeHandle direction="top" /> <ResizeHandle
<ResizeHandle direction="right" /> position={state.devToolsPanelPosition}
<ResizeHandle direction="bottom" /> direction="top"
<ResizeHandle direction="left" /> />
<ResizeHandle direction="top-left" /> <ResizeHandle
<ResizeHandle direction="top-right" /> position={state.devToolsPanelPosition}
<ResizeHandle direction="bottom-left" /> direction="right"
<ResizeHandle direction="bottom-right" /> />
<ResizeHandle
position={state.devToolsPanelPosition}
direction="bottom"
/>
<ResizeHandle
position={state.devToolsPanelPosition}
direction="left"
/>
<ResizeHandle
position={state.devToolsPanelPosition}
direction="top-left"
/>
<ResizeHandle
position={state.devToolsPanelPosition}
direction="top-right"
/>
<ResizeHandle
position={state.devToolsPanelPosition}
direction="bottom-left"
/>
<ResizeHandle
position={state.devToolsPanelPosition}
direction="bottom-right"
/>
</> </>
)} )}
</> </>
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
/* todo smarter z index */ /* todo smarter z index */
z-index: -1; z-index: -1;
pointer-events: none; pointer-events: none;
/* a normal exit animation curve- at this point the exit animation is */ /* a normal exit animation curve- aat this point the exit animation is */
/* 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? */
...@@ -20,14 +20,14 @@ ...@@ -20,14 +20,14 @@
/* 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, 1);
} }
.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-100);
} }
.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-100);
} }
.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-md) var(--rounded-md) 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-md) var(--rounded-md);
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-md) 0 0 var(--rounded-md);
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-md) var(--rounded-md) 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,19 @@ import type { Corners } from '../../../shared' ...@@ -3,14 +3,19 @@ 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, storageKey,
// devToolsPosition,
draggingDirection, draggingDirection,
setDraggingDirection, setDraggingDirection,
} = useResize() } = useResize()
...@@ -44,13 +49,13 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => { ...@@ -44,13 +49,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
} }
...@@ -123,10 +128,7 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => { ...@@ -123,10 +128,7 @@ export const ResizeHandle = ({ direction }: { direction: ResizeDirection }) => {
// invariant ref exists // 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)
......
...@@ -22,9 +22,10 @@ interface ResizeContextValue { ...@@ -22,9 +22,10 @@ interface ResizeContextValue {
resizeRef: RefObject<HTMLElement | null> resizeRef: RefObject<HTMLElement | null>
minWidth: number minWidth: number
minHeight: number minHeight: number
devToolsPosition: Corners // devToolsPosition: Corners
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 +45,8 @@ const constrainDimensions = (params: { ...@@ -44,8 +45,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 +60,7 @@ const parseResizeLocalStorage = () => { ...@@ -59,7 +60,7 @@ const parseResizeLocalStorage = () => {
} }
return null return null
} catch (e) { } catch (e) {
localStorage.removeItem(STORAGE_KEY_DIMENSIONS) localStorage.removeItem(key)
return null return null
} }
} }
...@@ -70,6 +71,7 @@ interface ResizeProviderProps { ...@@ -70,6 +71,7 @@ interface ResizeProviderProps {
minWidth?: number minWidth?: number
minHeight?: number minHeight?: number
devToolsPosition: Corners devToolsPosition: Corners
storageKey?: string
} }
children: React.ReactNode children: React.ReactNode
} }
...@@ -80,6 +82,8 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => { ...@@ -80,6 +82,8 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => {
const [draggingDirection, setDraggingDirection] = const [draggingDirection, setDraggingDirection] =
useState<ResizeDirection | null>(null) useState<ResizeDirection | null>(null)
const storageKey = value.storageKey ?? STORAGE_KEY_DIMENSIONS
useLayoutEffect(() => { useLayoutEffect(() => {
const applyConstrainedDimensions = () => { const applyConstrainedDimensions = () => {
if (!value.resizeRef.current) return if (!value.resizeRef.current) return
...@@ -91,7 +95,7 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => { ...@@ -91,7 +95,7 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => {
// an optimization if this is too expensive is to maintain the current // 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 // container size in a ref and update it on resize, which is essentially
// what we're doing here, just dumber // what we're doing here, just dumber
const dim = parseResizeLocalStorage() const dim = parseResizeLocalStorage(storageKey)
if (!dim) { if (!dim) {
return return
} }
...@@ -110,7 +114,7 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => { ...@@ -110,7 +114,7 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => {
window.addEventListener('resize', applyConstrainedDimensions) window.addEventListener('resize', applyConstrainedDimensions)
return () => return () =>
window.removeEventListener('resize', applyConstrainedDimensions) window.removeEventListener('resize', applyConstrainedDimensions)
}, [value.resizeRef, minWidth, minHeight]) }, [value.resizeRef, minWidth, minHeight, storageKey])
return ( return (
<ResizeContext.Provider <ResizeContext.Provider
...@@ -118,9 +122,10 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => { ...@@ -118,9 +122,10 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => {
resizeRef: value.resizeRef, resizeRef: value.resizeRef,
minWidth, minWidth,
minHeight, minHeight,
devToolsPosition: value.devToolsPosition, // devToolsPosition: value.devToolsPosition,
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 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 +36,7 @@ const meta: Meta<typeof DevToolsIndicator> = { ...@@ -36,7 +36,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 = {
...@@ -68,36 +68,31 @@ const state: OverlayState = { ...@@ -68,36 +68,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}
}, />
),
} }
...@@ -3,8 +3,6 @@ import { ...@@ -3,8 +3,6 @@ import {
ACTION_ERROR_OVERLAY_OPEN, ACTION_ERROR_OVERLAY_OPEN,
ACTION_ERROR_OVERLAY_TOGGLE, ACTION_ERROR_OVERLAY_TOGGLE,
STORAGE_KEY_POSITION, STORAGE_KEY_POSITION,
type OverlayDispatch,
type OverlayState,
} from '../../../shared' } from '../../../shared'
import { useState, useEffect, useRef, createContext, useContext } from 'react' import { useState, useEffect, useRef, createContext, useContext } from 'react'
...@@ -27,20 +25,16 @@ import { ...@@ -27,20 +25,16 @@ import {
} from './dev-tools-info/preferences' } from './dev-tools-info/preferences'
import { Draggable } from './draggable' import { Draggable } from './draggable'
import { SegmentsExplorer } from './dev-tools-info/segments-explorer' import { SegmentsExplorer } from './dev-tools-info/segments-explorer'
import { useDevOverlayContext } from '../../../../dev-overlay.browser'
import { useRenderErrorContext } from '../../../dev-overlay'
import { css } from '../../../utils/css'
// TODO: add E2E tests to cover different scenarios // TODO: add E2E tests to cover different scenarios
export function DevToolsIndicator({ export function DevToolsIndicator({
state, scale,
errorCount, setScale,
isBuildError,
...props
}: { }: {
state: OverlayState
dispatch: OverlayDispatch
errorCount: number
isBuildError: boolean
scale: DevToolsScale scale: DevToolsScale
setScale: (value: DevToolsScale) => void setScale: (value: DevToolsScale) => void
}) { }) {
...@@ -49,23 +43,15 @@ export function DevToolsIndicator({ ...@@ -49,23 +43,15 @@ export function DevToolsIndicator({
return ( return (
<DevToolsPopover <DevToolsPopover
routerType={state.routerType} isDevToolsIndicatorVisible={isDevToolsIndicatorVisible}
semver={state.versionInfo.installed} scale={scale}
issueCount={errorCount} setScale={setScale}
isDevBuilding={state.buildingIndicator}
isDevRendering={state.renderingIndicator}
isStaticRoute={state.staticIndicator}
hide={() => { hide={() => {
setIsDevToolsIndicatorVisible(false) setIsDevToolsIndicatorVisible(false)
fetch('/__nextjs_disable_dev_indicator', { fetch('/__nextjs_disable_dev_indicator', {
method: 'POST', method: 'POST',
}) })
}} }}
isTurbopack={!!process.env.TURBOPACK}
disabled={state.disableDevIndicator || !isDevToolsIndicatorVisible}
isBuildError={isBuildError}
page={state.page}
{...props}
/> />
) )
} }
...@@ -80,7 +66,7 @@ interface C { ...@@ -80,7 +66,7 @@ interface C {
const Context = createContext({} as C) const Context = createContext({} as C)
const OVERLAYS = { export const OVERLAYS = {
Root: 'root', Root: 'root',
Turbo: 'turbo', Turbo: 'turbo',
Route: 'route', Route: 'route',
...@@ -93,38 +79,28 @@ export type Overlays = (typeof OVERLAYS)[keyof typeof OVERLAYS] ...@@ -93,38 +79,28 @@ export type Overlays = (typeof OVERLAYS)[keyof typeof OVERLAYS]
const INDICATOR_PADDING = 20 const INDICATOR_PADDING = 20
function DevToolsPopover({ function DevToolsPopover({
routerType,
disabled,
issueCount,
isDevBuilding,
isDevRendering,
isStaticRoute,
isTurbopack,
isBuildError,
hide, hide,
dispatch,
scale, scale,
setScale, setScale,
page, isDevToolsIndicatorVisible,
}: { }: {
routerType: 'pages' | 'app'
disabled: boolean
issueCount: number
isStaticRoute: boolean
semver: string | undefined
isDevBuilding: boolean
isDevRendering: boolean
isTurbopack: boolean
isBuildError: boolean
hide: () => void hide: () => void
dispatch: OverlayDispatch
scale: DevToolsScale scale: DevToolsScale
setScale: (value: DevToolsScale) => void setScale: (value: DevToolsScale) => void
page: string isDevToolsIndicatorVisible: boolean
}) { }) {
const { state, dispatch } = useDevOverlayContext()
const routerType = state.routerType
const issueCount = useRenderErrorContext().totalErrorCount
const isDevBuilding = state.buildingIndicator
const isDevRendering = state.renderingIndicator
const isStaticRoute = state.staticIndicator
const isTurbopack = !!process.env.TURBOPACK
const disabled = state.disableDevIndicator || !isDevToolsIndicatorVisible
const page = state.page
const menuRef = useRef<HTMLDivElement>(null) const menuRef = useRef<HTMLDivElement>(null)
const triggerRef = useRef<HTMLButtonElement | null>(null) const triggerRef = useRef<HTMLButtonElement | null>(null)
const [open, setOpen] = useState<Overlays | null>(null) const [open, setOpen] = useState<Overlays | null>(null)
const [position, setPosition] = useState(getInitialPosition()) const [position, setPosition] = useState(getInitialPosition())
const [selectedIndex, setSelectedIndex] = useState(-1) const [selectedIndex, setSelectedIndex] = useState(-1)
...@@ -240,7 +216,10 @@ function DevToolsPopover({ ...@@ -240,7 +216,10 @@ function DevToolsPopover({
if (open === OVERLAYS.Root) { if (open === OVERLAYS.Root) {
setOpen(null) setOpen(null)
} else { } else {
console.log('opening overlays', OVERLAYS.Root)
setOpen(OVERLAYS.Root) setOpen(OVERLAYS.Root)
// flush sync?
setTimeout(() => { setTimeout(() => {
select('first') select('first')
}) })
...@@ -264,6 +243,7 @@ function DevToolsPopover({ ...@@ -264,6 +243,7 @@ function DevToolsPopover({
} }
const [vertical, horizontal] = position.split('-', 2) const [vertical, horizontal] = position.split('-', 2)
// here it is ah
const popover = { [vertical]: 'calc(100% + 8px)', [horizontal]: 0 } const popover = { [vertical]: 'calc(100% + 8px)', [horizontal]: 0 }
return ( return (
...@@ -276,6 +256,8 @@ function DevToolsPopover({ ...@@ -276,6 +256,8 @@ function DevToolsPopover({
boxShadow: 'none', boxShadow: 'none',
[vertical]: `${INDICATOR_PADDING}px`, [vertical]: `${INDICATOR_PADDING}px`,
[horizontal]: `${INDICATOR_PADDING}px`, [horizontal]: `${INDICATOR_PADDING}px`,
// position:'absolute'
} as CSSProperties } as CSSProperties
} }
> >
...@@ -302,19 +284,16 @@ function DevToolsPopover({ ...@@ -302,19 +284,16 @@ function DevToolsPopover({
toggleErrorOverlay={toggleErrorOverlay} toggleErrorOverlay={toggleErrorOverlay}
isDevBuilding={isDevBuilding} isDevBuilding={isDevBuilding}
isDevRendering={isDevRendering} isDevRendering={isDevRendering}
isBuildError={isBuildError} isBuildError={state.buildError !== null}
scale={scale} scale={scale}
/> />
</Draggable> </Draggable>
{/* Route Info */} {/* Route Info */}
<RouteInfo <RouteInfo
isOpen={isRouteInfoOpen}
close={closeToRootMenu} close={closeToRootMenu}
triggerRef={triggerRef}
style={popover} style={popover}
routerType={routerType} isOpen={isRouteInfoOpen}
routeType={isStaticRoute ? 'Static' : 'Dynamic'}
/> />
{/* Turbopack Info */} {/* Turbopack Info */}
...@@ -524,7 +503,7 @@ function IssueCount({ children }: { children: number }) { ...@@ -524,7 +503,7 @@ function IssueCount({ children }: { children: number }) {
////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////
export const DEV_TOOLS_INDICATOR_STYLES = ` export const DEV_TOOLS_INDICATOR_STYLES = css`
.dev-tools-indicator-menu { .dev-tools-indicator-menu {
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
display: flex; display: flex;
...@@ -535,6 +514,7 @@ export const DEV_TOOLS_INDICATOR_STYLES = ` ...@@ -535,6 +514,7 @@ export const DEV_TOOLS_INDICATOR_STYLES = `
background-clip: padding-box; background-clip: padding-box;
box-shadow: var(--shadow-menu); box-shadow: var(--shadow-menu);
border-radius: var(--rounded-xl); border-radius: var(--rounded-xl);
/* this was changed to absolute, we have it fixed for the other dev indicator menu along with removing border incase something went wrong we should revert this*/
position: absolute; position: absolute;
font-family: var(--font-stack-sans); font-family: var(--font-stack-sans);
z-index: 3; z-index: 3;
......
import React from 'react'
interface DevToolsHeaderProps {
title: React.ReactNode
onBack: () => void
children?: React.ReactNode
}
export function DevToolsHeader({
title,
onBack,
children,
ref,
}: DevToolsHeaderProps & { ref?: React.Ref<HTMLDivElement> }) {
return (
<div className="dev-tools-info-header" ref={ref}>
<button
className="dev-tools-info-close-button"
onClick={onBack}
aria-label="Go back"
>
<IconChevronLeft />
</button>
<h3 className="dev-tools-info-title" style={{ margin: 0 }}>
{title}
</h3>
{children}
</div>
)
}
function IconChevronLeft() {
return (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M5.14645 8.70703C4.75595 8.31651 4.75595 7.68349 5.14645 7.29297L10.5 1.93945L11.5605 3L6.56051 8L11.5605 13L10.5 14.0605L5.14645 8.70703Z"
fill="currentColor"
/>
</svg>
)
}
import { useRef } from 'react'
import { MENU_DURATION_MS, useClickOutside, useFocusTrap } from '../utils'
import { useDelayedRender } from '../../../../hooks/use-delayed-render'
import { css } from '../../../../utils/css'
export interface DevToolsInfoPropsCore {
isOpen: boolean
triggerRef: React.RefObject<HTMLButtonElement | null>
close: () => void
}
export interface DevToolsInfoProps extends DevToolsInfoPropsCore {
title: React.ReactNode
children: React.ReactNode
learnMoreLink?: string
}
export function DevToolsInfo2({
title,
children,
learnMoreLink,
isOpen,
triggerRef,
close,
...props
}: DevToolsInfoProps) {
const ref = useRef<HTMLDivElement | null>(null)
const closeButtonRef = useRef<HTMLButtonElement | null>(null)
const { mounted, rendered } = useDelayedRender(isOpen, {
// Intentionally no fade in, makes the UI feel more immediate
enterDelay: 0,
// Graceful fade out to confirm that the UI did not break
exitDelay: MENU_DURATION_MS,
})
useFocusTrap(ref, triggerRef, isOpen, () => {
// Bring focus to close button, so the user can easily close the overlay
closeButtonRef.current?.focus()
})
useClickOutside(ref, triggerRef, isOpen, close)
if (!mounted) {
return null
}
// TODO: this is a case of me changing styles for new that will break
// old, need to fork
return (
<div
tabIndex={-1}
role="dialog"
ref={ref}
// remove this if it breaks shit, its influencing real
// data-info-popover
{...props}
data-rendered={rendered}
style={{
// height: '100%'
WebkitFontSmoothing: 'antialiased',
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
// background: 'var(--color-background-100)',
// border: '1px solid var(--color-gray-alpha-400)',
// backgroundClip: 'padding-box',
boxShadow: 'var(--shadow-menu)',
borderRadius: 'var(--rounded-xl)',
position: 'absolute',
fontFamily: 'var(--font-stack-sans)',
zIndex: 3,
overflow: 'hidden',
opacity: rendered ? 1 : 0,
outline: 0,
minWidth: '350px',
transition: 'opacity var(--animate-out-duration-ms) var(--animate-out-timing-function)',
scale: rendered ? 1 : undefined,
}}
>
<div className="dev-tools-info-container">
<div className="dev-tools-info-header">
<button
ref={closeButtonRef}
className="dev-tools-info-close-button"
onClick={close}
aria-label="Close dialog"
>
<IconChevronLeft />
</button>
<h3 className="dev-tools-info-title">{title}</h3>
</div>
<div className="dev-tools-info-body">
{children}
{learnMoreLink && (
<div className="dev-tools-info-button-container">
<a
className="dev-tools-info-learn-more-button"
href={learnMoreLink}
target="_blank"
rel="noreferrer noopener"
>
Learn More
</a>
</div>
)}
</div>
</div>
</div>
)
}
export const DEV_TOOLS_INFO_STYLES = css`
[data-info-popover] {
-webkit-font-smoothing: antialiased;
display: flex;
flex-direction: column;
align-items: flex-start;
background: var(--color-background-100);
border: 1px solid var(--color-gray-alpha-400);
background-clip: padding-box;
box-shadow: var(--shadow-menu);
border-radius: var(--rounded-xl);
position: absolute;
font-family: var(--font-stack-sans);
z-index: 3;
overflow: hidden;
opacity: 0;
outline: 0;
min-width: 350px;
transition: opacity var(--animate-out-duration-ms)
var(--animate-out-timing-function);
&[data-rendered='true'] {
opacity: 1;
scale: 1;
}
button:focus-visible {
outline: var(--focus-ring);
}
}
.dev-tools-info-container {
width: 100%;
}
.dev-tools-info-body {
padding: 16px;
}
.dev-tools-info-header {
height: 48px;
display: flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-bottom: 1px solid var(--color-gray-alpha-400);
}
.dev-tools-info-close-button {
all: unset;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
color: var(--color-gray-900);
transition: color 150ms ease;
translate: 0 1px;
border-radius: 3px;
&:hover {
color: var(--color-gray-1000);
}
}
.dev-tools-info-title {
color: var(--color-gray-1000);
font-size: var(--size-14);
font-weight: 500;
line-height: var(--size-20);
margin: 0;
}
.dev-tools-info-section-title {
padding: 8px 0px;
color: var(--color-gray-1000);
font-size: var(--size-16);
font-weight: 600;
line-height: var(--size-20);
margin: 0;
}
.dev-tools-info-article {
padding: 8px 6px;
color: var(--color-gray-1000);
font-size: var(--size-14);
line-height: var(--size-20);
margin: 0;
}
.dev-tools-info-paragraph {
&:last-child {
margin-bottom: 0;
}
}
.dev-tools-info-button-container {
display: flex;
justify-content: space-between;
align-items: center;
}
.dev-tools-info-learn-more-button {
align-content: center;
padding: 0 8px;
height: var(--size-28);
font-size: var(--size-14);
font-weight: 500;
line-height: var(--size-20);
transition: background var(--duration-short) ease;
color: var(--color-background-100);
border-radius: var(--rounded-md-2);
background: var(--color-gray-1000);
margin-left: auto;
}
.dev-tools-info-learn-more-button:hover {
text-decoration: none;
color: var(--color-background-100);
opacity: 0.9;
}
`
function IconChevronLeft() {
return (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M5.14645 8.70703C4.75595 8.31651 4.75595 7.68349 5.14645 7.29297L10.5 1.93945L11.5605 3L6.56051 8L11.5605 13L10.5 14.0605L5.14645 8.70703Z"
fill="currentColor"
/>
</svg>
)
}
import type { HTMLProps } from 'react' import type { HTMLProps } from 'react'
import type { DevToolsInfoPropsCore } from './dev-tools-info' import type { DevToolsInfoPropsCore } from './dev-tools-info'
import { DevToolsInfo } from './dev-tools-info' import { DevToolsInfo } from './dev-tools-info'
import { useDevOverlayContext } from '../../../../../dev-overlay.browser'
function StaticRouteContent({ routerType }: { routerType: 'pages' | 'app' }) { function StaticRouteContent({ routerType }: { routerType: 'pages' | 'app' }) {
return ( return (
...@@ -110,32 +111,38 @@ const learnMoreLink = { ...@@ -110,32 +111,38 @@ const learnMoreLink = {
}, },
} as const } as const
export function RouteInfo({ export function RouteInfoBody() {
routeType, const { state } = useDevOverlayContext()
routerType,
...props
}: {
routeType: 'Static' | 'Dynamic'
routerType: 'pages' | 'app'
} & DevToolsInfoPropsCore &
HTMLProps<HTMLDivElement>) {
const isStaticRoute = routeType === 'Static'
const learnMore = isStaticRoute const isStaticRoute = state.staticIndicator
? learnMoreLink[routerType].static
: learnMoreLink[routerType].dynamic
return isStaticRoute ? (
<StaticRouteContent routerType={state.routerType} />
) : (
<DynamicRouteContent routerType={state.routerType} />
)
}
export function RouteInfo({ isOpen,close,...props}: { isOpen: boolean , close: () => void} & HTMLProps<HTMLDivElement>) {
const { state } = useDevOverlayContext()
const routeType = state.staticIndicator ? 'Static' : 'Dynamic'
const learnMore = state.staticIndicator
? learnMoreLink[state.routerType].static
: learnMoreLink[state.routerType].dynamic
// FOR OLD UI NEED TO PASS DOWN THE EVENT HANDLERS
return ( return (
<DevToolsInfo <DevToolsInfo
title={`${routeType} Route`} title={`${routeType} Route`}
learnMoreLink={learnMore} learnMoreLink={learnMore}
close={close}
isOpen={isOpen}
triggerRef={{ current: null }}
{...props} {...props}
// style={style}
> >
{isStaticRoute ? ( <RouteInfoBody />
<StaticRouteContent routerType={routerType} />
) : (
<DynamicRouteContent routerType={routerType} />
)}
</DevToolsInfo> </DevToolsInfo>
) )
} }
......
...@@ -2,19 +2,16 @@ import { PageSegmentTree } from '../../../overview/segment-explorer' ...@@ -2,19 +2,16 @@ import { PageSegmentTree } from '../../../overview/segment-explorer'
import { DevToolsInfo, type DevToolsInfoPropsCore } from './dev-tools-info' import { DevToolsInfo, type DevToolsInfoPropsCore } from './dev-tools-info'
export function SegmentsExplorer({ export function SegmentsExplorer({
routerType,
page,
...props ...props
}: DevToolsInfoPropsCore & }: DevToolsInfoPropsCore &
React.HTMLProps<HTMLDivElement> & { React.HTMLProps<HTMLDivElement> & {
routerType: 'app' | 'pages' routerType: 'app' | 'pages'
page: string page: string
}) { }) {
const isAppRouter = routerType === 'app'
return ( return (
<DevToolsInfo title="Route Info" {...props}> <DevToolsInfo title="Route Info" {...props}>
<div data-nextjs-segments-explorer> <div data-nextjs-segments-explorer>
<PageSegmentTree isAppRouter={isAppRouter} page={page} /> <PageSegmentTree />
</div> </div>
</DevToolsInfo> </DevToolsInfo>
) )
......
...@@ -2,15 +2,9 @@ import { DevToolsInfo, type DevToolsInfoPropsCore } from './dev-tools-info' ...@@ -2,15 +2,9 @@ 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: DevToolsInfoPropsCore & HTMLProps<HTMLDivElement>
) {
return ( return (
<DevToolsInfo <>
title="Turbopack"
learnMoreLink="https://nextjs.org/docs/app/api-reference/turbopack"
{...props}
>
<article className="dev-tools-info-article"> <article className="dev-tools-info-article">
<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
...@@ -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>
) )
} }
......
// Drag context to coordinate Draggable and its DragHandle children
import React, {
createContext,
useCallback,
useContext,
useMemo,
useRef,
} 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?: React.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 React.MutableRefObject<HTMLDivElement | null>
).current = node
}
},
[ref]
)
React.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,
...@@ -94,49 +103,54 @@ export function Draggable({ ...@@ -94,49 +103,54 @@ 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 // Helper to compute relative translation from 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', ...props.style }}
>
{children} {children}
</div> </div>
) )
...@@ -150,6 +164,7 @@ interface UseDragOptions { ...@@ -150,6 +164,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 {
...@@ -234,18 +249,32 @@ export function useDrag(options: UseDragOptions) { ...@@ -234,18 +249,32 @@ 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
if (options.handles && options.handles.size > 0) {
let node: HTMLElement | null = target as HTMLElement
while (node && node !== ref.current) {
if (options.handles.has(node)) return true
node = node.parentElement
}
return false
} }
const element = target as Element if (options.dragHandleSelector) {
if (!element.matches) { const selector = options.dragHandleSelector
const element = target as Element
if (element.matches && element.matches(selector)) return true
let parent = element.parentElement
while (parent && parent !== ref.current) {
if (parent.matches && parent.matches(selector)) {
return true
}
parent = parent.parentElement
}
return false return false
} }
// Check if the target element directly matches the drag handle selector return true
// This excludes children elements, only allowing drag from the exact element
return element.matches(options.dragHandleSelector)
} }
function onPointerDown(e: React.PointerEvent) { function onPointerDown(e: React.PointerEvent) {
...@@ -253,7 +282,7 @@ export function useDrag(options: UseDragOptions) { ...@@ -253,7 +282,7 @@ export function useDrag(options: UseDragOptions) {
return // ignore right click return // ignore right click
} }
// Check if the pointer down event is on a valid drag handle // Restrict drag initiation to valid handles if any registered
if (!isValidDragHandle(e.target)) { if (!isValidDragHandle(e.target)) {
return return
} }
...@@ -328,6 +357,13 @@ export function useDrag(options: UseDragOptions) { ...@@ -328,6 +357,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,
......
...@@ -100,19 +100,21 @@ export function useClickOutside( ...@@ -100,19 +100,21 @@ export function useClickOutside(
return return
} }
const cushion = 10
if ( if (
!(rootRef.current?.getBoundingClientRect() !(rootRef.current?.getBoundingClientRect()
? event.clientX >= rootRef.current.getBoundingClientRect()!.left && ? event.clientX >= rootRef.current.getBoundingClientRect()!.left - cushion &&
event.clientX <= rootRef.current.getBoundingClientRect()!.right && event.clientX <= rootRef.current.getBoundingClientRect()!.right + cushion &&
event.clientY >= rootRef.current.getBoundingClientRect()!.top && event.clientY >= rootRef.current.getBoundingClientRect()!.top - cushion &&
event.clientY <= rootRef.current.getBoundingClientRect()!.bottom 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 >= triggerRef.current.getBoundingClientRect()!.top - cushion &&
event.clientY <= triggerRef.current.getBoundingClientRect()!.bottom event.clientY <= triggerRef.current.getBoundingClientRect()!.bottom + cushion
: false) : false)
) { ) {
close() close()
......
...@@ -10,49 +10,29 @@ import { Errors } from '../../../container/errors' ...@@ -10,49 +10,29 @@ import { Errors } from '../../../container/errors'
import { useDelayedRender } from '../../../hooks/use-delayed-render' import { useDelayedRender } from '../../../hooks/use-delayed-render'
import type { ReadyRuntimeError } from '../../../utils/get-error-by-type' import type { ReadyRuntimeError } from '../../../utils/get-error-by-type'
import type { HydrationErrorState } from '../../../../shared/hydration-error' import type { HydrationErrorState } from '../../../../shared/hydration-error'
import { useDevOverlayContext } from '../../../../dev-overlay.browser'
import { useRenderErrorContext } from '../../../dev-overlay'
const transitionDurationMs = 200 const transitionDurationMs = 200
export interface ErrorBaseProps { export interface ErrorBaseProps {
rendered: boolean rendered: boolean
transitionDurationMs: number transitionDurationMs: number
isTurbopack: boolean
versionInfo: OverlayState['versionInfo']
errorCount: number
} }
export function ErrorOverlay({ export function ErrorOverlay() {
state, const { state } = useDevOverlayContext()
dispatch, const { runtimeErrors } = useRenderErrorContext()
getSquashedHydrationErrorDetails,
runtimeErrors,
errorCount,
}: {
state: OverlayState
dispatch: OverlayDispatch
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
runtimeErrors: ReadyRuntimeError[]
errorCount: number
}) {
const isTurbopack = !!process.env.TURBOPACK
// This hook lets us do an exit animation before unmounting the component // This hook lets us do an exit animation before unmounting the component
const { mounted, rendered } = useDelayedRender(state.isErrorOverlayOpen, { const { mounted, rendered } = useDelayedRender(state.isErrorOverlayOpen, {
exitDelay: transitionDurationMs, exitDelay: transitionDurationMs,
}) })
const commonProps = {
rendered,
transitionDurationMs,
isTurbopack,
versionInfo: state.versionInfo,
errorCount,
}
if (state.buildError !== null) { if (state.buildError !== null) {
return ( return (
<BuildError <BuildError
{...commonProps} transitionDurationMs={transitionDurationMs}
message={state.buildError} message={state.buildError}
// This is not a runtime error, forcedly display error overlay // This is not a runtime error, forcedly display error overlay
rendered rendered
...@@ -74,14 +54,6 @@ export function ErrorOverlay({ ...@@ -74,14 +54,6 @@ export function ErrorOverlay({
} }
return ( return (
<Errors <Errors transitionDurationMs={transitionDurationMs} rendered={rendered} />
{...commonProps}
debugInfo={state.debugInfo}
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
runtimeErrors={runtimeErrors}
onClose={() => {
dispatch({ type: ACTION_ERROR_OVERLAY_CLOSE })
}}
/>
) )
} }
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;
......
...@@ -16,6 +16,8 @@ import { ...@@ -16,6 +16,8 @@ import {
isBoundaryFile, isBoundaryFile,
normalizeBoundaryFilename, normalizeBoundaryFilename,
} from '../../../../server/app-render/segment-explorer-path' } from '../../../../server/app-render/segment-explorer-path'
import { ExternalIcon } from '../../icons/external'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
const isFileNode = (node: SegmentTrieNode) => { const isFileNode = (node: SegmentTrieNode) => {
return !!node.value?.type && !!node.value?.pagePath return !!node.value?.type && !!node.value?.pagePath
...@@ -99,15 +101,13 @@ function SegmentExplorerFooter({ ...@@ -99,15 +101,13 @@ function SegmentExplorerFooter({
) )
} }
export function PageSegmentTree({ export function PageSegmentTree() {
isAppRouter,
page,
}: {
isAppRouter: boolean
page: string
}) {
const tree = useSegmentTree() const tree = useSegmentTree()
const {state} = useDevOverlayContext()
const isAppRouter = state.routerType === 'app'
// Count active boundaries for the badge // Count active boundaries for the badge
const activeBoundariesCount = useMemo(() => { const activeBoundariesCount = useMemo(() => {
return isAppRouter ? countActiveBoundaries(tree) : 0 return isAppRouter ? countActiveBoundaries(tree) : 0
...@@ -122,7 +122,7 @@ export function PageSegmentTree({ ...@@ -122,7 +122,7 @@ export function PageSegmentTree({
return ( return (
<div data-nextjs-devtools-panel-segments-explorer> <div data-nextjs-devtools-panel-segments-explorer>
{isAppRouter && <PageRouteBar page={page} />} {isAppRouter && <PageRouteBar page={state.page} />}
<div <div
className="segment-explorer-content" className="segment-explorer-content"
data-nextjs-devtool-segment-explorer data-nextjs-devtool-segment-explorer
...@@ -316,7 +316,7 @@ function PageSegmentTreeLayerPresentation({ ...@@ -316,7 +316,7 @@ function PageSegmentTreeLayerPresentation({
const tooltipMessage = isBuiltin const tooltipMessage = isBuiltin
? `The default Next.js ${childNode.value.type} is being shown. You can customize this page by adding your own ${fileName} file to the app/ directory.` ? `The default Next.js ${childNode.value.type} is being shown. You can customize this page by adding your own ${fileName} file to the app/ directory.`
: `Open in editor` : null // `Open in editor`
return ( return (
<Tooltip <Tooltip
...@@ -346,7 +346,7 @@ function PageSegmentTreeLayerPresentation({ ...@@ -346,7 +346,7 @@ function PageSegmentTreeLayerPresentation({
}} }}
> >
{fileName} {fileName}
{isBuiltin && <InfoIcon />} {isBuiltin ? <InfoIcon /> : <ExternalIcon />}
</span> </span>
</Tooltip> </Tooltip>
) )
......
...@@ -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,
......
...@@ -18,6 +18,9 @@ import type { ReadyRuntimeError } from '../utils/get-error-by-type' ...@@ -18,6 +18,9 @@ import type { ReadyRuntimeError } from '../utils/get-error-by-type'
import type { ErrorBaseProps } from '../components/errors/error-overlay/error-overlay' import type { ErrorBaseProps } from '../components/errors/error-overlay/error-overlay'
import type { HydrationErrorState } from '../../shared/hydration-error' import type { HydrationErrorState } from '../../shared/hydration-error'
import { useActiveRuntimeError } from '../hooks/use-active-runtime-error' import { useActiveRuntimeError } from '../hooks/use-active-runtime-error'
import { useDevOverlayContext } from '../../dev-overlay.browser'
import { useRenderErrorContext } from '../dev-overlay'
import { ACTION_ERROR_OVERLAY_CLOSE } from '../shared'
export interface ErrorsProps extends ErrorBaseProps { export interface ErrorsProps extends ErrorBaseProps {
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
...@@ -111,15 +114,15 @@ export function useErrorDetails( ...@@ -111,15 +114,15 @@ export function useErrorDetails(
}, [error, getSquashedHydrationErrorDetails]) }, [error, getSquashedHydrationErrorDetails])
} }
export function Errors({ export function Errors({transitionDurationMs,rendered}:{transitionDurationMs: number, rendered:boolean}) {
getSquashedHydrationErrorDetails,
runtimeErrors,
debugInfo,
onClose,
...props
}: ErrorsProps) {
const dialogResizerRef = useRef<HTMLDivElement | null>(null) const dialogResizerRef = useRef<HTMLDivElement | null>(null)
const {getSquashedHydrationErrorDetails, dispatch,state} = useDevOverlayContext()
const {runtimeErrors} = useRenderErrorContext()
const onClose = () => {
dispatch({ type: ACTION_ERROR_OVERLAY_CLOSE })
}
const { const {
isLoading, isLoading,
errorCode, errorCode,
...@@ -162,13 +165,15 @@ export function Errors({ ...@@ -162,13 +165,15 @@ export function Errors({
) )
} }
onClose={isServerError ? undefined : onClose} onClose={isServerError ? undefined : onClose}
debugInfo={debugInfo} debugInfo={state.debugInfo}
error={error} error={error}
runtimeErrors={runtimeErrors} runtimeErrors={runtimeErrors}
activeIdx={activeIdx} activeIdx={activeIdx}
setActiveIndex={setActiveIndex} setActiveIndex={setActiveIndex}
dialogResizerRef={dialogResizerRef} dialogResizerRef={dialogResizerRef}
{...props} // {...props}
transitionDurationMs={transitionDurationMs}
rendered={rendered}
> >
<div className="error-overlay-notes-container"> <div className="error-overlay-notes-container">
{notes ? ( {notes ? (
......
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
storybookDefaultOverlayState, storybookDefaultOverlayState,
useStorybookOverlayReducer, useStorybookOverlayReducer,
} from './storybook/use-overlay-reducer' } from './storybook/use-overlay-reducer'
import { DevOverlayContext } from '../dev-overlay.browser'
const meta: Meta<typeof DevOverlay> = { const meta: Meta<typeof DevOverlay> = {
component: DevOverlay, component: DevOverlay,
...@@ -39,35 +40,45 @@ function getNoSquashedHydrationErrorDetails() { ...@@ -39,35 +40,45 @@ function getNoSquashedHydrationErrorDetails() {
const initialState: OverlayState = { const initialState: OverlayState = {
...storybookDefaultOverlayState, ...storybookDefaultOverlayState,
errors, // todo: i think hidden when errors for some reason
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
<img style={{
height: '100vh',
backgroundColor: "black"
}}
>
{/* get lots of real hard examples so we have better debug */}
{/* <img
src={imgApp} src={imgApp}
style={{ style={{
width: '100%', width: '100%',
height: '100vh', height: '100vh',
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 />
</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'
...@@ -90,12 +101,12 @@ export const WithPanel: Story = { ...@@ -90,12 +101,12 @@ export const WithPanel: Story = {
}} }}
/> />
<DevOverlay <DevOverlay
state={state} // state={state}
dispatch={dispatch} // dispatch={dispatch}
getSquashedHydrationErrorDetails={ // getSquashedHydrationErrorDetails={
// Testing like App Router where we no longer quash hydration errors // // Testing like App Router where we no longer quash hydration errors
getNoSquashedHydrationErrorDetails // getNoSquashedHydrationErrorDetails
} // }
/> />
</> </>
) )
......
import { import {
ACTION_DEVTOOLS_PANEL_OPEN, ACTION_DEVTOOLS_PANEL_OPEN,
ACTION_ERROR_OVERLAY_OPEN, ACTION_ERROR_OVERLAY_OPEN,
type DispatcherEvent,
type OverlayDispatch, type OverlayDispatch,
type OverlayState, type OverlayState,
} from './shared' } from './shared'
import { useState } from 'react' import {
createContext,
useContext,
useRef,
useState,
type ActionDispatch,
} from 'react'
import { ShadowPortal } from './components/shadow-portal' import { ShadowPortal } from './components/shadow-portal'
import { Base } from './styles/base' import { Base } from './styles/base'
...@@ -13,23 +20,30 @@ import { ComponentStyles } from './styles/component-styles' ...@@ -13,23 +20,30 @@ import { ComponentStyles } from './styles/component-styles'
import { CssReset } from './styles/css-reset' import { CssReset } from './styles/css-reset'
import { Colors } from './styles/colors' import { Colors } from './styles/colors'
import { ErrorOverlay } from './components/errors/error-overlay/error-overlay' import { ErrorOverlay } from './components/errors/error-overlay/error-overlay'
import { DevToolsIndicator } from './components/errors/dev-tools-indicator/dev-tools-indicator' import {
DevToolsIndicator,
type Overlays,
} from './components/errors/dev-tools-indicator/dev-tools-indicator'
import { RenderError } from './container/runtime-error/render-error' 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 { DevToolsIndicatorNew as DevToolsIndicatorNew } from './components/devtools-indicator/devtools-indicator'
import { DevToolsPanel } from './components/devtools-panel/devtools-panel' import { DevToolsPanel } from './components/devtools-panel/devtools-panel'
import type { ReadyRuntimeError } from './utils/get-error-by-type'
import { useDevOverlayContext } from '../dev-overlay.browser'
import { PanelRouter } from './menu/panel-router'
import { PanelContext, type PanelStateKind } from './menu/context'
export const RenderErrorContext = createContext<{
runtimeErrors: ReadyRuntimeError[]
totalErrorCount: number
}>(null!)
export function DevOverlay({ export const useRenderErrorContext = () => useContext(RenderErrorContext)
state,
dispatch, export function DevOverlay() {
getSquashedHydrationErrorDetails, const { dispatch, state } = useDevOverlayContext()
}: {
state: OverlayState
dispatch: OverlayDispatch
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
}) {
const [scale, setScale] = useDevToolsScale() const [scale, setScale] = useDevToolsScale()
const [isPrevBuildError, setIsPrevBuildError] = useState(false) const [isPrevBuildError, setIsPrevBuildError] = useState(false)
...@@ -47,7 +61,13 @@ export function DevOverlay({ ...@@ -47,7 +61,13 @@ export function DevOverlay({
} }
setIsPrevBuildError(isBuildError) setIsPrevBuildError(isBuildError)
} }
// stupid state same thing
const [panel, setPanel] = useState<PanelStateKind | null>(null)
const [open, setOpen] = useState<Overlays | null>(null)
const triggerRef = useRef<HTMLButtonElement>(null)
// // @ts-expect-error
// process.env.__NEXT_DEVTOOL_NEW_PANEL_UI = true
return ( return (
<ShadowPortal> <ShadowPortal>
<CssReset /> <CssReset />
...@@ -58,56 +78,34 @@ export function DevOverlay({ ...@@ -58,56 +78,34 @@ export function DevOverlay({
<ComponentStyles /> <ComponentStyles />
<DarkTheme /> <DarkTheme />
{/* todo: render error should provide this context, probably shouldn't have render props at all tbh */}
<RenderError state={state} dispatch={dispatch} isAppDir={true}> <RenderError state={state} dispatch={dispatch} isAppDir={true}>
{({ runtimeErrors, totalErrorCount }) => { {({ runtimeErrors, totalErrorCount }) => {
return ( return (
<> <PanelContext
{state.showIndicator && value={{
(process.env.__NEXT_DEVTOOL_NEW_PANEL_UI ? ( triggerRef,
<> panel,
<DevToolsIndicatorNew setPanel,
state={state} open,
dispatch={dispatch} setOpen,
errorCount={totalErrorCount} }}
isBuildError={isBuildError} >
/> <RenderErrorContext value={{ runtimeErrors, totalErrorCount }}>
{state.showIndicator &&
{(state.isDevToolsPanelOpen || (process.env.__NEXT_DEVTOOL_NEW_PANEL_UI ? (
state.isErrorOverlayOpen) && ( <>
<DevToolsPanel <PanelRouter />
state={state} <DevToolsIndicatorNew />
dispatch={dispatch} </>
issueCount={totalErrorCount} ) : (
runtimeErrors={runtimeErrors} <>
getSquashedHydrationErrorDetails={ <DevToolsIndicator scale={scale} setScale={setScale} />
getSquashedHydrationErrorDetails <ErrorOverlay />
} </>
/> ))}
)} </RenderErrorContext>
</> </PanelContext>
) : (
<>
<DevToolsIndicator
scale={scale}
setScale={setScale}
state={state}
dispatch={dispatch}
errorCount={totalErrorCount}
isBuildError={isBuildError}
/>
<ErrorOverlay
state={state}
dispatch={dispatch}
getSquashedHydrationErrorDetails={
getSquashedHydrationErrorDetails
}
runtimeErrors={runtimeErrors}
errorCount={totalErrorCount}
/>
</>
))}
</>
) )
}} }}
</RenderError> </RenderError>
......
import { createContext, useContext, type Dispatch, type SetStateAction } from "react";
import type { Overlays } from "../components/errors/dev-tools-indicator/dev-tools-indicator";
export const MenuContext = createContext<{
closeMenu: () => void
selectedIndex: number
setSelectedIndex: Dispatch<SetStateAction<number>>
}>(null!)
export const useMenuContext = () => useContext(MenuContext)
export type PanelStateKind =
| 'preferences'
| 'route-info'
| 'segment-explorer'
| 'panel-selector'
| 'turbo-info'
export const PanelContext = createContext<{
panel: PanelStateKind | null
setPanel: Dispatch<SetStateAction<PanelStateKind | null>>
open: Overlays | null
triggerRef: React.RefObject<HTMLButtonElement | null>,
setOpen: Dispatch<SetStateAction<Overlays | null>>
}>(null!)
export const usePanelContext = () => useContext(PanelContext)
\ No newline at end of file
import { useMenuContext } from './context'
export function MenuItem({
index,
label,
value,
onClick,
href,
...props
}: {
index?: number
title?: string
label: string
value: React.ReactNode
href?: string
onClick?: () => void
}) {
const isInteractive =
typeof onClick === 'function' || typeof href === 'string'
const { closeMenu, selectedIndex, setSelectedIndex } = useMenuContext()
const selected = selectedIndex === index
function click() {
if (isInteractive) {
onClick?.()
closeMenu()
if (href) {
window.open(href, '_blank', 'noopener, noreferrer')
}
}
}
return (
<div
className="dev-tools-indicator-item"
data-index={index}
data-selected={selected}
onClick={click}
// Needs `onMouseMove` instead of enter to work together
// with keyboard and mouse input
onMouseMove={() => {
if (isInteractive && index !== undefined && selectedIndex !== index) {
setSelectedIndex(index)
}
}}
onMouseLeave={() => setSelectedIndex(-1)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
click()
}
}}
role={isInteractive ? 'menuitem' : undefined}
tabIndex={selected ? 0 : -1}
{...props}
>
<span className="dev-tools-indicator-label">{label}</span>
<span className="dev-tools-indicator-value">{value}</span>
</div>
)
}
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