Unverified Commit f3d6af95 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[segment explorer] single row layout segment (#80576)

parent 693619fd
......@@ -336,7 +336,7 @@ function DevToolsPopover({
setScale={setScale}
/>
{/* Page Segment Explorer */}
{/* Page Route Info */}
{process.env.__NEXT_DEVTOOL_SEGMENT_EXPLORER ? (
<SegmentsExplorer
isOpen={isSegmentExplorerOpen}
......@@ -414,7 +414,7 @@ function DevToolsPopover({
{process.env.__NEXT_DEVTOOL_SEGMENT_EXPLORER ? (
<MenuItem
data-segment-explorer
label="Segment Explorer"
label="Route Info"
value={<ChevronRight />}
onClick={() => setOpen(OVERLAYS.SegmentExplorer)}
index={isTurbopack ? 3 : 4}
......
......@@ -3,6 +3,11 @@ import { css } from '../../utils/css'
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 { useSegmentTree, type SegmentTrieNode } from '../../segment-explorer'
import { cx } from '../../utils/cx'
const isFileNode = (node: SegmentTrieNode) => {
return !!node.value?.type && !!node.value?.pagePath
}
function PageSegmentTree({ tree }: { tree: SegmentTrieNode }) {
return (
......@@ -10,33 +15,21 @@ function PageSegmentTree({ tree }: { tree: SegmentTrieNode }) {
className="segment-explorer-content"
data-nextjs-devtool-segment-explorer
>
<PageSegmentTreeLayerPresentation
node={tree}
level={0}
segment=""
parentSegment=""
/>
<PageSegmentTreeLayerPresentation node={tree} level={0} segment="" />
</div>
)
}
function PageSegmentTreeLayerPresentation({
segment,
parentSegment,
node,
level,
}: {
segment: string
parentSegment: string
node: SegmentTrieNode
level: number
}) {
const pagePath = node.value?.pagePath || ''
const nodeName = node.value?.type
const isFile = !!nodeName
const segments = pagePath.split('/') || []
const fileName = isFile ? segments.pop() || '' : ''
const childrenKeys = Object.keys(node.children)
const sortedChildrenKeys = childrenKeys.sort((a, b) => {
......@@ -47,31 +40,61 @@ function PageSegmentTreeLayerPresentation({
if (aHasExt && !bHasExt) return -1
if (!aHasExt && bHasExt) return 1
// Otherwise sort alphabetically
return a.localeCompare(b)
})
// check if it has file children
const hasFileChildren = sortedChildrenKeys.some((key) => {
const childNode = node.children[key]
return !!childNode?.value?.type
// If it's file, sort by order: layout > template > page
if (aHasExt && bHasExt) {
const aType = node.children[a]?.value?.type
const bType = node.children[b]?.value?.type
if (aType === 'layout' && bType !== 'layout') return -1
if (aType !== 'layout' && bType === 'layout') return 1
if (aType === 'template' && bType !== 'template') return -1
if (aType !== 'template' && bType === 'template') return 1
// If both are the same type, sort by pagePath
const aFilePath = node.children[a]?.value?.pagePath || ''
const bFilePath = node.children[b]?.value?.pagePath || ''
return aFilePath.localeCompare(bFilePath)
}
return a.localeCompare(b)
})
// If it's the 1st level and contains a file, use 'app' as the folder name
const folderName = level === 1 && isFile ? 'app' : parentSegment
const folderName = level === 0 && !segment ? 'app' : segment
const folderChildrenKeys: string[] = []
const filesChildrenKeys: string[] = []
for (const childKey of sortedChildrenKeys) {
const childNode = node.children[childKey]
if (!childNode) continue
// If it's a file node, add it to filesChildrenKeys
if (isFileNode(childNode)) {
filesChildrenKeys.push(childKey)
continue
}
// Otherwise, it's a folder node, add it to folderChildrenKeys
folderChildrenKeys.push(childKey)
}
const hasFilesChildren = filesChildrenKeys.length > 0
return (
<>
{isFile ? (
{hasFilesChildren && (
<div
className="segment-explorer-item"
data-nextjs-devtool-segment-explorer-segment={segment}
data-nextjs-devtool-segment-explorer-segment={segment + '-' + level}
>
<div
className="segment-explorer-item-row"
style={{
// If it's children levels, show indents if there's any file at that level.
// Otherwise it's empty folder, no need to show indents.
...(level > 0 && isFile && { paddingLeft: `${level * 8}px` }),
...{ paddingLeft: `${(level + 1) * 8}px` },
}}
>
<div className="segment-explorer-line">
......@@ -84,27 +107,54 @@ function PageSegmentTreeLayerPresentation({
<small>{'/'}</small>
</span>
)}
<span className="segment-explorer-filename--name">
{fileName}
</span>
{/* display all the file segments in this level */}
{filesChildrenKeys.length > 0 && (
<span className="segment-explorer-files">
{filesChildrenKeys.map((fileChildSegment) => {
const childNode = node.children[fileChildSegment]
if (!childNode || !childNode.value) {
return null
}
const fileName =
childNode.value.pagePath.split('/').pop() || ''
return (
<span
key={fileChildSegment}
className={cx(
'segment-explorer-file-label',
`segment-explorer-file-label--${childNode.value.type}`
)}
>
{fileName}
</span>
)
})}
</span>
)}
</div>
</div>
</div>
</div>
</div>
) : null}
{sortedChildrenKeys.map((childSegment) => {
)}
{folderChildrenKeys.map((childSegment) => {
const child = node.children[childSegment]
if (!child) {
return null
}
// If it's an folder segment without any files under it,
// merge it with the segment in the next level.
const nextSegment = hasFilesChildren
? childSegment
: segment + ' / ' + childSegment
return (
<PageSegmentTreeLayerPresentation
key={childSegment}
segment={childSegment}
parentSegment={segment}
segment={nextSegment}
node={child}
level={hasFileChildren ? level + 1 : level}
level={hasFilesChildren ? level + 1 : level}
/>
)
})}
......@@ -118,7 +168,7 @@ export function SegmentsExplorer(
const tree = useSegmentTree()
return (
<DevToolsInfo title="Segment Explorer" {...props}>
<DevToolsInfo title="Route Info" {...props}>
<PageSegmentTree tree={tree} />
</DevToolsInfo>
)
......@@ -133,28 +183,36 @@ export const DEV_TOOLS_INFO_RENDER_FILES_STYLES = css`
.segment-explorer-item {
margin: 4px 0;
border-radius: 6px;
}
.segment-explorer-item:nth-child(odd) {
background-color: var(--color-gray-100);
background-color: var(--color-background-200);
}
.segment-explorer-item-row {
display: flex;
align-items: center;
padding: 4px 24px;
border-radius: 6px;
padding-top: 10px;
padding-bottom: 10px;
padding-right: 4px;
}
.segment-explorer-children--intended {
padding-left: 16px;
}
.segment-explorer-filename {
display: inline-flex;
}
.segment-explorer-filename--path {
margin-right: 8px;
}
.segment-explorer-filename--path small {
display: inline-block;
width: 0;
opacity: 0;
}
.segment-explorer-filename--name {
color: var(--color-gray-800);
......@@ -169,7 +227,26 @@ export const DEV_TOOLS_INFO_RENDER_FILES_STYLES = css`
color: var(--color-gray-1000);
}
[data-nextjs-devtool-segment-explorer-level='odd'] {
background-color: var(--color-gray-100);
.segment-explorer-files {
display: inline-flex;
gap: 8px;
}
.segment-explorer-file-label {
padding: 2px 6px;
border-radius: 16px;
font-size: var(--size-12);
line-height: 16px;
font-weight: 500;
user-select: none;
}
.segment-explorer-file-label--layout,
.segment-explorer-file-label--template {
background-color: var(--color-gray-300);
color: var(--color-gray-1000);
}
.segment-explorer-file-label--page {
background-color: var(--color-blue-300);
color: var(--color-blue-800);
}
`
......@@ -118,7 +118,7 @@ async function createComponentTreeInternal({
query,
} = ctx
const { page, layoutOrPagePath, segment, modules, parallelRoutes } =
const { page, conventionPath, segment, modules, parallelRoutes } =
parseLoaderTree(tree)
const {
......@@ -140,7 +140,7 @@ async function createComponentTreeInternal({
const layerAssets = getLayerAssets({
preloadCallbacks,
ctx,
layoutOrPagePath,
layoutOrPagePath: conventionPath,
injectedCSS: injectedCSSWithCurrentLayout,
injectedJS: injectedJSWithCurrentLayout,
injectedFontPreloadTags: injectedFontPreloadTagsWithCurrentLayout,
......@@ -421,6 +421,13 @@ async function createComponentTreeInternal({
</>
) : undefined
const dir = ctx.renderOpts.dir || ''
const isSegmentViewEnabled =
process.env.NODE_ENV === 'development' &&
ctx.renderOpts.devtoolSegmentExplorer
const nodeName = modType ?? 'page'
// TODO: Combine this `map` traversal with the loop below that turns the array
// into an object.
const parallelRouteMap = await Promise.all(
......@@ -491,7 +498,7 @@ async function createComponentTreeInternal({
// to provide more helpful debug information during development mode.
const parsedTree = parseLoaderTree(parallelRoute)
if (
parsedTree.layoutOrPagePath?.endsWith(PARALLEL_ROUTE_DEFAULT_PATH)
parsedTree.conventionPath?.endsWith(PARALLEL_ROUTE_DEFAULT_PATH)
) {
missingSlots.add(parallelRouteKey)
}
......@@ -526,7 +533,17 @@ async function createComponentTreeInternal({
childCacheNodeSeedData = seedData
}
// This is turned back into an object below.
const templateNode = (
<Template>
<RenderFromTemplateContext />
</Template>
)
const templateFilePath = getConventionPathByType(
parallelRoute,
dir,
'template'
)
return [
parallelRouteKey,
<LayoutRouter
......@@ -536,9 +553,14 @@ async function createComponentTreeInternal({
errorStyles={errorStyles}
errorScripts={errorScripts}
template={
<Template>
<RenderFromTemplateContext />
</Template>
// Only render SegmentViewNode when there's an actual template
isSegmentViewEnabled && templateFilePath ? (
<SegmentViewNode type="template" pagePath={templateFilePath}>
{templateNode}
</SegmentViewNode>
) : (
templateNode
)
}
templateStyles={templateStyles}
templateScripts={templateScripts}
......@@ -628,25 +650,18 @@ async function createComponentTreeInternal({
)
}
const dir = ctx.renderOpts.dir || process.cwd()
const isSegmentViewEnabled =
process.env.NODE_ENV === 'development' &&
ctx.renderOpts.devtoolSegmentExplorer
const nodeName = modType ?? 'page'
if (isPage) {
const PageComponent = isSegmentViewEnabled
? (pageProps: any) => {
return (
<SegmentViewNode
type={nodeName}
pagePath={normalizePageOrLayoutFilePath(dir, layoutOrPagePath)}
>
<Component {...pageProps} />
</SegmentViewNode>
)
}
: Component
const pageFilePath = getConventionPathByType(tree, dir, 'page')
const PageComponent =
isSegmentViewEnabled && pageFilePath
? (pageProps: any) => {
return (
<SegmentViewNode type={nodeName} pagePath={pageFilePath}>
<Component {...pageProps} />
</SegmentViewNode>
)
}
: Component
// Assign searchParams to props if this is a page
let pageElement: React.ReactNode
......@@ -727,18 +742,17 @@ async function createComponentTreeInternal({
isPossiblyPartialResponse,
]
} else {
const SegmentComponent = isSegmentViewEnabled
? (segmentProps: any) => {
return (
<SegmentViewNode
type={nodeName}
pagePath={normalizePageOrLayoutFilePath(dir, layoutOrPagePath)}
>
<Component {...segmentProps} />
</SegmentViewNode>
)
}
: Component
const layoutFilePath = getConventionPathByType(tree, dir, 'layout')
const SegmentComponent =
isSegmentViewEnabled && layoutFilePath
? (segmentProps: any) => {
return (
<SegmentViewNode type={nodeName} pagePath={layoutFilePath}>
<Component {...segmentProps} />
</SegmentViewNode>
)
}
: Component
const isRootLayoutWithChildrenSlotAndAtLeastOneMoreSlot =
rootLayoutAtThisLevel &&
......@@ -1010,19 +1024,35 @@ function getRootParamsImpl(
}
}
function normalizePageOrLayoutFilePath(
function normalizeConventionFilePath(
projectDir: string,
layoutOrPagePath: string | undefined
conventionPath: string | undefined
) {
const relativePath = (layoutOrPagePath || '')
const cwd = process.env.NEXT_RUNTIME === 'edge' ? '' : process.cwd()
const relativePath = (conventionPath || '')
// remove turbopack [project] prefix
.replace(/^\[project\][\\/]/, '')
// remove the process.cwd() prefix
.replace(process.cwd() + '/', '')
// remove the project root from the path
.replace(projectDir, '')
// remove cwd prefix
.replace(cwd, '')
// remove /(src/)?app/ dir prefix
.replace(/^[\\/](src[\\/])?app[\\/]/, '')
.replace(/^([\\/])*(src[\\/])?app[\\/]/, '')
return relativePath
}
function getConventionPathByType(
tree: LoaderTree,
dir: string,
conventionType: 'layout' | 'template' | 'page'
) {
const modules = tree[2]
const conventionPath_ = modules[conventionType]
? modules[conventionType][1]
: undefined
if (conventionPath_) {
return normalizeConventionFilePath(dir, conventionPath_)
}
return undefined
}
......@@ -9,13 +9,14 @@ export function parseLoaderTree(tree: LoaderTree) {
// segments in the route, so we should use the default page
page = segment === DEFAULT_SEGMENT_KEY ? modules.defaultPage : page
const layoutOrPagePath = layout?.[1] || template?.[1] || page?.[1]
const conventionPath = layout?.[1] || template?.[1] || page?.[1]
return {
page,
segment,
modules,
layoutOrPagePath,
/* it can be either layout / template / page */
conventionPath,
parallelRoutes,
}
}
export default function Layout({ children }) {
return (
<div>
<h2>Layout</h2>
<div>{children}</div>
</div>
)
}
export default function Page() {
return (
<div>
<h4>Page title</h4>
<p>Page</p>
</div>
)
}
export default function Template({ children }) {
return (
<div>
<h3>Template</h3>
<div>{children}</div>
</div>
)
}
export default function Layout({ children }) {
return (
<div>
<h3>Nested Layout</h3>
<h2>Nested Layout</h2>
<div className="nested-children">{children}</div>
</div>
)
......
export default function Template({ children }) {
return (
<div>
<h3>Template</h3>
<div id="nested-children">{children}</div>
</div>
)
}
export default function Layout({ children }) {
return (
<div>
<h3>Nested Layout</h3>
<h1>Nested Layout</h1>
<div className="nested-children">{children}</div>
</div>
)
......
......@@ -26,32 +26,44 @@ describe('segment-explorer', () => {
it('should render the segment explorer for parallel routes', async () => {
const browser = await next.browser('/parallel-routes')
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"app/layout.tsx
parallel-routes/layout.tsx
parallel-routes/page.tsx
@bar/layout.tsx
@bar/page.tsx
@foo/layout.tsx
@foo/page.tsx"
"app/
layout.tsx
parallel-routes/
layout.tsx
page.tsx
@bar/
layout.tsx
page.tsx
@foo/
layout.tsx
page.tsx"
`)
})
it('should render the segment explorer for nested routes', async () => {
const browser = await next.browser('/blog/~/grid')
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"app/layout.tsx
(v2)/layout.tsx
(team)/layout.tsx
(overview)/layout.tsx
grid/page.tsx"
"app/
layout.tsx
(v2)/
layout.tsx
blog / (team)/
layout.tsx
template.tsx
~ / (overview)/
layout.tsx
grid/
page.tsx"
`)
})
it('should cleanup on soft navigation', async () => {
const browser = await next.browser('/soft-navigation/a')
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"app/layout.tsx
a/page.tsx"
"app/
layout.tsx
soft-navigation / a/
page.tsx"
`)
await browser.elementByCss('[href="/soft-navigation/b"]').click()
......@@ -60,8 +72,22 @@ describe('segment-explorer', () => {
})
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"app/layout.tsx
b/page.tsx"
"app/
layout.tsx
soft-navigation / b/
page.tsx"
`)
})
it('should handle show file segments in order', async () => {
const browser = await next.browser('/file-segments')
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"app/
layout.tsx
(all) / file-segments/
layout.tsx
template.tsx
page.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