Unverified Commit 33477b7e authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[segment-explorer] display the builtin conventions (#80961)

Track built-in conventions in segment explorer. The default `global-not-found.js` and `global-error.js` will be displayed.
Their style will be different to the others, we'll follow up in the later PRs.

Closes NEXT-4576
parent c1f4e3e7
...@@ -931,6 +931,14 @@ async fn directory_tree_to_loader_tree_internal( ...@@ -931,6 +931,14 @@ async fn directory_tree_to_loader_tree_internal(
.await?, .await?,
); );
} }
if modules.global_error.is_none() {
modules.global_error = Some(
get_next_package(app_dir)
.join(rcstr!("dist/client/components/builtin/global-error.js"))
.to_resolved()
.await?,
);
}
} }
let mut tree = AppPageLoaderTree { let mut tree = AppPageLoaderTree {
......
...@@ -159,8 +159,8 @@ async function createTreeCodeFromPath( ...@@ -159,8 +159,8 @@ async function createTreeCodeFromPath(
const pages: string[] = [] const pages: string[] = []
let rootLayout: string | undefined let rootLayout: string | undefined
let globalError: string | undefined let globalError: string = defaultGlobalErrorPath
let globalNotFound: string | undefined let globalNotFound: string = defaultNotFoundPath
async function resolveAdjacentParallelSegments( async function resolveAdjacentParallelSegments(
segmentPath: string segmentPath: string
...@@ -303,6 +303,33 @@ async function createTreeCodeFromPath( ...@@ -303,6 +303,33 @@ async function createTreeCodeFromPath(
}) })
) )
// Only resolve global-* convention files at the root layer
if (isRootLayer) {
const resolvedGlobalErrorPath = await resolver(
`${appDirPrefix}/${GLOBAL_ERROR_FILE_TYPE}`
)
if (resolvedGlobalErrorPath) {
globalError = resolvedGlobalErrorPath
}
// Add global-error to root layer's filePaths, so that it's always available,
// by default it's the built-in global-error.js
filePaths.push([GLOBAL_ERROR_FILE_TYPE, globalError])
// TODO(global-not-found): remove this flag assertion condition
// once global-not-found is stable
if (isGlobalNotFoundEnabled) {
const resolvedGlobalNotFoundPath = await resolver(
`${appDirPrefix}/${GLOBAL_NOT_FOUND_FILE_TYPE}`
)
if (resolvedGlobalNotFoundPath) {
globalNotFound = resolvedGlobalNotFoundPath
}
// Add global-not-found to root layer's filePaths, so that it's always available,
// by default it's the built-in global-not-found.js
filePaths.push([GLOBAL_NOT_FOUND_FILE_TYPE, globalNotFound])
}
}
let definedFilePaths = filePaths.filter( let definedFilePaths = filePaths.filter(
([, filePath]) => filePath !== undefined ([, filePath]) => filePath !== undefined
) as [ValueOf<typeof FILE_TYPES>, string][] ) as [ValueOf<typeof FILE_TYPES>, string][]
...@@ -361,25 +388,6 @@ async function createTreeCodeFromPath( ...@@ -361,25 +388,6 @@ async function createTreeCodeFromPath(
} }
} }
if (!globalError) {
const resolvedGlobalErrorPath = await resolver(
`${appDirPrefix}/${GLOBAL_ERROR_FILE_TYPE}`
)
if (resolvedGlobalErrorPath) {
globalError = resolvedGlobalErrorPath
}
}
// TODO(global-not-found): remove this flag assertion condition
// once global-not-found is stable
if (isGlobalNotFoundEnabled && !globalNotFound) {
const resolvedGlobalNotFoundPath = await resolver(
`${appDirPrefix}/${GLOBAL_NOT_FOUND_FILE_TYPE}`
)
if (resolvedGlobalNotFoundPath) {
globalNotFound = resolvedGlobalNotFoundPath
}
}
let parallelSegmentKey = Array.isArray(parallelSegment) let parallelSegmentKey = Array.isArray(parallelSegment)
? parallelSegment[0] ? parallelSegment[0]
: parallelSegment : parallelSegment
...@@ -523,8 +531,8 @@ async function createTreeCodeFromPath( ...@@ -523,8 +531,8 @@ async function createTreeCodeFromPath(
treeCode: `${treeCode}.children;`, treeCode: `${treeCode}.children;`,
pages: `${JSON.stringify(pages)};`, pages: `${JSON.stringify(pages)};`,
rootLayout, rootLayout,
globalError: globalError ?? defaultGlobalErrorPath, globalError,
globalNotFound: globalNotFound ?? defaultNotFoundPath, globalNotFound,
} }
} }
......
...@@ -97,11 +97,7 @@ import { getRequiredScripts } from './required-scripts' ...@@ -97,11 +97,7 @@ import { getRequiredScripts } from './required-scripts'
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix' import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
import { makeGetServerInsertedHTML } from './make-get-server-inserted-html' import { makeGetServerInsertedHTML } from './make-get-server-inserted-html'
import { walkTreeWithFlightRouterState } from './walk-tree-with-flight-router-state' import { walkTreeWithFlightRouterState } from './walk-tree-with-flight-router-state'
import { import { createComponentTree, getRootParams } from './create-component-tree'
createComponentTree,
getRootParams,
normalizeConventionFilePath,
} from './create-component-tree'
import { getAssetQueryString } from './get-asset-query-string' import { getAssetQueryString } from './get-asset-query-string'
import { import {
getServerModuleMap, getServerModuleMap,
...@@ -200,6 +196,7 @@ import { ...@@ -200,6 +196,7 @@ import {
} from './module-loading/track-module-loading.external' } from './module-loading/track-module-loading.external'
import { isReactLargeShellError } from './react-large-shell-error' import { isReactLargeShellError } from './react-large-shell-error'
import type { GlobalErrorComponent } from '../../client/components/builtin/global-error' import type { GlobalErrorComponent } from '../../client/components/builtin/global-error'
import { normalizeConventionFilePath } from './segment-explorer-path'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug] // [slug] / [[slug]] / [...slug]
......
...@@ -26,6 +26,7 @@ import type { ...@@ -26,6 +26,7 @@ import type {
UseCachePageComponentProps, UseCachePageComponentProps,
} from '../use-cache/use-cache-wrapper' } from '../use-cache/use-cache-wrapper'
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment' import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
import { getConventionPathByType } from './segment-explorer-path'
/** /**
* Use the provided loader tree to create the React Component tree. * Use the provided loader tree to create the React Component tree.
...@@ -1102,53 +1103,3 @@ async function createBoundaryConventionElement({ ...@@ -1102,53 +1103,3 @@ async function createBoundaryConventionElement({
return wrappedElement return wrappedElement
} }
export function normalizeConventionFilePath(
projectDir: string,
conventionPath: string | undefined
) {
const cwd = process.env.NEXT_RUNTIME === 'edge' ? '' : process.cwd()
const nextInternalPrefixRegex =
/^(.*[\\/])?next[\\/]dist[\\/]client[\\/]components[\\/]builtin[\\/]/
let relativePath = (conventionPath || '')
// remove turbopack [project] prefix
.replace(/^\[project\][\\/]/, '')
// remove the project root from the path
.replace(projectDir, '')
// remove cwd prefix
.replace(cwd, '')
// remove /(src/)?app/ dir prefix
.replace(/^([\\/])*(src[\\/])?app[\\/]/, '')
// If it's internal file only keep the filename, strip nextjs internal prefix
if (nextInternalPrefixRegex.test(relativePath)) {
relativePath = relativePath.replace(nextInternalPrefixRegex, '')
}
return relativePath
}
function getConventionPathByType(
tree: LoaderTree,
dir: string,
conventionType:
| 'layout'
| 'template'
| 'page'
| 'not-found'
| 'error'
| 'loading'
| 'forbidden'
| 'unauthorized'
| 'defaultPage'
) {
const modules = tree[2]
const conventionPath = modules[conventionType]
? modules[conventionType][1]
: undefined
if (conventionPath) {
return normalizeConventionFilePath(dir, conventionPath)
}
return undefined
}
import type { LoaderTree } from '../lib/app-dir-module'
export function normalizeConventionFilePath(
projectDir: string,
conventionPath: string | undefined
) {
const cwd = process.env.NEXT_RUNTIME === 'edge' ? '' : process.cwd()
const nextInternalPrefixRegex =
/^(.*[\\/])?next[\\/]dist[\\/]client[\\/]components[\\/]builtin[\\/]/
let relativePath = (conventionPath || '')
// remove turbopack [project] prefix
.replace(/^\[project\][\\/]/, '')
// remove the project root from the path
.replace(projectDir, '')
// remove cwd prefix
.replace(cwd, '')
// remove /(src/)?app/ dir prefix
.replace(/^([\\/])*(src[\\/])?app[\\/]/, '')
// If it's internal file only keep the filename, strip nextjs internal prefix
if (nextInternalPrefixRegex.test(relativePath)) {
relativePath = relativePath.replace(nextInternalPrefixRegex, '')
}
return relativePath
}
export function getConventionPathByType(
tree: LoaderTree,
dir: string,
conventionType:
| 'layout'
| 'template'
| 'page'
| 'not-found'
| 'error'
| 'loading'
| 'forbidden'
| 'unauthorized'
| 'defaultPage'
) {
const modules = tree[2]
const conventionPath = modules[conventionType]
? modules[conventionType][1]
: undefined
if (conventionPath) {
return normalizeConventionFilePath(dir, conventionPath)
}
return undefined
}
...@@ -3,11 +3,9 @@ ...@@ -3,11 +3,9 @@
export default function GlobalError() { export default function GlobalError() {
return ( return (
<html> <html>
<head>
<title>Global Error</title>
</head>
<body> <body>
<h1>Global Error</h1> <h1>Global Error</h1>
<p>This is a global error</p>
</body> </body>
</html> </html>
) )
......
export default function GlobalNotFound() {
return (
<html>
<body>
<h1>404</h1>
<p>Not Found Page</p>
</body>
</html>
)
}
export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
const hrefs = [
'/parallel-routes',
'/blog/~/grid',
'/soft-navigation/a',
'/file-segments',
'/parallel-default',
'/parallel-default/subroute',
]
export default function Page() {
return (
<div>
<h1>Segment Explorer</h1>
<p>Examples</p>
<div>
{hrefs.map((href) => (
<div key={href}>
<Link href={href}>{href}</Link>
</div>
))}
</div>
</div>
)
}
.error-title {
color: red;
font-size: 24px;
font-weight: bold;
}
'use client'
import './error.css'
export default function CustomError() {
return <h2 className="error-title">Custom Error</h2>
}
'use client'
export default function Page() {
if (typeof window !== 'undefined') {
throw new Error('Error on client')
}
return <p>page</p>
}
'use client'
export default function Page() {
if (typeof window !== 'undefined') {
throw new Error('Error on client')
}
return <p>page</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
devtoolSegmentExplorer: true,
authInterrupts: true,
globalNotFound: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { openDevToolsIndicatorPopover } from 'next-test-utils'
import { Playwright } from 'next-webdriver'
async function getSegmentExplorerContent(browser: Playwright) {
// open the devtool button
await openDevToolsIndicatorPopover(browser)
// open the segment explorer
await browser.elementByCss('[data-segment-explorer]').click()
// wait for the segment explorer to be visible
await browser.waitForElementByCss('[data-nextjs-devtool-segment-explorer]')
const content = await browser.elementByCss(
'[data-nextjs-devtool-segment-explorer]'
)
return content.text()
}
describe('segment-explorer - globals', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should show global-error segment', async () => {
const browser = await next.browser('/runtime-error')
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"app/
global-error.tsx"
`)
})
it('should display parallel routes default page when present', async () => {
const browser = await next.browser('/404-not-found')
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"app/
global-not-found.tsx"
`)
})
})
import { ReactNode } from 'react' export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function Root({ children }: { children: ReactNode }) { export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return ( return (
<html> <html lang="en">
<body>{children}</body> <body>{children}</body>
</html> </html>
) )
......
...@@ -128,7 +128,7 @@ describe('segment-explorer', () => { ...@@ -128,7 +128,7 @@ describe('segment-explorer', () => {
const browser = await next.browser('/runtime-error') const browser = await next.browser('/runtime-error')
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(` expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"app/ "app/
global-error.tsx" global-error.js"
`) `)
}) })
......
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