Unverified Commit 2deacca0 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[devtools] Move ShadowRoot into context (#82296)

Our shadow root was always defined but each callsite guarded against the portal and therefore the shadow root not being defined.
This caution also required authoring cascading updates.

All of this is not required. We just expose the ShadowRoot in context so that everybody can use it directly.
parent 2c0ea98d
<nextjs-portal></nextjs-portal>
import type { Preview } from '@storybook/react' import type { Preview } from '@storybook/react'
import { useInsertionEffect } from 'react'
import { withDevOverlayContexts } from '../src/next-devtools/dev-overlay/storybook/with-dev-overlay-contexts' import { withDevOverlayContexts } from '../src/next-devtools/dev-overlay/storybook/with-dev-overlay-contexts'
function CreatePortalNode() { const portalNode = document.querySelector('nextjs-portal')!
useInsertionEffect(() => { const shadowRoot = portalNode.attachShadow({ mode: 'open' })
const portalNode = document.createElement('nextjs-portal')
document.body.appendChild(portalNode)
return () => {
document.body.removeChild(portalNode)
}
})
return null
}
const preview: Preview = { const preview: Preview = {
parameters: { parameters: {
...@@ -63,15 +52,7 @@ const preview: Preview = { ...@@ -63,15 +52,7 @@ const preview: Preview = {
manual: true, manual: true,
}, },
}, },
decorators: [ decorators: [withDevOverlayContexts({ shadowRoot })],
withDevOverlayContexts(),
(Story) => (
<>
<CreatePortalNode />
<Story />
</>
),
],
} }
export default preview export default preview
...@@ -28,6 +28,7 @@ import { ...@@ -28,6 +28,7 @@ import {
startTransition, startTransition,
useContext, useContext,
useInsertionEffect, useInsertionEffect,
useLayoutEffect,
type ActionDispatch, type ActionDispatch,
} from 'react' } from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
...@@ -189,11 +190,13 @@ function DevOverlayRoot({ ...@@ -189,11 +190,13 @@ function DevOverlayRoot({
getSquashedHydrationErrorDetails, getSquashedHydrationErrorDetails,
isRecoverableError, isRecoverableError,
routerType, routerType,
shadowRoot,
}: { }: {
getOwnerStack: (error: Error) => string | null | undefined getOwnerStack: (error: Error) => string | null | undefined
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
isRecoverableError: (error: Error) => boolean isRecoverableError: (error: Error) => boolean
routerType: 'app' | 'pages' routerType: 'app' | 'pages'
shadowRoot: ShadowRoot
}) { }) {
const [state, dispatch] = useErrorOverlayReducer( const [state, dispatch] = useErrorOverlayReducer(
routerType, routerType,
...@@ -201,6 +204,20 @@ function DevOverlayRoot({ ...@@ -201,6 +204,20 @@ function DevOverlayRoot({
isRecoverableError isRecoverableError
) )
useLayoutEffect(() => {
const portalNode = shadowRoot.host
if (state.theme === 'dark') {
portalNode.classList.add('dark')
portalNode.classList.remove('light')
} else if (state.theme === 'light') {
portalNode.classList.add('light')
portalNode.classList.remove('dark')
} else {
portalNode.classList.remove('dark')
portalNode.classList.remove('light')
}
}, [shadowRoot, state.theme])
useInsertionEffect(() => { useInsertionEffect(() => {
maybeDispatch = dispatch maybeDispatch = dispatch
...@@ -225,6 +242,7 @@ function DevOverlayRoot({ ...@@ -225,6 +242,7 @@ function DevOverlayRoot({
value={{ value={{
dispatch, dispatch,
getSquashedHydrationErrorDetails, getSquashedHydrationErrorDetails,
shadowRoot,
state, state,
}} }}
> >
...@@ -234,6 +252,7 @@ function DevOverlayRoot({ ...@@ -234,6 +252,7 @@ function DevOverlayRoot({
) )
} }
export const DevOverlayContext = createContext<{ export const DevOverlayContext = createContext<{
shadowRoot: ShadowRoot
state: OverlayState & { state: OverlayState & {
routerType: 'pages' | 'app' routerType: 'pages' | 'app'
} }
...@@ -284,6 +303,8 @@ export function renderAppDevOverlay( ...@@ -284,6 +303,8 @@ export function renderAppDevOverlay(
identifierPrefix: 'ndt-', identifierPrefix: 'ndt-',
}) })
const shadowRoot = container.attachShadow({ mode: 'open' })
startTransition(() => { startTransition(() => {
// TODO: Dedicated error boundary or root error callbacks? // TODO: Dedicated error boundary or root error callbacks?
// At least it won't unmount any user code if it errors. // At least it won't unmount any user code if it errors.
...@@ -293,6 +314,7 @@ export function renderAppDevOverlay( ...@@ -293,6 +314,7 @@ export function renderAppDevOverlay(
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetailsApp} getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetailsApp}
isRecoverableError={isRecoverableError} isRecoverableError={isRecoverableError}
routerType="app" routerType="app"
shadowRoot={shadowRoot}
/> />
) )
}) })
...@@ -344,7 +366,9 @@ export function renderPagesDevOverlay( ...@@ -344,7 +366,9 @@ export function renderPagesDevOverlay(
}) })
document.body.appendChild(container) document.body.appendChild(container)
const root = createRoot(container) const root = createRoot(container, { identifierPrefix: 'ndt-' })
const shadowRoot = container.attachShadow({ mode: 'open' })
startTransition(() => { startTransition(() => {
// TODO: Dedicated error boundary or root error callbacks? // TODO: Dedicated error boundary or root error callbacks?
...@@ -355,6 +379,7 @@ export function renderPagesDevOverlay( ...@@ -355,6 +379,7 @@ export function renderPagesDevOverlay(
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails} getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
isRecoverableError={isRecoverableError} isRecoverableError={isRecoverableError}
routerType="pages" routerType="pages"
shadowRoot={shadowRoot}
/> />
) )
}) })
......
...@@ -29,6 +29,7 @@ const Dialog: React.FC<DialogProps> = function Dialog({ ...@@ -29,6 +29,7 @@ const Dialog: React.FC<DialogProps> = function Dialog({
...props ...props
}) { }) {
const dialogRef = React.useRef<HTMLDivElement | null>(null) const dialogRef = React.useRef<HTMLDivElement | null>(null)
// TODO: Document is an external store. Either use useSyncExternalStore or always set the role.
const [role, setRole] = React.useState<string | undefined>( const [role, setRole] = React.useState<string | undefined>(
typeof document !== 'undefined' && document.hasFocus() typeof document !== 'undefined' && document.hasFocus()
? 'dialog' ? 'dialog'
......
...@@ -4,6 +4,7 @@ import type { ...@@ -4,6 +4,7 @@ import type {
DevToolsScale, DevToolsScale,
} from '../../../../shared' } from '../../../../shared'
import { useDevOverlayContext } from '../../../../../dev-overlay.browser'
import { css } from '../../../../utils/css' import { css } from '../../../../utils/css'
import EyeIcon from '../../../../icons/eye-icon' import EyeIcon from '../../../../icons/eye-icon'
import { NEXT_DEV_TOOLS_SCALE } from '../../../../shared' import { NEXT_DEV_TOOLS_SCALE } from '../../../../shared'
...@@ -73,13 +74,10 @@ export function UserPreferencesBody({ ...@@ -73,13 +74,10 @@ export function UserPreferencesBody({
setScale: (value: DevToolsScale) => void setScale: (value: DevToolsScale) => void
}) { }) {
const { restartServer, isPending } = useRestartServer() const { restartServer, isPending } = useRestartServer()
const { shadowRoot } = useDevOverlayContext()
const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => { const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const portal = document.querySelector('nextjs-portal') const portal = shadowRoot.host
if (!portal) {
return
}
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')
......
import { useEffect } from 'react' import { useEffect } from 'react'
export const getShadowRoot = () => {
const portal = document.querySelector('nextjs-portal')
return portal?.shadowRoot
}
export function useFocusTrap( export function useFocusTrap(
rootRef: React.RefObject<HTMLElement | null>, rootRef: React.RefObject<HTMLElement | null>,
triggerRef: React.RefObject<HTMLButtonElement | null> | null, triggerRef: React.RefObject<HTMLButtonElement | null> | null,
......
import './segment-boundary-trigger.css' import './segment-boundary-trigger.css'
import { useCallback, useState, useRef, useMemo } from 'react' import { useCallback, useState, useRef, useMemo } from 'react'
import { Menu } from '@base-ui-components/react/menu' import { Menu } from '@base-ui-components/react/menu'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
import type { import type {
SegmentBoundaryType, SegmentBoundaryType,
SegmentNodeState, SegmentNodeState,
...@@ -31,12 +32,7 @@ export function SegmentBoundaryTrigger({ ...@@ -31,12 +32,7 @@ export function SegmentBoundaryTrigger({
const { pagePath, boundaryType, setBoundaryType: onSelectBoundary } = currNode const { pagePath, boundaryType, setBoundaryType: onSelectBoundary } = currNode
const [isOpen, setIsOpen] = useState(false) const [isOpen, setIsOpen] = useState(false)
// TODO: move this shadowRoot ref util to a shared hook or into context const { shadowRoot } = useDevOverlayContext()
const [shadowRoot] = useState<ShadowRoot>(() => {
const ownerDocument = document
const portalNode = ownerDocument.querySelector('nextjs-portal')!
return portalNode.shadowRoot! as ShadowRoot
})
const triggerRef = useRef<HTMLButtonElement>(null) const triggerRef = useRef<HTMLButtonElement>(null)
const popupRef = useRef<HTMLDivElement>(null) const popupRef = useRef<HTMLDivElement>(null)
......
import * as React from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { useDevOverlayContext } from '../../dev-overlay.browser' import { useDevOverlayContext } from '../../dev-overlay.browser'
export function ShadowPortal({ children }: { children: React.ReactNode }) { export function ShadowPortal({ children }: { children: React.ReactNode }) {
const { state } = useDevOverlayContext() const { shadowRoot } = useDevOverlayContext()
let portalNode = React.useRef<HTMLElement | null>(null)
let shadowNode = React.useRef<ShadowRoot | null>(null)
let [, forceUpdate] = React.useState<{} | undefined>()
// Don't use useLayoutEffect here, as it will cause warnings during SSR in React 18. return createPortal(children, shadowRoot)
// Don't use useSyncExternalStore as an SSR gate unless you verified it doesn't
// downgrade a Transition of the initial root render to a sync render or
// we can assure the root render is not a Transition.
React.useEffect(() => {
const ownerDocument = document
portalNode.current = ownerDocument.querySelector('nextjs-portal')!
if (state.theme === 'dark') {
portalNode.current.classList.add('dark')
portalNode.current.classList.remove('light')
} else if (state.theme === 'light') {
portalNode.current.classList.add('light')
portalNode.current.classList.remove('dark')
} else {
portalNode.current.classList.remove('dark')
portalNode.current.classList.remove('light')
}
// We can only attach but never detach a shadow root.
// So if this is a remount, we don't need to attach a shadow root. Only
// on the very first, DOM-wide mount.
// This is mostly guarding against faulty _app implementations that
// create React Root in getInitialProps but don't clean it up like test/integration/app-tree/pages/_app.tsx
if (portalNode.current.shadowRoot === null) {
shadowNode.current = portalNode.current.attachShadow({ mode: 'open' })
}
forceUpdate({})
}, [state.theme])
// eslint-disable-next-line react-hooks/react-compiler -- TODO
const shadowRoot = shadowNode.current
return shadowRoot ? createPortal(children, shadowRoot as any) : null
} }
import { forwardRef, useState } from 'react' import { forwardRef } from 'react'
import { Tooltip as BaseTooltip } from '@base-ui-components/react/tooltip' import { Tooltip as BaseTooltip } from '@base-ui-components/react/tooltip'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
import { cx } from '../../utils/cx' import { cx } from '../../utils/cx'
import './tooltip.css' import './tooltip.css'
...@@ -26,11 +27,7 @@ export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>( ...@@ -26,11 +27,7 @@ export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>(
}, },
ref ref
) { ) {
const [shadowRoot] = useState<ShadowRoot>(() => { const { shadowRoot } = useDevOverlayContext()
const ownerDocument = document
const portalNode = ownerDocument.querySelector('nextjs-portal')!
return portalNode.shadowRoot! as ShadowRoot
})
if (!title) { if (!title) {
return children return children
} }
......
...@@ -10,7 +10,7 @@ import { ...@@ -10,7 +10,7 @@ import {
storybookDefaultOverlayState, storybookDefaultOverlayState,
useStorybookOverlayReducer, useStorybookOverlayReducer,
} from './storybook/use-overlay-reducer' } from './storybook/use-overlay-reducer'
import { DevOverlayContext } from '../dev-overlay.browser' import { DevOverlayContext, useDevOverlayContext } from '../dev-overlay.browser'
const meta: Meta<typeof DevOverlay> = { const meta: Meta<typeof DevOverlay> = {
component: DevOverlay, component: DevOverlay,
...@@ -46,6 +46,7 @@ const initialState: OverlayState = { ...@@ -46,6 +46,7 @@ const initialState: OverlayState = {
export const Default: Story = { export const Default: Story = {
render: function DevOverlayStory() { render: function DevOverlayStory() {
const [state, dispatch] = useStorybookOverlayReducer(initialState) const [state, dispatch] = useStorybookOverlayReducer(initialState)
const { shadowRoot } = useDevOverlayContext()
return ( return (
<div <div
style={{ style={{
...@@ -67,6 +68,7 @@ export const Default: Story = { ...@@ -67,6 +68,7 @@ export const Default: Story = {
dispatch, dispatch,
getSquashedHydrationErrorDetails: getSquashedHydrationErrorDetails:
getNoSquashedHydrationErrorDetails, getNoSquashedHydrationErrorDetails,
shadowRoot,
state, state,
}} }}
> >
...@@ -81,6 +83,7 @@ export const Default: Story = { ...@@ -81,6 +83,7 @@ export const Default: Story = {
export const WithPanel: Story = { export const WithPanel: Story = {
render: function DevOverlayStory() { render: function DevOverlayStory() {
const [state, dispatch] = useStorybookOverlayReducer(initialState) const [state, dispatch] = useStorybookOverlayReducer(initialState)
const { shadowRoot } = useDevOverlayContext()
return ( return (
<> <>
<img <img
...@@ -96,6 +99,7 @@ export const WithPanel: Story = { ...@@ -96,6 +99,7 @@ export const WithPanel: Story = {
dispatch, dispatch,
getSquashedHydrationErrorDetails: getSquashedHydrationErrorDetails:
getNoSquashedHydrationErrorDetails, getNoSquashedHydrationErrorDetails,
shadowRoot,
state, state,
}} }}
> >
......
...@@ -10,7 +10,6 @@ import { TurbopackInfoBody } from '../components/errors/dev-tools-indicator/dev- ...@@ -10,7 +10,6 @@ import { TurbopackInfoBody } from '../components/errors/dev-tools-indicator/dev-
import { DevToolsHeader } from '../components/errors/dev-tools-indicator/dev-tools-info/dev-tools-header' import { DevToolsHeader } from '../components/errors/dev-tools-indicator/dev-tools-info/dev-tools-header'
import { useDelayedRender } from '../hooks/use-delayed-render' import { useDelayedRender } from '../hooks/use-delayed-render'
import { import {
getShadowRoot,
MENU_CURVE, MENU_CURVE,
MENU_DURATION_MS, MENU_DURATION_MS,
} from '../components/errors/dev-tools-indicator/utils' } from '../components/errors/dev-tools-indicator/utils'
...@@ -110,29 +109,27 @@ const MenuPanel = () => { ...@@ -110,29 +109,27 @@ const MenuPanel = () => {
// a little hacky but it does the trick // a little hacky but it does the trick
const useToggleDevtoolsVisibility = () => { const useToggleDevtoolsVisibility = () => {
const { state, dispatch } = useDevOverlayContext() const { state, dispatch, shadowRoot } = useDevOverlayContext()
return () => { return () => {
dispatch({ dispatch({
type: ACTION_DEV_INDICATOR_SET, type: ACTION_DEV_INDICATOR_SET,
disabled: !state.disableDevIndicator, disabled: !state.disableDevIndicator,
}) })
const portal = getShadowRoot()
if (portal) {
const menuElement = portal.getElementById('panel-route') as HTMLElement
const indicatorElement = portal.getElementById(
'data-devtools-indicator'
) as HTMLElement
if (menuElement && menuElement.firstElementChild) { const menuElement = shadowRoot.getElementById('panel-route') as HTMLElement
const firstChild = menuElement.firstElementChild as HTMLElement const indicatorElement = shadowRoot.getElementById(
const isCurrentlyHidden = firstChild.style.display === 'none' 'data-devtools-indicator'
firstChild.style.display = isCurrentlyHidden ? '' : 'none' ) as HTMLElement
}
if (menuElement && menuElement.firstElementChild) {
const firstChild = menuElement.firstElementChild as HTMLElement
const isCurrentlyHidden = firstChild.style.display === 'none'
firstChild.style.display = isCurrentlyHidden ? '' : 'none'
}
if (indicatorElement) { if (indicatorElement) {
const isCurrentlyHidden = indicatorElement.style.display === 'none' const isCurrentlyHidden = indicatorElement.style.display === 'none'
indicatorElement.style.display = isCurrentlyHidden ? '' : 'none' indicatorElement.style.display = isCurrentlyHidden ? '' : 'none'
}
} }
} }
} }
......
import { useRef, useState, type Dispatch, type SetStateAction } from 'react' import { useRef, useState, type Dispatch, type SetStateAction } from 'react'
import { DevOverlayContext } from '../../dev-overlay.browser' import {
DevOverlayContext,
useDevOverlayContext,
} from '../../dev-overlay.browser'
import { RenderErrorContext } from '../dev-overlay' import { RenderErrorContext } from '../dev-overlay'
import { PanelRouterContext, type PanelStateKind } from '../menu/context' import { PanelRouterContext, type PanelStateKind } from '../menu/context'
import { INITIAL_OVERLAY_STATE } from '../shared' import { INITIAL_OVERLAY_STATE } from '../shared'
import type { OverlayState, DispatcherEvent } from '../shared' import type { OverlayState, DispatcherEvent } from '../shared'
import type { ReadyRuntimeError } from '../utils/get-error-by-type' import type { ReadyRuntimeError } from '../utils/get-error-by-type'
interface WithDevOverlayContextsProps { interface WithDevOverlayContextsOptions {
state?: Partial<OverlayState> state?: Partial<OverlayState>
dispatch?: (action: DispatcherEvent) => void dispatch?: (action: DispatcherEvent) => void
runtimeErrors?: ReadyRuntimeError[] runtimeErrors?: ReadyRuntimeError[]
...@@ -15,15 +18,17 @@ interface WithDevOverlayContextsProps { ...@@ -15,15 +18,17 @@ interface WithDevOverlayContextsProps {
setPanel?: Dispatch<SetStateAction<PanelStateKind | null>> setPanel?: Dispatch<SetStateAction<PanelStateKind | null>>
selectedIndex?: number selectedIndex?: number
setSelectedIndex?: Dispatch<SetStateAction<number>> setSelectedIndex?: Dispatch<SetStateAction<number>>
shadowRoot?: ShadowRoot
} }
export const withDevOverlayContexts = export const withDevOverlayContexts =
(props?: WithDevOverlayContextsProps) => (Story: any) => { (options?: WithDevOverlayContextsOptions) => (Story: any) => {
const parentContext = useDevOverlayContext()
const [panel, setPanel] = useState<PanelStateKind | null>( const [panel, setPanel] = useState<PanelStateKind | null>(
props?.panel ?? null options?.panel ?? null
) )
const [selectedIndex, setSelectedIndex] = useState( const [selectedIndex, setSelectedIndex] = useState(
props?.selectedIndex ?? -1 options?.selectedIndex ?? -1
) )
const triggerRef = useRef<HTMLButtonElement>(null) const triggerRef = useRef<HTMLButtonElement>(null)
...@@ -31,10 +36,17 @@ export const withDevOverlayContexts = ...@@ -31,10 +36,17 @@ export const withDevOverlayContexts =
...INITIAL_OVERLAY_STATE, ...INITIAL_OVERLAY_STATE,
routerType: 'app', routerType: 'app',
isErrorOverlayOpen: false, isErrorOverlayOpen: false,
...props?.state, ...options?.state,
} }
const defaultDispatch = props?.dispatch || (() => {}) const defaultDispatch = options?.dispatch || (() => {})
const shadowRoot = options?.shadowRoot ?? parentContext?.shadowRoot
if (shadowRoot == null) {
throw new Error(
'`options.shadowRoot` is required without a parent context'
)
}
return ( return (
<DevOverlayContext.Provider <DevOverlayContext.Provider
...@@ -42,21 +54,22 @@ export const withDevOverlayContexts = ...@@ -42,21 +54,22 @@ export const withDevOverlayContexts =
state: defaultState, state: defaultState,
dispatch: defaultDispatch, dispatch: defaultDispatch,
getSquashedHydrationErrorDetails: () => null, getSquashedHydrationErrorDetails: () => null,
shadowRoot,
}} }}
> >
<RenderErrorContext.Provider <RenderErrorContext.Provider
value={{ value={{
runtimeErrors: props?.runtimeErrors ?? [], runtimeErrors: options?.runtimeErrors ?? [],
totalErrorCount: props?.totalErrorCount ?? 0, totalErrorCount: options?.totalErrorCount ?? 0,
}} }}
> >
<PanelRouterContext.Provider <PanelRouterContext.Provider
value={{ value={{
panel, panel,
setPanel: props?.setPanel ?? setPanel, setPanel: options?.setPanel ?? setPanel,
triggerRef, triggerRef,
selectedIndex, selectedIndex,
setSelectedIndex: props?.setSelectedIndex ?? setSelectedIndex, setSelectedIndex: options?.setSelectedIndex ?? setSelectedIndex,
}} }}
> >
<Story /> <Story />
......
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