Skip to content

Commit

Permalink
Extract router utils to common functions (#37313)
Browse files Browse the repository at this point in the history
* Extract `detect-domain-locale` to a util file

* Remove `pathNoQueryHash` in favor of `parsePath`

* Remove `hasPathPrefix` in favor of `pathHasPrefix`

* Remove `addPathPrefix` in favor of an existing util

* Bugfix parsing pathname

* Refactor `addLocale`

* Extract `removeLocale`

* Extract `basePath` utils

* Dynamic imports for `getDomainLocale`
  • Loading branch information
javivelasco authored May 30, 2022
1 parent e7f5500 commit daab64c
Show file tree
Hide file tree
Showing 16 changed files with 182 additions and 171 deletions.
14 changes: 14 additions & 0 deletions packages/next/client/add-base-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { addPathPrefix } from '../shared/lib/router/utils/add-path-prefix'
import { normalizePathTrailingSlash } from './normalize-trailing-slash'

const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''

export function addBasePath(path: string, required?: boolean): string {
if (process.env.__NEXT_MANUAL_CLIENT_BASE_PATH) {
if (!required) {
return path
}
}

return normalizePathTrailingSlash(addPathPrefix(path, basePath))
}
11 changes: 11 additions & 0 deletions packages/next/client/add-locale.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { addLocale as Fn } from '../shared/lib/router/utils/add-locale'
import { normalizePathTrailingSlash } from './normalize-trailing-slash'

export const addLocale: typeof Fn = (path, ...args) => {
if (process.env.__NEXT_I18N_SUPPORT) {
return normalizePathTrailingSlash(
require('../shared/lib/router/utils/add-locale').addLocale(path, ...args)
)
}
return path
}
9 changes: 9 additions & 0 deletions packages/next/client/detect-domain-locale.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { detectDomainLocale as Fn } from '../shared/lib/i18n/detect-domain-locale'

export const detectDomainLocale: typeof Fn = (...args) => {
if (process.env.__NEXT_I18N_SUPPORT) {
return require('../shared/lib/i18n/detect-domain-locale').detectDomainLocale(
...args
)
}
}
30 changes: 30 additions & 0 deletions packages/next/client/get-domain-locale.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { DomainLocale } from '../server/config'
import type { normalizeLocalePath as NormalizeFn } from './normalize-locale-path'
import type { detectDomainLocale as DetectFn } from './detect-domain-locale'

const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''

export function getDomainLocale(
path: string,
locale?: string | false,
locales?: string[],
domainLocales?: DomainLocale[]
) {
if (process.env.__NEXT_I18N_SUPPORT) {
const normalizeLocalePath: typeof NormalizeFn =
require('./normalize-locale-path').normalizeLocalePath
const detectDomainLocale: typeof DetectFn =
require('./detect-domain-locale').detectDomainLocale

const target = locale || normalizeLocalePath(path, locales).detectedLocale
const domain = detectDomainLocale(domainLocales, undefined, target)
if (domain) {
const proto = `http${domain.http ? '' : 's'}://`
const finalLocale = target === domain.defaultLocale ? '' : `/${target}`
return `${proto}${domain.domain}${basePath}${finalLocale}${path}`
}
return false
} else {
return false
}
}
7 changes: 7 additions & 0 deletions packages/next/client/has-base-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { pathHasPrefix } from '../shared/lib/router/utils/path-has-prefix'

const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''

export function hasBasePath(path: string): boolean {
return pathHasPrefix(path, basePath)
}
6 changes: 3 additions & 3 deletions packages/next/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ import type Router from '../shared/lib/router/router'
import {
AppComponent,
AppProps,
delBasePath,
hasBasePath,
PrivateRouteInfo,
} from '../shared/lib/router/router'
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
Expand All @@ -35,6 +33,8 @@ import { getProperError } from '../lib/is-error'
import { RefreshContext } from './streaming/refresh'
import { ImageConfigContext } from '../shared/lib/image-config-context'
import { ImageConfigComplete } from '../shared/lib/image-config'
import { removeBasePath } from './remove-base-path'
import { hasBasePath } from './has-base-path'

const ReactDOM = process.env.__NEXT_REACT_ROOT
? require('react-dom/client')
Expand Down Expand Up @@ -206,7 +206,7 @@ export async function initialize(opts: { webpackHMR?: any } = {}): Promise<{

// make sure not to attempt stripping basePath for 404s
if (hasBasePath(asPath)) {
asPath = delBasePath(asPath)
asPath = removeBasePath(asPath)
}

if (process.env.__NEXT_I18N_SUPPORT) {
Expand Down
13 changes: 4 additions & 9 deletions packages/next/client/link.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import React from 'react'
import { UrlObject } from 'url'
import {
addBasePath,
addLocale,
getDomainLocale,
isLocalURL,
NextRouter,
PrefetchOptions,
resolveHref,
} from '../shared/lib/router/router'
import { addLocale } from './add-locale'
import { RouterContext } from '../shared/lib/router-context'
import { AppRouterContext } from '../shared/lib/app-router-context'
import { useIntersection } from './use-intersection'
import { getDomainLocale } from './get-domain-locale'
import { addBasePath } from './add-base-path'

type Url = string | UrlObject
type RequiredKeys<T> = {
Expand Down Expand Up @@ -422,12 +422,7 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
const localeDomain =
router &&
router.isLocaleDomain &&
getDomainLocale(
as,
curLocale,
router && router.locales,
router && router.domainLocales
)
getDomainLocale(as, curLocale, router.locales, router.domainLocales)

childProps.href =
localeDomain ||
Expand Down
11 changes: 11 additions & 0 deletions packages/next/client/normalize-locale-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { normalizeLocalePath as Fn } from '../shared/lib/i18n/normalize-locale-path'

export const normalizeLocalePath: typeof Fn = (pathname, locales) => {
if (process.env.__NEXT_I18N_SUPPORT) {
return require('../shared/lib/i18n/normalize-locale-path').normalizeLocalePath(
pathname,
locales
)
}
return { pathname, detectedLocale: undefined }
}
28 changes: 18 additions & 10 deletions packages/next/client/normalize-trailing-slash.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { parsePath } from '../shared/lib/router/utils/parse-path'

/**
* Normalizes the trailing slash of a path according to the `trailingSlash` option
* in `next.config.js`.
*/
export const normalizePathTrailingSlash = process.env.__NEXT_TRAILING_SLASH
? (path: string): string => {
if (/\.[^/]+\/?$/.test(path)) {
return removeTrailingSlash(path)
} else if (path.endsWith('/')) {
return path
} else {
return path + '/'
}
export const normalizePathTrailingSlash = (path: string) => {
if (!path.startsWith('/')) {
return path
}

const { pathname, query, hash } = parsePath(path)
if (process.env.__NEXT_TRAILING_SLASH) {
if (/\.[^/]+\/?$/.test(pathname)) {
return `${removeTrailingSlash(pathname)}${query}${hash}`
} else if (pathname.endsWith('/')) {
return `${pathname}${query}${hash}`
} else {
return `${pathname}/${query}${hash}`
}
: removeTrailingSlash
}

return `${removeTrailingSlash(pathname)}${query}${hash}`
}
8 changes: 3 additions & 5 deletions packages/next/client/page-loader.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import type { ComponentType } from 'react'
import type { RouteLoader } from './route-loader'
import {
addBasePath,
addLocale,
interpolateAs,
} from '../shared/lib/router/router'
import { addBasePath } from './add-base-path'
import { interpolateAs } from '../shared/lib/router/router'
import getAssetPathFromRoute from '../shared/lib/router/utils/get-asset-path-from-route'
import { addLocale } from './add-locale'
import { isDynamicRoute } from '../shared/lib/router/utils/is-dynamic'
import { parseRelativeUrl } from '../shared/lib/router/utils/parse-relative-url'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
Expand Down
15 changes: 15 additions & 0 deletions packages/next/client/remove-base-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { hasBasePath } from './has-base-path'

const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''

export function removeBasePath(path: string): string {
if (process.env.__NEXT_MANUAL_CLIENT_BASE_PATH) {
if (!hasBasePath(path)) {
return path
}
}

path = path.slice(basePath.length)
if (!path.startsWith('/')) path = `/${path}`
return path
}
18 changes: 18 additions & 0 deletions packages/next/client/remove-locale.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { parsePath } from '../shared/lib/router/utils/parse-path'

export function removeLocale(path: string, locale?: string) {
if (process.env.__NEXT_I18N_SUPPORT) {
const { pathname } = parsePath(path)
const pathLower = pathname.toLowerCase()
const localeLower = locale?.toLowerCase()

return locale &&
(pathLower.startsWith(`/${localeLower}/`) ||
pathLower === `/${localeLower}`)
? `${pathname.length === locale.length + 1 ? `/` : ``}${path.slice(
locale.length + 1
)}`
: path
}
return path
}
Loading

0 comments on commit daab64c

Please sign in to comment.