Skip to content

Commit

Permalink
cleanup magic segment strings (#59552)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
ztanner committed Dec 13, 2023
1 parent f518fd8 commit 855139b
Show file tree
Hide file tree
Showing 11 changed files with 40 additions and 16 deletions.
14 changes: 10 additions & 4 deletions packages/next/src/build/webpack/loaders/next-app-loader.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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)}],
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
7 changes: 5 additions & 2 deletions packages/next/src/client/components/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'

/**
Expand All @@ -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
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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] ?? {}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import type { Segment } from '../../../server/app-render/types'
import { PAGE_SEGMENT_KEY } from '../../../shared/lib/constants'

export function createRouterCacheKey(
segment: Segment,
withoutSearchParameters: boolean = false
) {
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
}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
}
Expand Down
3 changes: 2 additions & 1 deletion packages/next/src/server/app-render/parse-loader-tree.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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'
Expand Down
3 changes: 2 additions & 1 deletion packages/next/src/server/dev/on-demand-entry-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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]

Expand Down
3 changes: 2 additions & 1 deletion packages/next/src/server/lib/app-dir-module.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions packages/next/src/shared/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down

0 comments on commit 855139b

Please sign in to comment.