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

[segment-explorer] Signal updates to React (#80316)

We never actually invoked the listeners attached by React. Updates only worked on soft-navigation because we also re-render the DevOverlayRoot and don't bail out anywhere at the moment.

Just invoking the listeners is not sufficient after https://github.com/vercel/next.js/pull/79699 since userspace and dev-overlay would read different versions of `listeners`. I ported the segment explorer into the new folder structure. Updates now flow through the `dispatcher` and then invoking the listeners actually works. Though mid term we should move the segment tree into actual React tree to get rid of the sync updates.

I also noticed that we're missing an implementation for a remove operation which is required to show the correct state during soft navigations.
parent f646f4df
...@@ -27,6 +27,11 @@ import type { DebugInfo } from './shared/types' ...@@ -27,6 +27,11 @@ import type { DebugInfo } from './shared/types'
import { DevOverlay } from './dev-overlay/dev-overlay' import { DevOverlay } from './dev-overlay/dev-overlay'
import type { DevIndicatorServerState } from '../server/dev/dev-indicator-server-state' import type { DevIndicatorServerState } from '../server/dev/dev-indicator-server-state'
import type { VersionInfo } from '../server/dev/parse-version-info' import type { VersionInfo } from '../server/dev/parse-version-info'
import {
insertSegmentNode,
removeSegmentNode,
type SegmentNode,
} from './dev-overlay/segment-explorer'
export interface Dispatcher { export interface Dispatcher {
onBuildOk(): void onBuildOk(): void
...@@ -46,6 +51,14 @@ export interface Dispatcher { ...@@ -46,6 +51,14 @@ export interface Dispatcher {
buildingIndicatorShow(): void buildingIndicatorShow(): void
renderingIndicatorHide(): void renderingIndicatorHide(): void
renderingIndicatorShow(): void renderingIndicatorShow(): void
segmentExplorerNodeAdd(
nodeType: SegmentNode['type'],
pagePath: SegmentNode['pagePath']
): void
segmentExplorerNodeRemove(
nodeType: SegmentNode['type'],
pagePath: SegmentNode['pagePath']
): void
} }
type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1] type Dispatch = ReturnType<typeof useErrorOverlayReducer>[1]
...@@ -131,6 +144,24 @@ export const dispatcher: Dispatcher = { ...@@ -131,6 +144,24 @@ export const dispatcher: Dispatcher = {
renderingIndicatorShow: createQueuable((dispatch: Dispatch) => { renderingIndicatorShow: createQueuable((dispatch: Dispatch) => {
dispatch({ type: ACTION_RENDERING_INDICATOR_SHOW }) dispatch({ type: ACTION_RENDERING_INDICATOR_SHOW })
}), }),
segmentExplorerNodeAdd: createQueuable(
(
_: Dispatch,
nodeType: SegmentNode['type'],
pagePath: SegmentNode['pagePath']
) => {
insertSegmentNode({ type: nodeType, pagePath })
}
),
segmentExplorerNodeRemove: createQueuable(
(
_: Dispatch,
nodeType: SegmentNode['type'],
pagePath: SegmentNode['pagePath']
) => {
removeSegmentNode({ type: nodeType, pagePath })
}
),
} }
function replayQueuedEvents(dispatch: NonNullable<typeof maybeDispatch>) { function replayQueuedEvents(dispatch: NonNullable<typeof maybeDispatch>) {
......
...@@ -2,24 +2,16 @@ import type { HTMLProps } from 'react' ...@@ -2,24 +2,16 @@ import type { HTMLProps } from 'react'
import { css } from '../../utils/css' import { css } from '../../utils/css'
import type { DevToolsInfoPropsCore } from '../errors/dev-tools-indicator/dev-tools-info/dev-tools-info' import type { DevToolsInfoPropsCore } from '../errors/dev-tools-indicator/dev-tools-info/dev-tools-info'
import { DevToolsInfo } from '../errors/dev-tools-indicator/dev-tools-info/dev-tools-info' import { DevToolsInfo } from '../errors/dev-tools-indicator/dev-tools-info/dev-tools-info'
import { import { useSegmentTree, type SegmentTrieNode } from '../../segment-explorer'
type SegmentNode,
useSegmentTreeClientState, function PageSegmentTree({ tree }: { tree: SegmentTrieNode }) {
} from '../../../../shared/lib/devtool/app-segment-tree'
import type { Trie, TrieNode } from '../../../../shared/lib/devtool/trie'
function PageSegmentTree({ tree }: { tree: Trie<SegmentNode> | undefined }) {
if (!tree) {
return null
}
return ( return (
<div <div
className="segment-explorer-content" className="segment-explorer-content"
data-nextjs-devtool-segment-explorer data-nextjs-devtool-segment-explorer
> >
<PageSegmentTreeLayerPresentation <PageSegmentTreeLayerPresentation
tree={tree} node={tree}
node={tree.getRoot()}
level={0} level={0}
segment="" segment=""
parentSegment="" parentSegment=""
...@@ -29,16 +21,14 @@ function PageSegmentTree({ tree }: { tree: Trie<SegmentNode> | undefined }) { ...@@ -29,16 +21,14 @@ function PageSegmentTree({ tree }: { tree: Trie<SegmentNode> | undefined }) {
} }
function PageSegmentTreeLayerPresentation({ function PageSegmentTreeLayerPresentation({
tree,
segment, segment,
parentSegment, parentSegment,
node, node,
level, level,
}: { }: {
tree: Trie<SegmentNode>
segment: string segment: string
parentSegment: string parentSegment: string
node: TrieNode<SegmentNode> node: SegmentTrieNode
level: number level: number
}) { }) {
const pagePath = node.value?.pagePath || '' const pagePath = node.value?.pagePath || ''
...@@ -111,7 +101,6 @@ function PageSegmentTreeLayerPresentation({ ...@@ -111,7 +101,6 @@ function PageSegmentTreeLayerPresentation({
key={childSegment} key={childSegment}
segment={childSegment} segment={childSegment}
parentSegment={segment} parentSegment={segment}
tree={tree}
node={child} node={child}
level={hasFileChildren ? level + 1 : level} level={hasFileChildren ? level + 1 : level}
/> />
...@@ -124,14 +113,11 @@ function PageSegmentTreeLayerPresentation({ ...@@ -124,14 +113,11 @@ function PageSegmentTreeLayerPresentation({
export function SegmentsExplorer( export function SegmentsExplorer(
props: DevToolsInfoPropsCore & HTMLProps<HTMLDivElement> props: DevToolsInfoPropsCore & HTMLProps<HTMLDivElement>
) { ) {
const ctx = useSegmentTreeClientState() const tree = useSegmentTree()
if (!ctx) {
return null
}
return ( return (
<DevToolsInfo title="Segment Explorer" {...props}> <DevToolsInfo title="Segment Explorer" {...props}>
<PageSegmentTree tree={ctx.tree} /> <PageSegmentTree tree={tree} />
</DevToolsInfo> </DevToolsInfo>
) )
} }
......
/**
* @jest-environment jsdom
*/
/* eslint-disable @next/internal/typechecked-require -- Not a prod file */
/* eslint-disable import/no-extraneous-dependencies -- Not a prod file */
import type * as SegmentExplorer from './segment-explorer'
describe('Segment Explorer', () => {
let cleanup: typeof import('@testing-library/react').cleanup
let renderHook: typeof import('@testing-library/react').renderHook
let useSegmentTree: typeof SegmentExplorer.useSegmentTree
let insertSegmentNode: typeof SegmentExplorer.insertSegmentNode
let removeSegmentNode: typeof SegmentExplorer.removeSegmentNode
beforeEach(() => {
jest.resetModules()
jest.clearAllMocks()
const segmentExplorer = require('./segment-explorer')
useSegmentTree = segmentExplorer.useSegmentTree
insertSegmentNode = segmentExplorer.insertSegmentNode
removeSegmentNode = segmentExplorer.removeSegmentNode
const rtl = require('@testing-library/react/pure')
renderHook = rtl.renderHook
cleanup = rtl.cleanup
})
afterEach(() => {
cleanup()
})
test('add complex structure', () => {
insertSegmentNode({ pagePath: '/a/page.js', type: 'page' })
insertSegmentNode({ pagePath: '/a/layout.js', type: 'layout' })
insertSegmentNode({ pagePath: '/layout.js', type: 'layout' })
const { result } = renderHook(useSegmentTree)
expect(result.current).toEqual({
children: {
'': {
children: {
a: {
children: {
'layout.js': {
children: {},
value: {
pagePath: '/a/layout.js',
type: 'layout',
},
},
'page.js': {
children: {},
value: {
pagePath: '/a/page.js',
type: 'page',
},
},
},
value: undefined,
},
'layout.js': {
children: {},
value: {
pagePath: '/layout.js',
type: 'layout',
},
},
},
value: undefined,
},
},
value: undefined,
})
})
test.failing('remove node in the middle', () => {
insertSegmentNode({ pagePath: '/a/b/@sidebar/page.js', type: 'page' })
insertSegmentNode({ pagePath: '/a/b/page.js', type: 'page' })
insertSegmentNode({ pagePath: '/a/b/layout.js', type: 'layout' })
insertSegmentNode({ pagePath: '/a/layout.js', type: 'layout' })
insertSegmentNode({ pagePath: '/layout.js', type: 'layout' })
const { result } = renderHook(useSegmentTree)
expect(result.current).toEqual({
children: {
'': {
children: {
a: {
children: {
b: {
children: {
'@sidebar': {
children: {
'page.js': {
children: {},
value: {
pagePath: '/a/b/@sidebar/page.js',
type: 'page',
},
},
},
value: undefined,
},
'layout.js': {
children: {},
value: {
pagePath: '/a/b/layout.js',
type: 'layout',
},
},
'page.js': {
children: {},
value: {
pagePath: '/a/b/page.js',
type: 'page',
},
},
},
value: undefined,
},
'layout.js': {
children: {},
value: {
pagePath: '/a/layout.js',
type: 'layout',
},
},
},
value: undefined,
},
'layout.js': {
children: {},
value: {
pagePath: '/layout.js',
type: 'layout',
},
},
},
value: undefined,
},
},
value: undefined,
})
removeSegmentNode({ pagePath: '/a/b/layout.js', type: 'layout' })
expect(result.current).toEqual({
children: {
'': {
children: {
a: {
children: {
b: {
children: {
'@sidebar': {
children: {
'page.js': {
children: {},
value: {
pagePath: '/a/b/@sidebar/page.js',
type: 'page',
},
},
},
value: undefined,
},
'page.js': {
children: {},
value: {
pagePath: '/a/b/page.js',
type: 'page',
},
},
},
value: undefined,
},
'layout.js': {
children: {},
value: {
pagePath: '/a/layout.js',
type: 'layout',
},
},
},
value: undefined,
},
'layout.js': {
children: {},
value: {
pagePath: '/layout.js',
type: 'layout',
},
},
},
value: undefined,
},
},
value: undefined,
})
})
})
import { useSyncExternalStore } from 'react'
/** /**
* Trie data structure for storing and searching paths * Trie data structure for storing and searching paths
* *
...@@ -15,19 +17,44 @@ ...@@ -15,19 +17,44 @@
* ├── page.js * ├── page.js
**/ **/
export type TrieNode<Value = string> = { type TrieNode<Value = string> = {
value?: Value value: Value | undefined
children: { children: {
[key: string]: TrieNode<Value> | undefined [key: string]: TrieNode<Value> | undefined
} }
} }
export type Trie<Value = string> = { type Trie<Value = string> = {
insert: (value: Value) => void insert: (value: Value) => void
remove: (value: Value) => void
getRoot: () => TrieNode<Value> getRoot: () => TrieNode<Value>
} }
export function createTrie<Value = string>({ const listeners = new Set<() => void>()
const createSegmentTreeStore = (): {
subscribe: (callback: () => void) => () => void
getSnapshot: () => SegmentTrieNode
getServerSnapshot: () => SegmentTrieNode
} => {
// return a store that can be used by useSyncExternalStore
return {
subscribe: (callback) => {
listeners.add(callback)
return () => listeners.delete(callback)
},
getSnapshot: () => {
return trie.getRoot()
},
getServerSnapshot: () => {
return trie.getRoot()
},
}
}
// TODO: Move the Segment Tree into React State
const { subscribe, getSnapshot, getServerSnapshot } = createSegmentTreeStore()
function createTrie<Value = string>({
getKey = (k) => k as unknown as string, getKey = (k) => k as unknown as string,
}: { }: {
getKey: (k: Value) => string getKey: (k: Value) => string
...@@ -37,6 +64,12 @@ export function createTrie<Value = string>({ ...@@ -37,6 +64,12 @@ export function createTrie<Value = string>({
children: {}, children: {},
} }
function markUpdated() {
for (const listener of listeners) {
listener()
}
}
function insert(value: Value) { function insert(value: Value) {
let currentNode = root let currentNode = root
const key = getKey(value) const key = getKey(value)
...@@ -45,6 +78,7 @@ export function createTrie<Value = string>({ ...@@ -45,6 +78,7 @@ export function createTrie<Value = string>({
for (const segment of segments) { for (const segment of segments) {
if (!currentNode.children[segment]) { if (!currentNode.children[segment]) {
currentNode.children[segment] = { currentNode.children[segment] = {
value: undefined,
// Skip value for intermediate nodes // Skip value for intermediate nodes
children: {}, children: {},
} }
...@@ -53,11 +87,38 @@ export function createTrie<Value = string>({ ...@@ -53,11 +87,38 @@ export function createTrie<Value = string>({
} }
currentNode.value = value currentNode.value = value
markUpdated()
}
function remove(_: Value) {
// TODO Implement remove functionality
markUpdated()
} }
function getRoot(): TrieNode<Value> { function getRoot(): TrieNode<Value> {
return root return root
} }
return { insert, getRoot } return { insert, remove, getRoot }
}
export type SegmentNode = {
type: string
pagePath: string
}
export type SegmentTrie = Trie<SegmentNode>
export type SegmentTrieNode = TrieNode<SegmentNode>
const trie: SegmentTrie = createTrie({
getKey: (item) => item.pagePath,
})
export const insertSegmentNode = trie.insert
export const removeSegmentNode = trie.remove
export function useSegmentTree(): SegmentTrieNode {
const state = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
return state
} }
'use client'
import type { ReactNode } from 'react'
import { useEffect } from 'react'
import { dispatcher } from 'next/dist/compiled/next-devtools'
export function SegmentViewNode({
type,
pagePath,
children,
}: {
type: string
pagePath: string
children: ReactNode
}) {
useEffect(() => {
dispatcher.segmentExplorerNodeAdd(type, pagePath)
return () => {
dispatcher.segmentExplorerNodeRemove(type, pagePath)
}
}, [type, pagePath])
return children
}
...@@ -45,12 +45,12 @@ import { Postpone } from './rsc/postpone' ...@@ -45,12 +45,12 @@ import { Postpone } from './rsc/postpone'
import { taintObjectReference } from './rsc/taint' import { taintObjectReference } from './rsc/taint'
export { collectSegmentData } from './collect-segment-data' export { collectSegmentData } from './collect-segment-data'
let SegmentViewNode: typeof import('../../shared/lib/devtool/app-segment-tree').SegmentViewNode = let SegmentViewNode: typeof import('../../next-devtools/userspace/app/segment-explorer').SegmentViewNode =
() => null () => null
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
const appSegmentTree: typeof import('../../shared/lib/devtool/app-segment-tree') = SegmentViewNode = (
require('../../shared/lib/devtool/app-segment-tree') as typeof import('../../shared/lib/devtool/app-segment-tree') require('../../next-devtools/userspace/app/segment-explorer') as typeof import('../../next-devtools/userspace/app/segment-explorer')
SegmentViewNode = appSegmentTree.SegmentViewNode ).SegmentViewNode
} }
// patchFetch makes use of APIs such as `React.unstable_postpone` which are only available // patchFetch makes use of APIs such as `React.unstable_postpone` which are only available
......
'use client'
import { type ReactNode, useEffect, useSyncExternalStore } from 'react'
import { createTrie, type Trie } from './trie'
export type SegmentNode = {
type: string
pagePath: string
}
type DevtoolClientState = {
tree?: Trie<SegmentNode>
}
const DEFAULT_CLIENT_STATE =
typeof window === 'undefined'
? undefined
: createTrie<SegmentNode>({
getKey: (item) => item.pagePath,
})
declare global {
interface Window {
__NEXT_DEVTOOLS_CLIENT_STATE?: DevtoolClientState
}
}
function getSegmentTreeClientState(): DevtoolClientState {
if (typeof window === 'undefined') {
return {}
}
if (!window.__NEXT_DEVTOOLS_CLIENT_STATE) {
window.__NEXT_DEVTOOLS_CLIENT_STATE = {
// Initial state
tree: DEFAULT_CLIENT_STATE,
}
}
return window.__NEXT_DEVTOOLS_CLIENT_STATE
}
const listeners = typeof window === 'undefined' ? null : new Set<() => void>()
const createSegmentTreeStore = (): {
subscribe: (callback: () => void) => () => void
getSnapshot: () => DevtoolClientState
getServerSnapshot: () => undefined
} => {
if (typeof window === 'undefined') {
return {
subscribe: () => () => void 0,
getSnapshot: () => ({}),
getServerSnapshot: () => undefined,
}
}
// return a store that can be used by useSyncExternalStore
return {
subscribe: (callback) => {
listeners?.add(callback)
return () => listeners?.delete(callback)
},
getSnapshot: () => {
return getSegmentTreeClientState()
},
getServerSnapshot: () => {
return undefined
},
}
}
const { subscribe, getSnapshot, getServerSnapshot } = createSegmentTreeStore()
export function SegmentViewNode({
type,
pagePath,
children,
}: {
type: string
pagePath: string
children: ReactNode
}) {
const clientState = getSegmentTreeClientState()
const tree = clientState.tree
useEffect(() => {
if (!tree) {
return
}
tree.insert({
type,
pagePath,
})
}, [type, pagePath, tree])
return children
}
export function useSegmentTreeClientState() {
const state = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
return state
}
import Link from 'next/link'
export default function SoftNavigationAPage() {
return (
<>
<p>Page A</p>
<Link href="/soft-navigation/b">Go to Page b</Link>
</>
)
}
import Link from 'next/link'
export default function SoftNavigationBPage() {
return (
<>
<p>Page B</p>
<Link href="/soft-navigation/a">Go to Page a</Link>
</>
)
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { openDevToolsIndicatorPopover } from 'next-test-utils' import { openDevToolsIndicatorPopover, retry } from 'next-test-utils'
import { Playwright } from 'next-webdriver' import { Playwright } from 'next-webdriver'
async function getSegmentExplorerContent(browser: Playwright) { async function getSegmentExplorerContent(browser: Playwright) {
...@@ -46,4 +46,24 @@ describe('segment-explorer', () => { ...@@ -46,4 +46,24 @@ describe('segment-explorer', () => {
gridpage.tsx" gridpage.tsx"
`) `)
}) })
it('should cleanup on soft navigation', async () => {
const browser = await next.browser('/soft-navigation/a')
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"applayout.tsx
apage.tsx"
`)
await browser.elementByCss('[href="/soft-navigation/b"]').click()
await retry(async () => {
expect(await browser.elementByCss('body').text()).toContain('Page B')
})
// FIXME: Should no longer contain /soft-navigation/a/page.js
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"applayout.tsx
apage.tsx
bpage.tsx"
`)
})
}) })
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