cleanup magic segment strings (#59552)

This uses the existing PAGE_SEGMENT constant in places where we had
`__PAGE__` and introduces a similar constant for `__DEFAULT__`.
<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Closes NEXT-1860
This commit is contained in:
Zack Tanner 2023-12-13 07:03:40 -08:00 committed by GitHub
parent f518fd81b3
commit 855139b239
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 40 additions and 16 deletions

View file

@ -1,5 +1,9 @@
import type webpack from 'next/dist/compiled/webpack/webpack'
import type { ValueOf } from '../../../shared/lib/constants'
import {
DEFAULT_SEGMENT_KEY,
PAGE_SEGMENT_KEY,
type ValueOf,
} from '../../../shared/lib/constants'
import type { ModuleReference, CollectedMetadata } from './metadata/types'
import path from 'path'
@ -274,7 +278,9 @@ async function createTreeCodeFromPath(
if (resolvedPagePath) pages.push(resolvedPagePath)
// Use '' for segment as it's the page. There can't be a segment called '' so this is the safest way to add it.
props[normalizeParallelKey(parallelKey)] = `['__PAGE__', {}, {
props[
normalizeParallelKey(parallelKey)
] = `['${PAGE_SEGMENT_KEY}', {}, {
page: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(
resolvedPagePath
)}), ${JSON.stringify(resolvedPagePath)}],
@ -379,7 +385,7 @@ async function createTreeCodeFromPath(
definedFilePaths.find(([type]) => type === 'not-found')?.[1] ??
defaultNotFoundPath
subtreeCode = `{
children: ['__PAGE__', {}, {
children: ['${PAGE_SEGMENT_KEY}', {}, {
page: [
() => import(/* webpackMode: "eager" */ ${JSON.stringify(
notFoundPath
@ -422,7 +428,7 @@ async function createTreeCodeFromPath(
)) ?? 'next/dist/client/components/parallel-route-default'
props[normalizeParallelKey(adjacentParallelSegment)] = `[
'__DEFAULT__',
'${DEFAULT_SEGMENT_KEY}',
{},
{
defaultPage: [() => import(/* webpackMode: "eager" */ ${JSON.stringify(

View file

@ -12,6 +12,7 @@ import {
} from '../../shared/lib/hooks-client-context.shared-runtime'
import { clientHookInServerComponentError } from './client-hook-in-server-component-error'
import { getSegmentValue } from './router-reducer/reducers/get-segment-value'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/constants'
const INTERNAL_URLSEARCHPARAMS_INSTANCE = Symbol(
'internal for urlsearchparams readonly'
@ -141,7 +142,7 @@ function getSelectedParams(
const segment = parallelRoute[0]
const isDynamicParameter = Array.isArray(segment)
const segmentValue = isDynamicParameter ? segment[1] : segment
if (!segmentValue || segmentValue.startsWith('__PAGE__')) continue
if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) continue
// Ensure catchAll and optional catchall are turned into an array
const isCatchAll =
@ -203,7 +204,9 @@ function getSelectedLayoutSegmentPath(
const segment = node[0]
const segmentValue = getSegmentValue(segment)
if (!segmentValue || segmentValue.startsWith('__PAGE__')) return segmentPath
if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) {
return segmentPath
}
segmentPath.push(segmentValue)

View file

@ -2,6 +2,7 @@ import type {
FlightRouterState,
FlightSegmentPath,
} from '../../../server/app-render/types'
import { DEFAULT_SEGMENT_KEY } from '../../../shared/lib/constants'
import { matchSegment } from '../match-segments'
/**
@ -16,7 +17,10 @@ function applyPatch(
// if the applied patch segment is __DEFAULT__ then we can ignore it and return the initial tree
// this is because the __DEFAULT__ segment is used as a placeholder on navigation
if (patchSegment === '__DEFAULT__' && initialSegment !== '__DEFAULT__') {
if (
patchSegment === DEFAULT_SEGMENT_KEY &&
initialSegment !== DEFAULT_SEGMENT_KEY
) {
return initialTree
}

View file

@ -3,6 +3,10 @@ import type {
Segment,
} from '../../../server/app-render/types'
import { INTERCEPTION_ROUTE_MARKERS } from '../../../server/future/helpers/interception-routes'
import {
DEFAULT_SEGMENT_KEY,
PAGE_SEGMENT_KEY,
} from '../../../shared/lib/constants'
import { isGroupSegment } from '../../../shared/lib/segment'
import { matchSegment } from '../match-segments'
@ -39,12 +43,12 @@ export function extractPathFromFlightRouterState(
: flightRouterState[0]
if (
segment === '__DEFAULT__' ||
segment === DEFAULT_SEGMENT_KEY ||
INTERCEPTION_ROUTE_MARKERS.some((m) => segment.startsWith(m))
)
return undefined
if (segment.startsWith('__PAGE__')) return ''
if (segment.startsWith(PAGE_SEGMENT_KEY)) return ''
const segments = [segment]
const parallelRoutes = flightRouterState[1] ?? {}

View file

@ -1,4 +1,5 @@
import type { Segment } from '../../../server/app-render/types'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/constants'
export function createRouterCacheKey(
segment: Segment,
@ -6,7 +7,7 @@ export function createRouterCacheKey(
) {
return Array.isArray(segment)
? `${segment[0]}|${segment[1]}|${segment[2]}`.toLowerCase()
: withoutSearchParameters && segment.startsWith('__PAGE__')
? '__PAGE__'
: withoutSearchParameters && segment.startsWith(PAGE_SEGMENT_KEY)
? PAGE_SEGMENT_KEY
: segment
}

View file

@ -27,6 +27,7 @@ import {
import { prunePrefetchCache } from './prune-prefetch-cache'
import { prefetchQueue } from './prefetch-reducer'
import { createEmptyCacheNode } from '../../app-router'
import { DEFAULT_SEGMENT_KEY } from '../../../../shared/lib/constants'
export function handleExternalUrl(
state: ReadonlyReducerState,
@ -465,7 +466,7 @@ function navigateReducer_PPR(
// Filter out the __DEFAULT__ paths as they shouldn't be scrolled to in this case.
if (
scrollableSegmentPath[scrollableSegmentPath.length - 1] !==
'__DEFAULT__'
DEFAULT_SEGMENT_KEY
) {
scrollableSegments.push(scrollableSegmentPath)
}

View file

@ -1,3 +1,4 @@
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/constants'
import type { LoaderTree } from '../lib/app-dir-module'
export function parseLoaderTree(tree: LoaderTree) {
@ -6,7 +7,7 @@ export function parseLoaderTree(tree: LoaderTree) {
let { page } = components
// a __DEFAULT__ segment means that this route didn't match any of the
// segments in the route, so we should use the default page
page = segment === '__DEFAULT__' ? components.defaultPage : page
page = segment === DEFAULT_SEGMENT_KEY ? components.defaultPage : page
const layoutOrPagePath = layout?.[1] || page?.[1]

View file

@ -21,6 +21,7 @@ import type { CreateSegmentPath, AppRenderContext } from './app-render'
import { getLayerAssets } from './get-layer-assets'
import { hasLoadingComponentInTree } from './has-loading-component-in-tree'
import { createComponentTree } from './create-component-tree'
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/constants'
/**
* Use router state to decide at what common layout to render the page.
@ -236,7 +237,7 @@ export async function walkTreeWithFlightRouterState({
// we don't need to send over default routes in the flight data
// because they are always ignored by the client, unless it's a refetch
if (
item[0] === '__DEFAULT__' &&
item[0] === DEFAULT_SEGMENT_KEY &&
flightRouterState &&
!!flightRouterState[1][parallelRouteKey][0] &&
flightRouterState[1][parallelRouteKey][3] !== 'refetch'

View file

@ -33,6 +33,7 @@ import { PageNotFoundError, stringifyError } from '../../shared/lib/utils'
import {
COMPILER_INDEXES,
COMPILER_NAMES,
PAGE_SEGMENT_KEY,
RSC_MODULE_TYPES,
} from '../../shared/lib/constants'
import { HMR_ACTIONS_SENT_TO_BROWSER } from './hot-reloader-types'
@ -130,7 +131,7 @@ function getEntrypointsFromTree(
? convertDynamicParamTypeToSyntax(segment[2], segment[0])
: segment
const isPageSegment = currentSegment.startsWith('__PAGE__')
const isPageSegment = currentSegment.startsWith(PAGE_SEGMENT_KEY)
const currentPath = [...parentPath, isPageSegment ? '' : currentSegment]

View file

@ -1,4 +1,5 @@
import type { ComponentsType } from '../../build/webpack/loaders/next-app-loader'
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/constants'
/**
* LoaderTree is generated in next-app-loader.
@ -14,7 +15,7 @@ export async function getLayoutOrPageModule(loaderTree: LoaderTree) {
const isLayout = typeof layout !== 'undefined'
const isPage = typeof page !== 'undefined'
const isDefaultPage =
typeof defaultPage !== 'undefined' && loaderTree[0] === '__DEFAULT__'
typeof defaultPage !== 'undefined' && loaderTree[0] === DEFAULT_SEGMENT_KEY
let value = undefined
let modType: 'layout' | 'page' | undefined = undefined

View file

@ -98,6 +98,7 @@ export const EDGE_RUNTIME_WEBPACK = 'edge-runtime-webpack'
export const STATIC_PROPS_ID = '__N_SSG'
export const SERVER_PROPS_ID = '__N_SSP'
export const PAGE_SEGMENT_KEY = '__PAGE__'
export const DEFAULT_SEGMENT_KEY = '__DEFAULT__'
export const GOOGLE_FONT_PROVIDER = 'https://fonts.googleapis.com/'
export const OPTIMIZED_FONT_PROVIDERS = [
{ url: GOOGLE_FONT_PROVIDER, preconnect: 'https://fonts.gstatic.com' },