Unverified Commit 536b6b79 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

[devtools] save user config inside `.next/cache` (#81807)

### Why?

It's common for developers to clear `localStorage` during development.
Since the current DevTools config is saved there, this can hurt the
developer experience when `localStorage` is cleared for any reason.

To avoid this, we decided to store the DevTools config in the app’s
cache directory, which is `{distDir}/cache/`. The content inside this
directory is expected to remain during Next.js’ workflow (i.e., `next
build`) unless it's manually removed.

### How?

Added the `/__nextjs_devtools_config` endpoint to handle config writing.
The client sends a POST request to this endpoint, passing the config
data. After the config is successfully written, HMR is triggered to
update the client state accordingly.

---------
Co-authored-by: 's avatarJiachi Liu <inbox@huozhi.im>
parent 907501e8
...@@ -293,6 +293,8 @@ function processMessage( ...@@ -293,6 +293,8 @@ function processMessage(
if ('versionInfo' in obj) dispatcher.onVersionInfo(obj.versionInfo) if ('versionInfo' in obj) dispatcher.onVersionInfo(obj.versionInfo)
if ('debug' in obj && obj.debug) dispatcher.onDebugInfo(obj.debug) if ('debug' in obj && obj.debug) dispatcher.onDebugInfo(obj.debug)
if ('devIndicator' in obj) dispatcher.onDevIndicator(obj.devIndicator) if ('devIndicator' in obj) dispatcher.onDevIndicator(obj.devIndicator)
if ('devToolsConfig' in obj)
dispatcher.onDevToolsConfig(obj.devToolsConfig)
const hasErrors = Boolean(errors && errors.length) const hasErrors = Boolean(errors && errors.length)
// Compilation with errors (e.g. syntax error or missing modules). // Compilation with errors (e.g. syntax error or missing modules).
...@@ -440,6 +442,10 @@ function processMessage( ...@@ -440,6 +442,10 @@ function processMessage(
case HMR_ACTIONS_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE: { case HMR_ACTIONS_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE: {
return return
} }
case HMR_ACTIONS_SENT_TO_BROWSER.DEVTOOLS_CONFIG: {
dispatcher.onDevToolsConfig(obj.data)
return
}
default: { default: {
obj satisfies never obj satisfies never
} }
......
...@@ -285,6 +285,8 @@ function processMessage(obj: HMR_ACTION_TYPES) { ...@@ -285,6 +285,8 @@ function processMessage(obj: HMR_ACTION_TYPES) {
// Is undefined when it's a 'built' event // Is undefined when it's a 'built' event
if ('versionInfo' in obj) dispatcher.onVersionInfo(obj.versionInfo) if ('versionInfo' in obj) dispatcher.onVersionInfo(obj.versionInfo)
if ('devIndicator' in obj) dispatcher.onDevIndicator(obj.devIndicator) if ('devIndicator' in obj) dispatcher.onDevIndicator(obj.devIndicator)
if ('devToolsConfig' in obj)
dispatcher.onDevToolsConfig(obj.devToolsConfig)
const hasErrors = Boolean(errors && errors.length) const hasErrors = Boolean(errors && errors.length)
if (hasErrors) { if (hasErrors) {
...@@ -369,6 +371,9 @@ function processMessage(obj: HMR_ACTION_TYPES) { ...@@ -369,6 +371,9 @@ function processMessage(obj: HMR_ACTION_TYPES) {
customHmrEventHandler(obj) customHmrEventHandler(obj)
} }
break break
case HMR_ACTIONS_SENT_TO_BROWSER.DEVTOOLS_CONFIG:
dispatcher.onDevToolsConfig(obj.data)
break
default: default:
obj satisfies never obj satisfies never
} }
......
...@@ -61,6 +61,7 @@ export function pageBootstrap(assetPrefix: string) { ...@@ -61,6 +61,7 @@ export function pageBootstrap(assetPrefix: string) {
case HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE: case HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE:
case HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED: case HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_CONNECTED:
case HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST: case HMR_ACTIONS_SENT_TO_BROWSER.ISR_MANIFEST:
case HMR_ACTIONS_SENT_TO_BROWSER.DEVTOOLS_CONFIG:
// Most of these action types are handled in // Most of these action types are handled in
// src/client/dev/hot-reloader/pages/hot-reloader-pages.ts // src/client/dev/hot-reloader/pages/hot-reloader-pages.ts
break break
......
...@@ -18,6 +18,7 @@ import { ...@@ -18,6 +18,7 @@ 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,
ACTION_DEVTOOLS_CONFIG,
type OverlayState, type OverlayState,
type DispatcherEvent, type DispatcherEvent,
} from './dev-overlay/shared' } from './dev-overlay/shared'
...@@ -41,6 +42,7 @@ import { ...@@ -41,6 +42,7 @@ import {
removeSegmentNode, removeSegmentNode,
} from './dev-overlay/segment-explorer-trie' } from './dev-overlay/segment-explorer-trie'
import type { SegmentNodeState } from './userspace/app/segment-explorer-node' import type { SegmentNodeState } from './userspace/app/segment-explorer-node'
import type { DevToolsConfig } from './dev-overlay/shared'
export interface Dispatcher { export interface Dispatcher {
onBuildOk(): void onBuildOk(): void
...@@ -51,6 +53,7 @@ export interface Dispatcher { ...@@ -51,6 +53,7 @@ export interface Dispatcher {
onRefresh(): void onRefresh(): void
onStaticIndicator(status: boolean): void onStaticIndicator(status: boolean): void
onDevIndicator(devIndicator: DevIndicatorServerState): void onDevIndicator(devIndicator: DevIndicatorServerState): void
onDevToolsConfig(config: DevToolsConfig): void
onUnhandledError(reason: Error): void onUnhandledError(reason: Error): void
onUnhandledRejection(reason: Error): void onUnhandledRejection(reason: Error): void
openErrorOverlay(): void openErrorOverlay(): void
...@@ -115,6 +118,11 @@ export const dispatcher: Dispatcher = { ...@@ -115,6 +118,11 @@ export const dispatcher: Dispatcher = {
dispatch({ type: ACTION_DEV_INDICATOR, devIndicator }) dispatch({ type: ACTION_DEV_INDICATOR, devIndicator })
} }
), ),
onDevToolsConfig: createQueuable(
(dispatch: Dispatch, devToolsConfig: DevToolsConfig) => {
dispatch({ type: ACTION_DEVTOOLS_CONFIG, devToolsConfig })
}
),
onUnhandledError: createQueuable((dispatch: Dispatch, error: Error) => { onUnhandledError: createQueuable((dispatch: Dispatch, error: Error) => {
dispatch({ dispatch({
type: ACTION_UNHANDLED_ERROR, type: ACTION_UNHANDLED_ERROR,
......
import './devtools-indicator.css' import './devtools-indicator.css'
import type { CSSProperties } from 'react' import type { CSSProperties } from 'react'
import type { DevToolsIndicatorPosition } from '../../shared'
import { NextLogo } from './next-logo' import { NextLogo } from './next-logo'
import { Toast } from '../toast' import { Toast } from '../toast'
import { import {
...@@ -7,7 +8,6 @@ import { ...@@ -7,7 +8,6 @@ import {
MENU_DURATION_MS, MENU_DURATION_MS,
} from '../errors/dev-tools-indicator/utils' } from '../errors/dev-tools-indicator/utils'
import { import {
STORAGE_KEY_POSITION,
ACTION_DEVTOOLS_POSITION, ACTION_DEVTOOLS_POSITION,
STORE_KEY_SHARED_PANEL_LOCATION, STORE_KEY_SHARED_PANEL_LOCATION,
STORAGE_KEY_PANEL_POSITION_PREFIX, STORAGE_KEY_PANEL_POSITION_PREFIX,
...@@ -16,7 +16,7 @@ import { ...@@ -16,7 +16,7 @@ import {
import { Draggable } from '../errors/dev-tools-indicator/draggable' import { Draggable } from '../errors/dev-tools-indicator/draggable'
import { useDevOverlayContext } from '../../../dev-overlay.browser' import { useDevOverlayContext } from '../../../dev-overlay.browser'
import { usePanelRouterContext } from '../../menu/context' import { usePanelRouterContext } from '../../menu/context'
import type { DevToolsIndicatorPosition } from '../errors/dev-tools-indicator/dev-tools-info/preferences' import { saveDevToolsConfig } from '../../utils/save-devtools-config'
export const INDICATOR_PADDING = 20 export const INDICATOR_PADDING = 20
...@@ -51,7 +51,7 @@ export function DevToolsIndicator() { ...@@ -51,7 +51,7 @@ export function DevToolsIndicator() {
type: ACTION_DEVTOOLS_POSITION, type: ACTION_DEVTOOLS_POSITION,
devToolsPosition: p, devToolsPosition: p,
}) })
localStorage.setItem(STORAGE_KEY_POSITION, p) saveDevToolsConfig({ devToolsPosition: p })
updateAllPanelPositions(p) updateAllPanelPositions(p)
}} }}
...@@ -79,7 +79,7 @@ export function DevToolsIndicator() { ...@@ -79,7 +79,7 @@ export function DevToolsIndicator() {
* cannot be dragged when any panel is open * cannot be dragged when any panel is open
*/ */
export const useUpdateAllPanelPositions = () => { export const useUpdateAllPanelPositions = () => {
const { dispatch } = useDevOverlayContext() const { state, dispatch } = useDevOverlayContext()
return (position: DevToolsIndicatorPosition) => { return (position: DevToolsIndicatorPosition) => {
dispatch({ dispatch({
type: ACTION_DEVTOOLS_PANEL_POSITION, type: ACTION_DEVTOOLS_PANEL_POSITION,
...@@ -87,19 +87,26 @@ export const useUpdateAllPanelPositions = () => { ...@@ -87,19 +87,26 @@ export const useUpdateAllPanelPositions = () => {
key: STORE_KEY_SHARED_PANEL_LOCATION, key: STORE_KEY_SHARED_PANEL_LOCATION,
}) })
localStorage.setItem(STORE_KEY_SHARED_PANEL_LOCATION, position) const panelPositionKeys = Object.keys(state.devToolsPanelPosition).filter(
(key) => key.startsWith(STORAGE_KEY_PANEL_POSITION_PREFIX)
const panelPositionKeys = Object.keys(localStorage).filter((key) =>
key.startsWith(STORAGE_KEY_PANEL_POSITION_PREFIX)
) )
const panelPositionPatch: Record<string, DevToolsIndicatorPosition> = {
[STORE_KEY_SHARED_PANEL_LOCATION]: position,
}
panelPositionKeys.forEach((key) => { panelPositionKeys.forEach((key) => {
dispatch({ dispatch({
type: ACTION_DEVTOOLS_PANEL_POSITION, type: ACTION_DEVTOOLS_PANEL_POSITION,
devToolsPanelPosition: position, devToolsPanelPosition: position,
key, key,
}) })
localStorage.setItem(key, position)
panelPositionPatch[key] = position
})
saveDevToolsConfig({
devToolsPanelPosition: panelPositionPatch,
}) })
} }
} }
import { useState } from 'react'
import { STORAGE_KEY_THEME } from '../../../shared'
function getInitialTheme() {
if (typeof localStorage === 'undefined') {
return 'system'
}
const theme = localStorage.getItem(STORAGE_KEY_THEME)
return theme === 'dark' || theme === 'light' ? theme : 'system'
}
export function useTheme() {
return useState(getInitialTheme())
}
...@@ -2,6 +2,7 @@ import { useState, useLayoutEffect } from 'react' ...@@ -2,6 +2,7 @@ import { useState, useLayoutEffect } from 'react'
import type { Corners } from '../../../shared' 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'
import { saveDevToolsConfig } from '../../../utils/save-devtools-config'
export const ResizeHandle = ({ export const ResizeHandle = ({
direction, direction,
...@@ -127,8 +128,9 @@ export const ResizeHandle = ({ ...@@ -127,8 +128,9 @@ export const ResizeHandle = ({
} }
const { width, height } = resizeRef.current.getBoundingClientRect() const { width, height } = resizeRef.current.getBoundingClientRect()
saveDevToolsConfig({
localStorage.setItem(storageKey, JSON.stringify({ width, height })) devToolsPanelSize: { [storageKey]: { width, height } },
})
} }
document.addEventListener('mousemove', handleMouseMove) document.addEventListener('mousemove', handleMouseMove)
document.addEventListener('mouseup', handleMouseUp) document.addEventListener('mouseup', handleMouseUp)
......
...@@ -46,26 +46,6 @@ const constrainDimensions = (params: { ...@@ -46,26 +46,6 @@ const constrainDimensions = (params: {
} }
} }
const parseResizeLocalStorage = (key: string) => {
const savedDimensions = localStorage.getItem(key)
if (!savedDimensions) return null
try {
const parsed = JSON.parse(savedDimensions)
if (
typeof parsed === 'object' &&
parsed !== null &&
typeof parsed.width === 'number' &&
typeof parsed.height === 'number'
) {
return { width: parsed.width, height: parsed.height }
}
return null
} catch (e) {
localStorage.removeItem(key)
return null
}
}
interface ResizeProviderProps { interface ResizeProviderProps {
value: { value: {
resizeRef: RefObject<HTMLElement | null> resizeRef: RefObject<HTMLElement | null>
...@@ -74,6 +54,7 @@ interface ResizeProviderProps { ...@@ -74,6 +54,7 @@ interface ResizeProviderProps {
maxWidth?: number maxWidth?: number
maxHeight?: number maxHeight?: number
devToolsPosition: Corners devToolsPosition: Corners
devToolsPanelSize: Record<string, { width: number; height: number }>
storageKey?: string storageKey?: string
initialSize?: { height: number; width: number } initialSize?: { height: number; width: number }
} }
...@@ -105,7 +86,7 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => { ...@@ -105,7 +86,7 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => {
return return
} }
const dim = parseResizeLocalStorage(storageKey) const dim = value.devToolsPanelSize[storageKey]
if (!dim) { if (!dim) {
return return
} }
...@@ -118,7 +99,14 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => { ...@@ -118,7 +99,14 @@ export const ResizeProvider = ({ value, children }: ResizeProviderProps) => {
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`
return true return true
}, [value.resizeRef, draggingDirection, storageKey, minWidth, minHeight]) }, [
value.resizeRef,
draggingDirection,
storageKey,
minWidth,
minHeight,
value.devToolsPanelSize,
])
useLayoutEffect(() => { useLayoutEffect(() => {
const applied = applyConstrainedDimensions() const applied = applyConstrainedDimensions()
......
import { useState } from 'react'
import {
NEXT_DEV_TOOLS_SCALE,
STORAGE_KEY_POSITION,
STORAGE_KEY_SCALE,
STORAGE_KEY_THEME,
} from '../../../../shared'
const INDICATOR_POSITION =
(process.env
.__NEXT_DEV_INDICATOR_POSITION as typeof window.__NEXT_DEV_INDICATOR_POSITION) ||
'bottom-left'
export const STORAGE_KEY_HIDE_SHORTCUT = '__nextjs_hide_shortcut'
export type DevToolsIndicatorPosition = typeof INDICATOR_POSITION
export function getInitialPosition() {
if (
typeof localStorage !== 'undefined' &&
localStorage.getItem(STORAGE_KEY_POSITION)
) {
return localStorage.getItem(
STORAGE_KEY_POSITION
) as DevToolsIndicatorPosition
}
return INDICATOR_POSITION
}
//////////////////////////////////////////////////////////////////////////////////////
export type DevToolsScale =
(typeof NEXT_DEV_TOOLS_SCALE)[keyof typeof NEXT_DEV_TOOLS_SCALE]
function getInitialScale() {
if (
typeof localStorage !== 'undefined' &&
localStorage.getItem(STORAGE_KEY_SCALE)
) {
return Number(localStorage.getItem(STORAGE_KEY_SCALE)) as DevToolsScale
}
return NEXT_DEV_TOOLS_SCALE.Medium
}
export function useDevToolsScale(): [
DevToolsScale,
(value: DevToolsScale) => void,
] {
const [scale, setScale] = useState<DevToolsScale>(getInitialScale())
function set(value: DevToolsScale) {
setScale(value)
localStorage.setItem(STORAGE_KEY_SCALE, String(value))
}
return [scale, set]
}
//////////////////////////////////////////////////////////////////////////////////////
export function getInitialTheme() {
if (typeof localStorage === 'undefined') {
return 'system'
}
const theme = localStorage.getItem(STORAGE_KEY_THEME)
return theme === 'dark' || theme === 'light' ? theme : 'system'
}
//////////////////////////////////////////////////////////////////////////////////////
export function getInitialHideShortcut(): string | null {
if (typeof localStorage === 'undefined') {
return null
}
const hideShortcut = localStorage.getItem(STORAGE_KEY_HIDE_SHORTCUT)
return hideShortcut ? hideShortcut : null
}
export function useHideShortcutStorage(): [
string | null,
(value: string | null) => void,
] {
const [hideShortcut, setHideShortcut] = useState<string | null>(
getInitialHideShortcut()
)
function set(value: string | null) {
setHideShortcut(value)
if (value === null) {
localStorage.removeItem(STORAGE_KEY_HIDE_SHORTCUT)
} else {
localStorage.setItem(STORAGE_KEY_HIDE_SHORTCUT, value)
}
}
return [hideShortcut, set]
}
import { useState, type HTMLProps } from 'react' import type { HTMLProps } from 'react'
import type {
DevToolsIndicatorPosition,
DevToolsScale,
} from '../../../../shared'
import { css } from '../../../../utils/css' import { css } from '../../../../utils/css'
import EyeIcon from '../../../../icons/eye-icon' import EyeIcon from '../../../../icons/eye-icon'
import { import { NEXT_DEV_TOOLS_SCALE } from '../../../../shared'
NEXT_DEV_TOOLS_SCALE,
STORAGE_KEY_POSITION,
STORAGE_KEY_THEME,
} from '../../../../shared'
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 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 {
getInitialTheme,
type DevToolsIndicatorPosition,
type DevToolsScale,
} from './preferences'
import { ShortcutRecorder } from './shortcut-recorder' import { ShortcutRecorder } from './shortcut-recorder'
import { useRestartServer } from '../../error-overlay-toolbar/use-restart-server' import { useRestartServer } from '../../error-overlay-toolbar/use-restart-server'
import { saveDevToolsConfig } from '../../../../utils/save-devtools-config'
export function UserPreferences({ export function UserPreferences({
theme,
hide, hide,
hideShortcut, hideShortcut,
setHideShortcut, setHideShortcut,
...@@ -29,6 +27,7 @@ export function UserPreferences({ ...@@ -29,6 +27,7 @@ export function UserPreferences({
setPosition, setPosition,
...props ...props
}: { }: {
theme: 'dark' | 'light' | 'system'
hide: () => void hide: () => void
hideShortcut: string | null hideShortcut: string | null
setHideShortcut: (value: string | null) => void setHideShortcut: (value: string | null) => void
...@@ -41,6 +40,7 @@ export function UserPreferences({ ...@@ -41,6 +40,7 @@ export function UserPreferences({
return ( return (
<DevToolsInfo title="Preferences" {...props}> <DevToolsInfo title="Preferences" {...props}>
<UserPreferencesBody <UserPreferencesBody
theme={theme}
scale={scale} scale={scale}
position={position} position={position}
setPosition={setPosition} setPosition={setPosition}
...@@ -54,6 +54,7 @@ export function UserPreferences({ ...@@ -54,6 +54,7 @@ export function UserPreferences({
} }
export function UserPreferencesBody({ export function UserPreferencesBody({
theme,
hide, hide,
hideShortcut, hideShortcut,
setHideShortcut, setHideShortcut,
...@@ -62,6 +63,7 @@ export function UserPreferencesBody({ ...@@ -62,6 +63,7 @@ export function UserPreferencesBody({
setScale, setScale,
position, position,
}: { }: {
theme: 'dark' | 'light' | 'system'
hide: () => void hide: () => void
hideShortcut: string | null hideShortcut: string | null
setHideShortcut: (value: string | null) => void setHideShortcut: (value: string | null) => void
...@@ -71,40 +73,42 @@ export function UserPreferencesBody({ ...@@ -71,40 +73,42 @@ export function UserPreferencesBody({
setScale: (value: DevToolsScale) => void setScale: (value: DevToolsScale) => void
}) { }) {
const { restartServer, isPending } = useRestartServer() const { restartServer, isPending } = useRestartServer()
const [theme, setTheme] = useState(getInitialTheme())
const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const portal = document.querySelector('nextjs-portal') const portal = document.querySelector('nextjs-portal')
if (!portal) return if (!portal) {
return
setTheme(e.target.value) }
if (e.target.value === 'system') { if (e.target.value === 'system') {
portal.classList.remove('dark') portal.classList.remove('dark')
portal.classList.remove('light') portal.classList.remove('light')
localStorage.removeItem(STORAGE_KEY_THEME) saveDevToolsConfig({ theme: 'system' })
return return
} }
if (e.target.value === 'dark') { if (e.target.value === 'dark') {
portal.classList.add('dark') portal.classList.add('dark')
portal.classList.remove('light') portal.classList.remove('light')
localStorage.setItem(STORAGE_KEY_THEME, 'dark') saveDevToolsConfig({ theme: 'dark' })
} else { } else {
portal.classList.remove('dark') portal.classList.remove('dark')
portal.classList.add('light') portal.classList.add('light')
localStorage.setItem(STORAGE_KEY_THEME, 'light') saveDevToolsConfig({ theme: 'light' })
} }
} }
function handlePositionChange(e: React.ChangeEvent<HTMLSelectElement>) { function handlePositionChange(e: React.ChangeEvent<HTMLSelectElement>) {
setPosition(e.target.value as DevToolsIndicatorPosition) setPosition(e.target.value as DevToolsIndicatorPosition)
localStorage.setItem(STORAGE_KEY_POSITION, e.target.value) saveDevToolsConfig({
devToolsPosition: e.target.value as DevToolsIndicatorPosition,
})
} }
function handleSizeChange({ target }: React.ChangeEvent<HTMLSelectElement>) { function handleSizeChange({ target }: React.ChangeEvent<HTMLSelectElement>) {
const value = Number(target.value) as DevToolsScale const value = Number(target.value) as DevToolsScale
setScale(value) setScale(value)
saveDevToolsConfig({ scale: value })
} }
return ( return (
......
import * as React from 'react' import * as React from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { STORAGE_KEY_THEME } from '../shared' import { useDevOverlayContext } from '../../dev-overlay.browser'
export function ShadowPortal({ children }: { children: React.ReactNode }) { export function ShadowPortal({ children }: { children: React.ReactNode }) {
const { state } = useDevOverlayContext()
let portalNode = React.useRef<HTMLElement | null>(null) let portalNode = React.useRef<HTMLElement | null>(null)
let shadowNode = React.useRef<ShadowRoot | null>(null) let shadowNode = React.useRef<ShadowRoot | null>(null)
let [, forceUpdate] = React.useState<{} | undefined>() let [, forceUpdate] = React.useState<{} | undefined>()
...@@ -14,16 +15,16 @@ export function ShadowPortal({ children }: { children: React.ReactNode }) { ...@@ -14,16 +15,16 @@ export function ShadowPortal({ children }: { children: React.ReactNode }) {
React.useEffect(() => { React.useEffect(() => {
const ownerDocument = document const ownerDocument = document
portalNode.current = ownerDocument.querySelector('nextjs-portal')! portalNode.current = ownerDocument.querySelector('nextjs-portal')!
// load default color preference from localstorage
if (typeof localStorage !== 'undefined') { if (state.theme === 'dark') {
const theme = localStorage.getItem(STORAGE_KEY_THEME) portalNode.current.classList.add('dark')
if (theme === 'dark') { portalNode.current.classList.remove('light')
portalNode.current.classList.add('dark') } else if (state.theme === 'light') {
portalNode.current.classList.remove('light') portalNode.current.classList.add('light')
} else if (theme === 'light') { portalNode.current.classList.remove('dark')
portalNode.current.classList.remove('dark') } else {
portalNode.current.classList.add('light') portalNode.current.classList.remove('dark')
} portalNode.current.classList.remove('light')
} }
// We can only attach but never detach a shadow root. // We can only attach but never detach a shadow root.
...@@ -35,7 +36,7 @@ export function ShadowPortal({ children }: { children: React.ReactNode }) { ...@@ -35,7 +36,7 @@ export function ShadowPortal({ children }: { children: React.ReactNode }) {
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' }) shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
} }
forceUpdate({}) forceUpdate({})
}, []) }, [state.theme])
return shadowNode.current return shadowNode.current
? createPortal(children, shadowNode.current as any) ? createPortal(children, shadowNode.current as any)
......
...@@ -26,9 +26,9 @@ import { ...@@ -26,9 +26,9 @@ import {
} from '../shared' } from '../shared'
import GearIcon from '../icons/gear-icon' import GearIcon from '../icons/gear-icon'
import { UserPreferencesBody } from '../components/errors/dev-tools-indicator/dev-tools-info/user-preferences' import { UserPreferencesBody } from '../components/errors/dev-tools-indicator/dev-tools-info/user-preferences'
import { useHideShortcutStorage } from '../components/errors/dev-tools-indicator/dev-tools-info/preferences'
import { useShortcuts } from '../hooks/use-shortcuts' import { useShortcuts } from '../hooks/use-shortcuts'
import { useUpdateAllPanelPositions } from '../components/devtools-indicator/devtools-indicator' import { useUpdateAllPanelPositions } from '../components/devtools-indicator/devtools-indicator'
import { saveDevToolsConfig } from '../utils/save-devtools-config'
import './panel-router.css' import './panel-router.css'
const MenuPanel = () => { const MenuPanel = () => {
...@@ -143,11 +143,11 @@ export const PanelRouter = () => { ...@@ -143,11 +143,11 @@ export const PanelRouter = () => {
const toggleDevtools = useToggleDevtoolsVisibility() const toggleDevtools = useToggleDevtoolsVisibility()
const isAppRouter = state.routerType === 'app' const isAppRouter = state.routerType === 'app'
const [hideShortcut, setHideShortcut] = useHideShortcutStorage()
useShortcuts( useShortcuts(
hideShortcut ? { [hideShortcut]: toggleDevtools } : {}, state.hideShortcut ? { [state.hideShortcut]: toggleDevtools } : {},
triggerRef triggerRef
) )
return ( return (
<> <>
<PanelRoute name="panel-selector"> <PanelRoute name="panel-selector">
...@@ -165,10 +165,7 @@ export const PanelRouter = () => { ...@@ -165,10 +165,7 @@ export const PanelRouter = () => {
closeOnClickOutside closeOnClickOutside
header={<DevToolsHeader title="Preferences" />} header={<DevToolsHeader title="Preferences" />}
> >
<UserPreferencesWrapper <UserPreferencesWrapper />
hideShortcut={hideShortcut}
setHideShortcut={setHideShortcut}
/>
</DynamicPanel> </DynamicPanel>
</PanelRoute> </PanelRoute>
...@@ -267,13 +264,7 @@ const InfoFooter = ({ href }: { href: string }) => { ...@@ -267,13 +264,7 @@ const InfoFooter = ({ href }: { href: string }) => {
) )
} }
const UserPreferencesWrapper = ({ const UserPreferencesWrapper = () => {
hideShortcut,
setHideShortcut,
}: {
hideShortcut: string | null
setHideShortcut: (value: string | null) => void
}) => {
const { dispatch, state } = useDevOverlayContext() const { dispatch, state } = useDevOverlayContext()
const { setPanel, setSelectedIndex } = usePanelRouterContext() const { setPanel, setSelectedIndex } = usePanelRouterContext()
const updateAllPanelPositions = useUpdateAllPanelPositions() const updateAllPanelPositions = useUpdateAllPanelPositions()
...@@ -281,6 +272,7 @@ const UserPreferencesWrapper = ({ ...@@ -281,6 +272,7 @@ const UserPreferencesWrapper = ({
return ( return (
<div className="user-preferences-wrapper"> <div className="user-preferences-wrapper">
<UserPreferencesBody <UserPreferencesBody
theme={state.theme}
position={state.devToolsPosition} position={state.devToolsPosition}
scale={state.scale} scale={state.scale}
setScale={(scale) => { setScale={(scale) => {
...@@ -296,8 +288,10 @@ const UserPreferencesWrapper = ({ ...@@ -296,8 +288,10 @@ const UserPreferencesWrapper = ({
}) })
updateAllPanelPositions(devToolsPosition) updateAllPanelPositions(devToolsPosition)
}} }}
hideShortcut={hideShortcut} hideShortcut={state.hideShortcut}
setHideShortcut={setHideShortcut} setHideShortcut={(value) => {
saveDevToolsConfig({ hideShortcut: value })
}}
hide={() => { hide={() => {
dispatch({ dispatch({
type: ACTION_DEV_INDICATOR_SET, type: ACTION_DEV_INDICATOR_SET,
......
import { useMemo, useRef, useState, useEffect, type CSSProperties } from 'react' import { useRef, useState, useEffect, type CSSProperties } from 'react'
import { useDevOverlayContext } from '../../dev-overlay.browser' import { useDevOverlayContext } from '../../dev-overlay.browser'
import { INDICATOR_PADDING } from '../components/devtools-indicator/devtools-indicator' import { INDICATOR_PADDING } from '../components/devtools-indicator/devtools-indicator'
import { ResizeHandle } from '../components/devtools-panel/resize/resize-handle' import { ResizeHandle } from '../components/devtools-panel/resize/resize-handle'
...@@ -19,6 +19,7 @@ import { ...@@ -19,6 +19,7 @@ import {
STORE_KEY_SHARED_PANEL_SIZE, STORE_KEY_SHARED_PANEL_SIZE,
} from '../shared' } from '../shared'
import { getIndicatorOffset } from '../utils/indicator-metrics' import { getIndicatorOffset } from '../utils/indicator-metrics'
import { saveDevToolsConfig } from '../utils/save-devtools-config'
import './dynamic-panel.css' import './dynamic-panel.css'
function resolveCSSValue( function resolveCSSValue(
...@@ -72,34 +73,6 @@ function useResolvedDimensions( ...@@ -72,34 +73,6 @@ function useResolvedDimensions(
return dimensions return dimensions
} }
function getStoredPanelSize(panelName?: string) {
const key = panelName
? `${STORE_KEY_PANEL_SIZE_PREFIX}_${panelName}`
: STORE_KEY_SHARED_PANEL_SIZE
const defaultSize = { width: 450, height: 350 }
try {
const stored = JSON.parse(localStorage.getItem(key) ?? 'null')
if (!stored) {
return defaultSize
}
if (
typeof stored === 'object' &&
'height' in stored &&
'width' in stored &&
typeof stored.height === 'number' &&
typeof stored.width === 'number'
) {
return {
width: stored.width as number,
height: stored.height as number,
}
}
return null
} catch {
return null
}
}
export function DynamicPanel({ export function DynamicPanel({
header, header,
children, children,
...@@ -217,7 +190,10 @@ export function DynamicPanel({ ...@@ -217,7 +190,10 @@ export function DynamicPanel({
const maxWidth = resolvedDimensions.maxWidth const maxWidth = resolvedDimensions.maxWidth
const maxHeight = resolvedDimensions.maxHeight const maxHeight = resolvedDimensions.maxHeight
const panelSize = useMemo(() => getStoredPanelSize(name), [name]) const panelSizeKey = name
? `${STORE_KEY_PANEL_SIZE_PREFIX}_${name}`
: STORE_KEY_SHARED_PANEL_SIZE
const panelSize = state.devToolsPanelSize[panelSizeKey]
return ( return (
<ResizeProvider <ResizeProvider
...@@ -230,6 +206,7 @@ export function DynamicPanel({ ...@@ -230,6 +206,7 @@ export function DynamicPanel({
maxWidth, maxWidth,
maxHeight, maxHeight,
devToolsPosition: state.devToolsPosition, devToolsPosition: state.devToolsPosition,
devToolsPanelSize: state.devToolsPanelSize,
storageKey: resizeStorageKey, storageKey: resizeStorageKey,
}} }}
> >
...@@ -272,14 +249,19 @@ export function DynamicPanel({ ...@@ -272,14 +249,19 @@ export function DynamicPanel({
padding={INDICATOR_PADDING} padding={INDICATOR_PADDING}
position={devtoolsPanelPosition} position={devtoolsPanelPosition}
setPosition={(p) => { setPosition={(p) => {
if (sizeConfig.kind === 'resizable') {
localStorage.setItem(positionStorageKey, p)
}
dispatch({ dispatch({
type: ACTION_DEVTOOLS_PANEL_POSITION, type: ACTION_DEVTOOLS_PANEL_POSITION,
devToolsPanelPosition: p, devToolsPanelPosition: p,
key: positionStorageKey, key: positionStorageKey,
}) })
if (sizeConfig.kind === 'resizable') {
saveDevToolsConfig({
devToolsPanelPosition: {
[positionStorageKey]: p,
},
})
}
}} }}
style={{ style={{
overflow: 'auto', overflow: 'auto',
......
...@@ -8,7 +8,21 @@ import type { DevIndicatorServerState } from '../../server/dev/dev-indicator-ser ...@@ -8,7 +8,21 @@ import type { DevIndicatorServerState } from '../../server/dev/dev-indicator-ser
import { parseStack } from '../../server/lib/parse-stack' import { parseStack } from '../../server/lib/parse-stack'
import { isConsoleError } from '../shared/console-error' import { isConsoleError } from '../shared/console-error'
export type DevToolsConfig = {
theme?: 'light' | 'dark' | 'system'
disableDevIndicator?: boolean
devToolsPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
devToolsPanelPosition?: Record<
string,
'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
>
devToolsPanelSize?: Record<string, { width: number; height: number }>
scale?: number
hideShortcut?: string | null
}
export type Corners = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' export type Corners = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
export type DevToolsIndicatorPosition = Corners
const BASE_SIZE = 16 const BASE_SIZE = 16
...@@ -18,6 +32,9 @@ export const NEXT_DEV_TOOLS_SCALE = { ...@@ -18,6 +32,9 @@ export const NEXT_DEV_TOOLS_SCALE = {
Large: BASE_SIZE / 18, Large: BASE_SIZE / 18,
} }
export type DevToolsScale =
(typeof NEXT_DEV_TOOLS_SCALE)[keyof typeof NEXT_DEV_TOOLS_SCALE]
type FastRefreshState = type FastRefreshState =
/** No refresh in progress. */ /** No refresh in progress. */
| { type: 'idle' } | { type: 'idle' }
...@@ -49,8 +66,14 @@ export interface OverlayState { ...@@ -49,8 +66,14 @@ export interface OverlayState {
isErrorOverlayOpen: boolean isErrorOverlayOpen: boolean
devToolsPosition: Corners devToolsPosition: Corners
devToolsPanelPosition: Record<DevtoolsPanelName, Corners> devToolsPanelPosition: Record<DevtoolsPanelName, Corners>
devToolsPanelSize: Record<
DevtoolsPanelName,
{ width: number; height: number }
>
scale: number scale: number
page: string page: string
theme: 'light' | 'dark' | 'system'
hideShortcut: string | null
} }
type DevtoolsPanelName = string type DevtoolsPanelName = string
export type OverlayDispatch = React.Dispatch<DispatcherEvent> export type OverlayDispatch = React.Dispatch<DispatcherEvent>
...@@ -86,6 +109,8 @@ export const ACTION_DEVTOOLS_PANEL_SIZE = 'devtools-panel-size' ...@@ -86,6 +109,8 @@ 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 ACTION_DEVTOOLS_CONFIG = 'devtools-config'
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 = export const STORAGE_KEY_PANEL_POSITION_PREFIX =
...@@ -96,7 +121,6 @@ export const STORE_KEY_SHARED_PANEL_SIZE = ...@@ -96,7 +121,6 @@ export const STORE_KEY_SHARED_PANEL_SIZE =
export const STORE_KEY_SHARED_PANEL_LOCATION = export const STORE_KEY_SHARED_PANEL_LOCATION =
'__nextjs-dev-tools-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 ACTION_DEVTOOL_UPDATE_ROUTE_STATE = export const ACTION_DEVTOOL_UPDATE_ROUTE_STATE =
'segment-explorer-update-route-state' 'segment-explorer-update-route-state'
...@@ -199,6 +223,11 @@ export interface RestartServerButtonAction { ...@@ -199,6 +223,11 @@ export interface RestartServerButtonAction {
showRestartServerButton: boolean showRestartServerButton: boolean
} }
export interface DevToolsConfigAction {
type: typeof ACTION_DEVTOOLS_CONFIG
devToolsConfig: DevToolsConfig
}
export type DispatcherEvent = export type DispatcherEvent =
| BuildOkAction | BuildOkAction
| BuildErrorAction | BuildErrorAction
...@@ -223,6 +252,7 @@ export type DispatcherEvent = ...@@ -223,6 +252,7 @@ export type DispatcherEvent =
| DevToolUpdateRouteStateAction | DevToolUpdateRouteStateAction
| RestartServerButtonAction | RestartServerButtonAction
| DevIndicatorSetAction | DevIndicatorSetAction
| DevToolsConfigAction
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX =
// 1st group: new frame + v8 // 1st group: new frame + v8
...@@ -242,41 +272,6 @@ function getStackIgnoringStrictMode(stack: string | undefined) { ...@@ -242,41 +272,6 @@ 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'
...@@ -299,13 +294,15 @@ export const INITIAL_OVERLAY_STATE: Omit< ...@@ -299,13 +294,15 @@ export const INITIAL_OVERLAY_STATE: Omit<
versionInfo: { installed: '0.0.0', staleness: 'unknown' }, versionInfo: { installed: '0.0.0', staleness: 'unknown' },
debugInfo: { devtoolsFrontendUrl: undefined }, debugInfo: { devtoolsFrontendUrl: undefined },
showRestartServerButton: false, showRestartServerButton: false,
devToolsPosition: getStoredPosition(), devToolsPosition: 'bottom-left',
devToolsPanelPosition: { devToolsPanelPosition: {
[STORE_KEY_SHARED_PANEL_LOCATION]: getStoredPanelPosition(), [STORE_KEY_SHARED_PANEL_LOCATION]: 'bottom-left',
}, },
devToolsPanelSize: {},
scale: NEXT_DEV_TOOLS_SCALE.Medium, scale: NEXT_DEV_TOOLS_SCALE.Medium,
page: '', page: '',
theme: 'system',
hideShortcut: null,
} }
function getInitialState( function getInitialState(
...@@ -497,6 +494,32 @@ export function useErrorOverlayReducer( ...@@ -497,6 +494,32 @@ export function useErrorOverlayReducer(
showRestartServerButton: action.showRestartServerButton, showRestartServerButton: action.showRestartServerButton,
} }
} }
case ACTION_DEVTOOLS_CONFIG: {
const {
theme,
disableDevIndicator,
devToolsPosition,
devToolsPanelPosition,
devToolsPanelSize,
scale,
hideShortcut,
} = action.devToolsConfig
return {
...state,
theme: theme ?? state.theme,
disableDevIndicator:
disableDevIndicator ?? state.disableDevIndicator,
devToolsPosition: devToolsPosition ?? state.devToolsPosition,
devToolsPanelPosition:
devToolsPanelPosition ?? state.devToolsPanelPosition,
scale: scale ?? state.scale,
devToolsPanelSize: devToolsPanelSize ?? state.devToolsPanelSize,
hideShortcut:
// hideShortcut can be null.
hideShortcut !== undefined ? hideShortcut : state.hideShortcut,
}
}
default: { default: {
return state return state
} }
......
...@@ -11,6 +11,7 @@ import { ...@@ -11,6 +11,7 @@ import {
ACTION_DEV_INDICATOR, ACTION_DEV_INDICATOR,
ACTION_DEV_INDICATOR_SET, ACTION_DEV_INDICATOR_SET,
ACTION_DEVTOOL_UPDATE_ROUTE_STATE, ACTION_DEVTOOL_UPDATE_ROUTE_STATE,
ACTION_DEVTOOLS_CONFIG,
ACTION_DEVTOOLS_PANEL_POSITION, ACTION_DEVTOOLS_PANEL_POSITION,
ACTION_DEVTOOLS_POSITION, ACTION_DEVTOOLS_POSITION,
ACTION_DEVTOOLS_SCALE, ACTION_DEVTOOLS_SCALE,
...@@ -86,6 +87,7 @@ export function useStorybookOverlayReducer(initialState?: OverlayState) { ...@@ -86,6 +87,7 @@ export function useStorybookOverlayReducer(initialState?: OverlayState) {
case ACTION_UNHANDLED_ERROR: case ACTION_UNHANDLED_ERROR:
case ACTION_UNHANDLED_REJECTION: case ACTION_UNHANDLED_REJECTION:
case ACTION_VERSION_INFO: case ACTION_VERSION_INFO:
case ACTION_DEVTOOLS_CONFIG:
return state return state
default: { default: {
return action satisfies never return action satisfies never
......
import { css } from '../utils/css' import { css } from '../utils/css'
import type { DevToolsScale } from '../components/errors/dev-tools-indicator/dev-tools-info/preferences' import type { DevToolsScale } from '../shared'
export function Base({ scale = 1 }: { scale?: DevToolsScale }) { export function Base({ scale = 1 }: { scale?: DevToolsScale }) {
return ( return (
......
import type { DevToolsConfig } from '../shared'
import { devToolsConfigSchema } from '../../shared/devtools-config-schema'
import { deepMerge } from '../../shared/deepmerge'
let queuedConfigPatch: DevToolsConfig = {}
let timer: ReturnType<typeof setTimeout> | null = null
function flushPatch() {
if (Object.keys(queuedConfigPatch).length === 0) {
return
}
const body = JSON.stringify(queuedConfigPatch)
queuedConfigPatch = {}
fetch('/__nextjs_devtools_config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body,
// keepalive in case of fetch interrupted, e.g. navigation or reload
keepalive: true,
}).catch((error) => {
console.warn('[Next.js DevTools] Failed to save config:', {
data: body,
error,
})
})
}
export function saveDevToolsConfig(patch: DevToolsConfig) {
const validation = devToolsConfigSchema.safeParse(patch)
if (!validation.success) {
console.warn(
'[Next.js DevTools] Invalid config patch:',
validation.error.message
)
return
}
queuedConfigPatch = deepMerge(queuedConfigPatch, patch)
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(flushPatch, 120)
}
import type { IncomingMessage, ServerResponse } from 'http'
import type { DevToolsConfig } from '../dev-overlay/shared'
import { existsSync } from 'fs'
import { readFile, writeFile, mkdir } from 'fs/promises'
import { dirname, join } from 'path'
import { middlewareResponse } from './middleware-response'
import { devToolsConfigSchema } from '../shared/devtools-config-schema'
import { deepMerge } from '../shared/deepmerge'
const DEVTOOLS_CONFIG_FILENAME = 'next-devtools-config.json'
const DEVTOOLS_CONFIG_MIDDLEWARE_ENDPOINT = '/__nextjs_devtools_config'
export function devToolsConfigMiddleware({
distDir,
sendUpdateSignal,
}: {
distDir: string
sendUpdateSignal: (data: DevToolsConfig) => void
}) {
const configPath = join(distDir, 'cache', DEVTOOLS_CONFIG_FILENAME)
return async function devToolsConfigMiddlewareHandler(
req: IncomingMessage,
res: ServerResponse,
next: () => void
): Promise<void> {
const { pathname } = new URL(`http://n${req.url}`)
if (pathname !== DEVTOOLS_CONFIG_MIDDLEWARE_ENDPOINT) {
return next()
}
if (req.method !== 'POST') {
return middlewareResponse.methodNotAllowed(res)
}
const currentConfig = await getDevToolsConfig(distDir)
const chunks: Buffer[] = []
for await (const chunk of req) {
chunks.push(Buffer.from(chunk))
}
let body = Buffer.concat(chunks).toString('utf8')
try {
body = JSON.parse(body)
} catch (error) {
console.error('[Next.js DevTools] Invalid config body passed:', error)
return middlewareResponse.badRequest(res)
}
const validation = devToolsConfigSchema.safeParse(body)
if (!validation.success) {
console.error(
'[Next.js DevTools] Invalid config passed:',
validation.error.message
)
return middlewareResponse.badRequest(res)
}
const newConfig = deepMerge(currentConfig, validation.data)
await writeFile(configPath, JSON.stringify(newConfig, null, 2))
sendUpdateSignal(newConfig)
return middlewareResponse.noContent(res)
}
}
export async function getDevToolsConfig(
distDir: string
): Promise<DevToolsConfig> {
const configPath = join(distDir, 'cache', DEVTOOLS_CONFIG_FILENAME)
if (!existsSync(configPath)) {
await mkdir(dirname(configPath), { recursive: true })
await writeFile(configPath, JSON.stringify({}))
return {}
}
return JSON.parse(await readFile(configPath, 'utf8'))
}
export function deepMerge(target: any, source: any): any {
if (!source || typeof source !== 'object' || Array.isArray(source)) {
return source
}
if (!target || typeof target !== 'object' || Array.isArray(target)) {
return source
}
const result = { ...target }
for (const key in source) {
const sourceValue = source[key]
const targetValue = target[key]
if (sourceValue !== undefined) {
if (
sourceValue &&
typeof sourceValue === 'object' &&
!Array.isArray(sourceValue) &&
targetValue &&
typeof targetValue === 'object' &&
!Array.isArray(targetValue)
) {
result[key] = deepMerge(targetValue, sourceValue)
} else {
result[key] = sourceValue
}
}
}
return result
}
import type { DevToolsConfig } from '../dev-overlay/shared'
import { z } from 'next/dist/compiled/zod'
export const devToolsConfigSchema: z.ZodType<DevToolsConfig> = z.object({
theme: z.enum(['light', 'dark', 'system']).optional(),
disableDevIndicator: z.boolean().optional(),
devToolsPosition: z
.enum(['top-left', 'top-right', 'bottom-left', 'bottom-right'])
.optional(),
devToolsPanelPosition: z
.record(
z.string(),
z.enum(['top-left', 'top-right', 'bottom-left', 'bottom-right'])
)
.optional(),
devToolsPanelSize: z
.record(z.string(), z.object({ width: z.number(), height: z.number() }))
.optional(),
scale: z.number().optional(),
hideShortcut: z.string().nullable().optional(),
})
...@@ -23,6 +23,7 @@ ...@@ -23,6 +23,7 @@
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import type { webpack } from 'next/dist/compiled/webpack/webpack' import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type ws from 'next/dist/compiled/ws' import type ws from 'next/dist/compiled/ws'
import type { DevToolsConfig } from '../../next-devtools/dev-overlay/shared'
import { isMiddlewareFilename } from '../../build/utils' import { isMiddlewareFilename } from '../../build/utils'
import type { VersionInfo } from './parse-version-info' import type { VersionInfo } from './parse-version-info'
import type { HMR_ACTION_TYPES } from './hot-reloader-types' import type { HMR_ACTION_TYPES } from './hot-reloader-types'
...@@ -103,11 +104,13 @@ export class WebpackHotMiddleware { ...@@ -103,11 +104,13 @@ export class WebpackHotMiddleware {
closed: boolean closed: boolean
versionInfo: VersionInfo versionInfo: VersionInfo
devtoolsFrontendUrl: string | undefined devtoolsFrontendUrl: string | undefined
devToolsConfig: DevToolsConfig
constructor( constructor(
compilers: webpack.Compiler[], compilers: webpack.Compiler[],
versionInfo: VersionInfo, versionInfo: VersionInfo,
devtoolsFrontendUrl: string | undefined devtoolsFrontendUrl: string | undefined,
devToolsConfig: DevToolsConfig
) { ) {
this.eventStream = new EventStream() this.eventStream = new EventStream()
this.clientLatestStats = null this.clientLatestStats = null
...@@ -116,6 +119,7 @@ export class WebpackHotMiddleware { ...@@ -116,6 +119,7 @@ export class WebpackHotMiddleware {
this.closed = false this.closed = false
this.versionInfo = versionInfo this.versionInfo = versionInfo
this.devtoolsFrontendUrl = devtoolsFrontendUrl this.devtoolsFrontendUrl = devtoolsFrontendUrl
this.devToolsConfig = devToolsConfig || ({} as DevToolsConfig)
compilers[0].hooks.invalid.tap( compilers[0].hooks.invalid.tap(
'webpack-hot-middleware', 'webpack-hot-middleware',
...@@ -184,6 +188,10 @@ export class WebpackHotMiddleware { ...@@ -184,6 +188,10 @@ export class WebpackHotMiddleware {
} }
} }
public updateDevToolsConfig(newConfig: DevToolsConfig): void {
this.devToolsConfig = newConfig
}
/** /**
* To sync we use the most recent stats but also we append middleware * To sync we use the most recent stats but also we append middleware
* errors. This is because it is possible that middleware fails to compile * errors. This is because it is possible that middleware fails to compile
...@@ -220,6 +228,7 @@ export class WebpackHotMiddleware { ...@@ -220,6 +228,7 @@ export class WebpackHotMiddleware {
devtoolsFrontendUrl: this.devtoolsFrontendUrl, devtoolsFrontendUrl: this.devtoolsFrontendUrl,
}, },
devIndicator: devIndicatorServerState, devIndicator: devIndicatorServerState,
devToolsConfig: this.devToolsConfig,
}) })
} }
} }
......
...@@ -100,6 +100,10 @@ import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compi ...@@ -100,6 +100,10 @@ import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compi
import { getSupportedBrowsers } from '../../build/utils' import { getSupportedBrowsers } from '../../build/utils'
import { receiveBrowserLogsTurbopack } from './browser-logs/receive-logs' import { receiveBrowserLogsTurbopack } from './browser-logs/receive-logs'
import { normalizePath } from '../../lib/normalize-path' import { normalizePath } from '../../lib/normalize-path'
import {
devToolsConfigMiddleware,
getDevToolsConfig,
} from '../../next-devtools/server/devtools-config-middleware'
const wsServer = new ws.Server({ noServer: true }) const wsServer = new ws.Server({ noServer: true })
const isTestMode = !!( const isTestMode = !!(
...@@ -658,6 +662,15 @@ export async function createHotReloaderTurbopack( ...@@ -658,6 +662,15 @@ export async function createHotReloaderTurbopack(
telemetry: opts.telemetry, telemetry: opts.telemetry,
turbopackProject: project, turbopackProject: project,
}), }),
devToolsConfigMiddleware({
distDir,
sendUpdateSignal: (data) => {
hotReloader.send({
action: HMR_ACTIONS_SENT_TO_BROWSER.DEVTOOLS_CONFIG,
data,
})
},
}),
] ]
const versionInfoPromise = getVersionInfo() const versionInfoPromise = getVersionInfo()
...@@ -867,6 +880,7 @@ export async function createHotReloaderTurbopack( ...@@ -867,6 +880,7 @@ export async function createHotReloaderTurbopack(
;(async function () { ;(async function () {
const versionInfo = await versionInfoPromise const versionInfo = await versionInfoPromise
const devToolsConfig = await getDevToolsConfig(distDir)
const sync: SyncAction = { const sync: SyncAction = {
action: HMR_ACTIONS_SENT_TO_BROWSER.SYNC, action: HMR_ACTIONS_SENT_TO_BROWSER.SYNC,
...@@ -878,6 +892,7 @@ export async function createHotReloaderTurbopack( ...@@ -878,6 +892,7 @@ export async function createHotReloaderTurbopack(
devtoolsFrontendUrl, devtoolsFrontendUrl,
}, },
devIndicator: devIndicatorServerState, devIndicator: devIndicatorServerState,
devToolsConfig,
} }
sendToClient(client, sync) sendToClient(client, sync)
......
...@@ -8,6 +8,7 @@ import type { Project, Update as TurbopackUpdate } from '../../build/swc/types' ...@@ -8,6 +8,7 @@ import type { Project, Update as TurbopackUpdate } from '../../build/swc/types'
import type { VersionInfo } from './parse-version-info' import type { VersionInfo } from './parse-version-info'
import type { DebugInfo } from '../../next-devtools/shared/types' import type { DebugInfo } from '../../next-devtools/shared/types'
import type { DevIndicatorServerState } from './dev-indicator-server-state' import type { DevIndicatorServerState } from './dev-indicator-server-state'
import type { DevToolsConfig } from '../../next-devtools/dev-overlay/shared'
export const enum HMR_ACTIONS_SENT_TO_BROWSER { export const enum HMR_ACTIONS_SENT_TO_BROWSER {
ADDED_PAGE = 'addedPage', ADDED_PAGE = 'addedPage',
...@@ -26,6 +27,7 @@ export const enum HMR_ACTIONS_SENT_TO_BROWSER { ...@@ -26,6 +27,7 @@ export const enum HMR_ACTIONS_SENT_TO_BROWSER {
TURBOPACK_CONNECTED = 'turbopack-connected', TURBOPACK_CONNECTED = 'turbopack-connected',
ISR_MANIFEST = 'isrManifest', ISR_MANIFEST = 'isrManifest',
DEV_INDICATOR = 'devIndicator', DEV_INDICATOR = 'devIndicator',
DEVTOOLS_CONFIG = 'devtoolsConfig',
} }
interface ServerErrorAction { interface ServerErrorAction {
...@@ -58,6 +60,7 @@ export interface SyncAction { ...@@ -58,6 +60,7 @@ export interface SyncAction {
updatedModules?: ReadonlyArray<string> updatedModules?: ReadonlyArray<string>
debug?: DebugInfo debug?: DebugInfo
devIndicator: DevIndicatorServerState devIndicator: DevIndicatorServerState
devToolsConfig?: DevToolsConfig
} }
interface BuiltAction { interface BuiltAction {
action: HMR_ACTIONS_SENT_TO_BROWSER.BUILT action: HMR_ACTIONS_SENT_TO_BROWSER.BUILT
...@@ -119,6 +122,11 @@ export interface AppIsrManifestAction { ...@@ -119,6 +122,11 @@ export interface AppIsrManifestAction {
data: Record<string, boolean> data: Record<string, boolean>
} }
export interface DevToolsConfigAction {
action: HMR_ACTIONS_SENT_TO_BROWSER.DEVTOOLS_CONFIG
data: DevToolsConfig
}
export type HMR_ACTION_TYPES = export type HMR_ACTION_TYPES =
| TurbopackMessageAction | TurbopackMessageAction
| TurbopackConnectedAction | TurbopackConnectedAction
...@@ -135,6 +143,7 @@ export type HMR_ACTION_TYPES = ...@@ -135,6 +143,7 @@ export type HMR_ACTION_TYPES =
| DevPagesManifestUpdateAction | DevPagesManifestUpdateAction
| ServerErrorAction | ServerErrorAction
| AppIsrManifestAction | AppIsrManifestAction
| DevToolsConfigAction
export type TurbopackMsgToBrowser = export type TurbopackMsgToBrowser =
| { type: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE; data: any } | { type: HMR_ACTIONS_SENT_TO_BROWSER.TURBOPACK_MESSAGE; data: any }
......
...@@ -91,6 +91,10 @@ import getWebpackBundler from '../../shared/lib/get-webpack-bundler' ...@@ -91,6 +91,10 @@ import getWebpackBundler from '../../shared/lib/get-webpack-bundler'
import { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware' import { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware'
import { checkPersistentCacheInvalidationAndCleanup } from '../../build/webpack/cache-invalidation' import { checkPersistentCacheInvalidationAndCleanup } from '../../build/webpack/cache-invalidation'
import { receiveBrowserLogsWebpack } from './browser-logs/receive-logs' import { receiveBrowserLogsWebpack } from './browser-logs/receive-logs'
import {
devToolsConfigMiddleware,
getDevToolsConfig,
} from '../../next-devtools/server/devtools-config-middleware'
const MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000) const MILLISECONDS_IN_NANOSECOND = BigInt(1_000_000)
...@@ -815,6 +819,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -815,6 +819,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
// Ensure distDir exists before writing package.json // Ensure distDir exists before writing package.json
await fs.mkdir(this.distDir, { recursive: true }) await fs.mkdir(this.distDir, { recursive: true })
const initialDevToolsConfig = await getDevToolsConfig(this.distDir)
const distPackageJsonPath = join(this.distDir, 'package.json') const distPackageJsonPath = join(this.distDir, 'package.json')
// Ensure commonjs handling is used for files in the distDir (generally .next) // Ensure commonjs handling is used for files in the distDir (generally .next)
// Files outside of the distDir can be "type": "module" // Files outside of the distDir can be "type": "module"
...@@ -1553,7 +1559,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1553,7 +1559,8 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
this.webpackHotMiddleware = new WebpackHotMiddleware( this.webpackHotMiddleware = new WebpackHotMiddleware(
this.multiCompiler.compilers, this.multiCompiler.compilers,
this.versionInfo, this.versionInfo,
this.devtoolsFrontendUrl this.devtoolsFrontendUrl,
initialDevToolsConfig
) )
let booted = false let booted = false
...@@ -1608,6 +1615,19 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1608,6 +1615,19 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
? getCacheDirectories(this.activeWebpackConfigs) ? getCacheDirectories(this.activeWebpackConfigs)
: undefined, : undefined,
}), }),
devToolsConfigMiddleware({
distDir: this.distDir,
sendUpdateSignal: (data) => {
// Update the in-memory devToolsConfig value
// which will be used for the next onHMR call.
this.webpackHotMiddleware?.updateDevToolsConfig(data)
this.send({
action: HMR_ACTIONS_SENT_TO_BROWSER.DEVTOOLS_CONFIG,
data,
})
},
}),
] ]
} }
......
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