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 { useInsertionEffect } from 'react'
import { withDevOverlayContexts } from '../src/next-devtools/dev-overlay/storybook/with-dev-overlay-contexts'
function CreatePortalNode() {
useInsertionEffect(() => {
const portalNode = document.createElement('nextjs-portal')
document.body.appendChild(portalNode)
return () => {
document.body.removeChild(portalNode)
}
})
return null
}
const portalNode = document.querySelector('nextjs-portal')!
const shadowRoot = portalNode.attachShadow({ mode: 'open' })
const preview: Preview = {
parameters: {
......@@ -63,15 +52,7 @@ const preview: Preview = {
manual: true,
},
},
decorators: [
withDevOverlayContexts(),
(Story) => (
<>
<CreatePortalNode />
<Story />
</>
),
],
decorators: [withDevOverlayContexts({ shadowRoot })],
}
export default preview
......@@ -28,6 +28,7 @@ import {
startTransition,
useContext,
useInsertionEffect,
useLayoutEffect,
type ActionDispatch,
} from 'react'
import { createRoot } from 'react-dom/client'
......@@ -189,11 +190,13 @@ function DevOverlayRoot({
getSquashedHydrationErrorDetails,
isRecoverableError,
routerType,
shadowRoot,
}: {
getOwnerStack: (error: Error) => string | null | undefined
getSquashedHydrationErrorDetails: (error: Error) => HydrationErrorState | null
isRecoverableError: (error: Error) => boolean
routerType: 'app' | 'pages'
shadowRoot: ShadowRoot
}) {
const [state, dispatch] = useErrorOverlayReducer(
routerType,
......@@ -201,6 +204,20 @@ function DevOverlayRoot({
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(() => {
maybeDispatch = dispatch
......@@ -225,6 +242,7 @@ function DevOverlayRoot({
value={{
dispatch,
getSquashedHydrationErrorDetails,
shadowRoot,
state,
}}
>
......@@ -234,6 +252,7 @@ function DevOverlayRoot({
)
}
export const DevOverlayContext = createContext<{
shadowRoot: ShadowRoot
state: OverlayState & {
routerType: 'pages' | 'app'
}
......@@ -284,6 +303,8 @@ export function renderAppDevOverlay(
identifierPrefix: 'ndt-',
})
const shadowRoot = container.attachShadow({ mode: 'open' })
startTransition(() => {
// TODO: Dedicated error boundary or root error callbacks?
// At least it won't unmount any user code if it errors.
......@@ -293,6 +314,7 @@ export function renderAppDevOverlay(
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetailsApp}
isRecoverableError={isRecoverableError}
routerType="app"
shadowRoot={shadowRoot}
/>
)
})
......@@ -344,7 +366,9 @@ export function renderPagesDevOverlay(
})
document.body.appendChild(container)
const root = createRoot(container)
const root = createRoot(container, { identifierPrefix: 'ndt-' })
const shadowRoot = container.attachShadow({ mode: 'open' })
startTransition(() => {
// TODO: Dedicated error boundary or root error callbacks?
......@@ -355,6 +379,7 @@ export function renderPagesDevOverlay(
getSquashedHydrationErrorDetails={getSquashedHydrationErrorDetails}
isRecoverableError={isRecoverableError}
routerType="pages"
shadowRoot={shadowRoot}
/>
)
})
......
......@@ -29,6 +29,7 @@ const Dialog: React.FC<DialogProps> = function Dialog({
...props
}) {
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>(
typeof document !== 'undefined' && document.hasFocus()
? 'dialog'
......
......@@ -4,6 +4,7 @@ import type {
DevToolsScale,
} from '../../../../shared'
import { useDevOverlayContext } from '../../../../../dev-overlay.browser'
import { css } from '../../../../utils/css'
import EyeIcon from '../../../../icons/eye-icon'
import { NEXT_DEV_TOOLS_SCALE } from '../../../../shared'
......@@ -73,13 +74,10 @@ export function UserPreferencesBody({
setScale: (value: DevToolsScale) => void
}) {
const { restartServer, isPending } = useRestartServer()
const { shadowRoot } = useDevOverlayContext()
const handleThemeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const portal = document.querySelector('nextjs-portal')
if (!portal) {
return
}
const portal = shadowRoot.host
if (e.target.value === 'system') {
portal.classList.remove('dark')
portal.classList.remove('light')
......
import { useEffect } from 'react'
export const getShadowRoot = () => {
const portal = document.querySelector('nextjs-portal')
return portal?.shadowRoot
}
export function useFocusTrap(
rootRef: React.RefObject<HTMLElement | null>,
triggerRef: React.RefObject<HTMLButtonElement | null> | null,
......
import './segment-boundary-trigger.css'
import { useCallback, useState, useRef, useMemo } from 'react'
import { Menu } from '@base-ui-components/react/menu'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
import type {
SegmentBoundaryType,
SegmentNodeState,
......@@ -31,12 +32,7 @@ export function SegmentBoundaryTrigger({
const { pagePath, boundaryType, setBoundaryType: onSelectBoundary } = currNode
const [isOpen, setIsOpen] = useState(false)
// TODO: move this shadowRoot ref util to a shared hook or into context
const [shadowRoot] = useState<ShadowRoot>(() => {
const ownerDocument = document
const portalNode = ownerDocument.querySelector('nextjs-portal')!
return portalNode.shadowRoot! as ShadowRoot
})
const { shadowRoot } = useDevOverlayContext()
const triggerRef = useRef<HTMLButtonElement>(null)
const popupRef = useRef<HTMLDivElement>(null)
......
import * as React from 'react'
import { createPortal } from 'react-dom'
import { useDevOverlayContext } from '../../dev-overlay.browser'
export function ShadowPortal({ children }: { children: React.ReactNode }) {
const { state } = useDevOverlayContext()
let portalNode = React.useRef<HTMLElement | null>(null)
let shadowNode = React.useRef<ShadowRoot | null>(null)
let [, forceUpdate] = React.useState<{} | undefined>()
const { shadowRoot } = useDevOverlayContext()
// Don't use useLayoutEffect here, as it will cause warnings during SSR in React 18.
// 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
return createPortal(children, shadowRoot)
}
import { forwardRef, useState } from 'react'
import { forwardRef } from 'react'
import { Tooltip as BaseTooltip } from '@base-ui-components/react/tooltip'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
import { cx } from '../../utils/cx'
import './tooltip.css'
......@@ -26,11 +27,7 @@ export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>(
},
ref
) {
const [shadowRoot] = useState<ShadowRoot>(() => {
const ownerDocument = document
const portalNode = ownerDocument.querySelector('nextjs-portal')!
return portalNode.shadowRoot! as ShadowRoot
})
const { shadowRoot } = useDevOverlayContext()
if (!title) {
return children
}
......
......@@ -10,7 +10,7 @@ import {
storybookDefaultOverlayState,
useStorybookOverlayReducer,
} from './storybook/use-overlay-reducer'
import { DevOverlayContext } from '../dev-overlay.browser'
import { DevOverlayContext, useDevOverlayContext } from '../dev-overlay.browser'
const meta: Meta<typeof DevOverlay> = {
component: DevOverlay,
......@@ -46,6 +46,7 @@ const initialState: OverlayState = {
export const Default: Story = {
render: function DevOverlayStory() {
const [state, dispatch] = useStorybookOverlayReducer(initialState)
const { shadowRoot } = useDevOverlayContext()
return (
<div
style={{
......@@ -67,6 +68,7 @@ export const Default: Story = {
dispatch,
getSquashedHydrationErrorDetails:
getNoSquashedHydrationErrorDetails,
shadowRoot,
state,
}}
>
......@@ -81,6 +83,7 @@ export const Default: Story = {
export const WithPanel: Story = {
render: function DevOverlayStory() {
const [state, dispatch] = useStorybookOverlayReducer(initialState)
const { shadowRoot } = useDevOverlayContext()
return (
<>
<img
......@@ -96,6 +99,7 @@ export const WithPanel: Story = {
dispatch,
getSquashedHydrationErrorDetails:
getNoSquashedHydrationErrorDetails,
shadowRoot,
state,
}}
>
......
......@@ -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 { useDelayedRender } from '../hooks/use-delayed-render'
import {
getShadowRoot,
MENU_CURVE,
MENU_DURATION_MS,
} from '../components/errors/dev-tools-indicator/utils'
......@@ -110,29 +109,27 @@ const MenuPanel = () => {
// a little hacky but it does the trick
const useToggleDevtoolsVisibility = () => {
const { state, dispatch } = useDevOverlayContext()
const { state, dispatch, shadowRoot } = useDevOverlayContext()
return () => {
dispatch({
type: ACTION_DEV_INDICATOR_SET,
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 firstChild = menuElement.firstElementChild as HTMLElement
const isCurrentlyHidden = firstChild.style.display === 'none'
firstChild.style.display = isCurrentlyHidden ? '' : 'none'
}
const menuElement = shadowRoot.getElementById('panel-route') as HTMLElement
const indicatorElement = shadowRoot.getElementById(
'data-devtools-indicator'
) 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) {
const isCurrentlyHidden = indicatorElement.style.display === 'none'
indicatorElement.style.display = isCurrentlyHidden ? '' : 'none'
}
if (indicatorElement) {
const isCurrentlyHidden = indicatorElement.style.display === 'none'
indicatorElement.style.display = isCurrentlyHidden ? '' : 'none'
}
}
}
......
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 { PanelRouterContext, type PanelStateKind } from '../menu/context'
import { INITIAL_OVERLAY_STATE } from '../shared'
import type { OverlayState, DispatcherEvent } from '../shared'
import type { ReadyRuntimeError } from '../utils/get-error-by-type'
interface WithDevOverlayContextsProps {
interface WithDevOverlayContextsOptions {
state?: Partial<OverlayState>
dispatch?: (action: DispatcherEvent) => void
runtimeErrors?: ReadyRuntimeError[]
......@@ -15,15 +18,17 @@ interface WithDevOverlayContextsProps {
setPanel?: Dispatch<SetStateAction<PanelStateKind | null>>
selectedIndex?: number
setSelectedIndex?: Dispatch<SetStateAction<number>>
shadowRoot?: ShadowRoot
}
export const withDevOverlayContexts =
(props?: WithDevOverlayContextsProps) => (Story: any) => {
(options?: WithDevOverlayContextsOptions) => (Story: any) => {
const parentContext = useDevOverlayContext()
const [panel, setPanel] = useState<PanelStateKind | null>(
props?.panel ?? null
options?.panel ?? null
)
const [selectedIndex, setSelectedIndex] = useState(
props?.selectedIndex ?? -1
options?.selectedIndex ?? -1
)
const triggerRef = useRef<HTMLButtonElement>(null)
......@@ -31,10 +36,17 @@ export const withDevOverlayContexts =
...INITIAL_OVERLAY_STATE,
routerType: 'app',
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 (
<DevOverlayContext.Provider
......@@ -42,21 +54,22 @@ export const withDevOverlayContexts =
state: defaultState,
dispatch: defaultDispatch,
getSquashedHydrationErrorDetails: () => null,
shadowRoot,
}}
>
<RenderErrorContext.Provider
value={{
runtimeErrors: props?.runtimeErrors ?? [],
totalErrorCount: props?.totalErrorCount ?? 0,
runtimeErrors: options?.runtimeErrors ?? [],
totalErrorCount: options?.totalErrorCount ?? 0,
}}
>
<PanelRouterContext.Provider
value={{
panel,
setPanel: props?.setPanel ?? setPanel,
setPanel: options?.setPanel ?? setPanel,
triggerRef,
selectedIndex,
setSelectedIndex: props?.setSelectedIndex ?? setSelectedIndex,
setSelectedIndex: options?.setSelectedIndex ?? setSelectedIndex,
}}
>
<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