2019-03-13 15:56:20 +01:00
|
|
|
|
/* global __NEXT_DATA__ */
|
|
|
|
|
// tslint:disable:no-console
|
2019-05-29 13:57:26 +02:00
|
|
|
|
import { ParsedUrlQuery } from 'querystring'
|
|
|
|
|
import { ComponentType } from 'react'
|
2020-07-13 18:08:12 +02:00
|
|
|
|
import { UrlObject } from 'url'
|
2020-08-13 07:24:57 +02:00
|
|
|
|
import {
|
|
|
|
|
normalizePathTrailingSlash,
|
|
|
|
|
removePathTrailingSlash,
|
|
|
|
|
} from '../../../client/normalize-trailing-slash'
|
2020-08-26 18:34:53 +02:00
|
|
|
|
import { GoodPageCache, StyleSheetTuple } from '../../../client/page-loader'
|
2020-08-18 16:06:10 +02:00
|
|
|
|
import { denormalizePagePath } from '../../server/denormalize-page-path'
|
2019-05-29 13:57:26 +02:00
|
|
|
|
import mitt, { MittEmitter } from '../mitt'
|
2019-05-27 20:20:33 +02:00
|
|
|
|
import {
|
2019-05-29 13:57:26 +02:00
|
|
|
|
AppContextType,
|
|
|
|
|
formatWithValidation,
|
2020-08-13 07:24:57 +02:00
|
|
|
|
getLocationOrigin,
|
2019-05-29 13:57:26 +02:00
|
|
|
|
getURL,
|
|
|
|
|
loadGetInitialProps,
|
|
|
|
|
NextPageContext,
|
2020-01-04 21:53:33 +01:00
|
|
|
|
ST,
|
2019-05-29 13:57:26 +02:00
|
|
|
|
} from '../utils'
|
2019-11-11 04:24:53 +01:00
|
|
|
|
import { isDynamicRoute } from './utils/is-dynamic'
|
2020-08-13 07:24:57 +02:00
|
|
|
|
import { parseRelativeUrl } from './utils/parse-relative-url'
|
|
|
|
|
import { searchParamsToUrlQuery } from './utils/querystring'
|
2020-08-18 16:06:10 +02:00
|
|
|
|
import resolveRewrites from './utils/resolve-rewrites'
|
2019-05-31 00:44:27 +02:00
|
|
|
|
import { getRouteMatcher } from './utils/route-matcher'
|
2019-05-30 22:42:45 +02:00
|
|
|
|
import { getRouteRegex } from './utils/route-regex'
|
2020-09-02 18:23:26 +02:00
|
|
|
|
import escapePathDelimiters from './utils/escape-path-delimiters'
|
2019-03-23 23:00:46 +01:00
|
|
|
|
|
2020-08-01 20:13:03 +02:00
|
|
|
|
interface TransitionOptions {
|
|
|
|
|
shallow?: boolean
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface NextHistoryState {
|
|
|
|
|
url: string
|
|
|
|
|
as: string
|
|
|
|
|
options: TransitionOptions
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type HistoryState = null | { __N: false } | ({ __N: true } & NextHistoryState)
|
|
|
|
|
|
2020-04-15 01:12:02 +02:00
|
|
|
|
const basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''
|
2020-04-14 09:50:39 +02:00
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
function buildCancellationError() {
|
|
|
|
|
return Object.assign(new Error('Route Cancelled'), {
|
|
|
|
|
cancelled: true,
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-01 13:51:47 +02:00
|
|
|
|
export function hasBasePath(path: string): boolean {
|
|
|
|
|
return path === basePath || path.startsWith(basePath + '/')
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-14 09:50:39 +02:00
|
|
|
|
export function addBasePath(path: string): string {
|
2020-08-05 20:12:17 +02:00
|
|
|
|
// we only add the basepath on relative urls
|
|
|
|
|
return basePath && path.startsWith('/')
|
2020-07-16 01:53:31 +02:00
|
|
|
|
? path === '/'
|
|
|
|
|
? normalizePathTrailingSlash(basePath)
|
|
|
|
|
: basePath + path
|
|
|
|
|
: path
|
2020-04-14 09:50:39 +02:00
|
|
|
|
}
|
|
|
|
|
|
2020-04-26 17:14:39 +02:00
|
|
|
|
export function delBasePath(path: string): string {
|
2020-07-02 05:48:10 +02:00
|
|
|
|
return path.slice(basePath.length) || '/'
|
2019-03-23 23:00:46 +01:00
|
|
|
|
}
|
2019-03-13 15:56:20 +01:00
|
|
|
|
|
2020-08-05 20:12:17 +02:00
|
|
|
|
/**
|
|
|
|
|
* Detects whether a given url is routable by the Next.js router (browser only).
|
|
|
|
|
*/
|
|
|
|
|
export function isLocalURL(url: string): boolean {
|
|
|
|
|
if (url.startsWith('/')) return true
|
|
|
|
|
try {
|
|
|
|
|
// absolute urls can be local if they are on the same origin
|
|
|
|
|
const locationOrigin = getLocationOrigin()
|
|
|
|
|
const resolved = new URL(url, locationOrigin)
|
|
|
|
|
return resolved.origin === locationOrigin && hasBasePath(resolved.pathname)
|
|
|
|
|
} catch (_) {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-07-10 06:10:44 +02:00
|
|
|
|
type Url = UrlObject | string
|
|
|
|
|
|
2020-09-02 18:23:26 +02:00
|
|
|
|
export function interpolateAs(
|
|
|
|
|
route: string,
|
|
|
|
|
asPathname: string,
|
|
|
|
|
query: ParsedUrlQuery
|
|
|
|
|
) {
|
|
|
|
|
let interpolatedRoute = ''
|
|
|
|
|
|
|
|
|
|
const dynamicRegex = getRouteRegex(route)
|
|
|
|
|
const dynamicGroups = dynamicRegex.groups
|
|
|
|
|
const dynamicMatches =
|
|
|
|
|
// Try to match the dynamic route against the asPath
|
|
|
|
|
(asPathname !== route ? getRouteMatcher(dynamicRegex)(asPathname) : '') ||
|
|
|
|
|
// Fall back to reading the values from the href
|
|
|
|
|
// TODO: should this take priority; also need to change in the router.
|
|
|
|
|
query
|
|
|
|
|
|
|
|
|
|
interpolatedRoute = route
|
|
|
|
|
if (
|
|
|
|
|
!Object.keys(dynamicGroups).every((param) => {
|
|
|
|
|
let value = dynamicMatches[param] || ''
|
|
|
|
|
const { repeat, optional } = dynamicGroups[param]
|
|
|
|
|
|
|
|
|
|
// support single-level catch-all
|
|
|
|
|
// TODO: more robust handling for user-error (passing `/`)
|
|
|
|
|
let replaced = `[${repeat ? '...' : ''}${param}]`
|
|
|
|
|
if (optional) {
|
|
|
|
|
replaced = `${!value ? '/' : ''}[${replaced}]`
|
|
|
|
|
}
|
|
|
|
|
if (repeat && !Array.isArray(value)) value = [value]
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
(optional || param in dynamicMatches) &&
|
|
|
|
|
// Interpolate group into data URL if present
|
|
|
|
|
(interpolatedRoute =
|
|
|
|
|
interpolatedRoute!.replace(
|
|
|
|
|
replaced,
|
|
|
|
|
repeat
|
|
|
|
|
? (value as string[]).map(escapePathDelimiters).join('/')
|
|
|
|
|
: escapePathDelimiters(value as string)
|
|
|
|
|
) || '/')
|
|
|
|
|
)
|
|
|
|
|
})
|
|
|
|
|
) {
|
|
|
|
|
interpolatedRoute = '' // did not satisfy all requirements
|
|
|
|
|
|
|
|
|
|
// n.b. We ignore this error because we handle warning for this case in
|
|
|
|
|
// development in the `<Link>` component directly.
|
|
|
|
|
}
|
|
|
|
|
return interpolatedRoute
|
|
|
|
|
}
|
|
|
|
|
|
2020-07-13 18:08:12 +02:00
|
|
|
|
/**
|
|
|
|
|
* Resolves a given hyperlink with a certain router state (basePath not included).
|
|
|
|
|
* Preserves absolute urls.
|
|
|
|
|
*/
|
2020-09-02 18:23:26 +02:00
|
|
|
|
export function resolveHref(
|
|
|
|
|
currentPath: string,
|
|
|
|
|
href: Url,
|
|
|
|
|
resolveAs?: boolean
|
|
|
|
|
): string {
|
2020-07-13 18:08:12 +02:00
|
|
|
|
// we use a dummy base url for relative urls
|
|
|
|
|
const base = new URL(currentPath, 'http://n')
|
|
|
|
|
const urlAsString =
|
|
|
|
|
typeof href === 'string' ? href : formatWithValidation(href)
|
2020-08-05 20:12:17 +02:00
|
|
|
|
try {
|
|
|
|
|
const finalUrl = new URL(urlAsString, base)
|
|
|
|
|
finalUrl.pathname = normalizePathTrailingSlash(finalUrl.pathname)
|
2020-09-02 18:23:26 +02:00
|
|
|
|
let interpolatedAs = ''
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
isDynamicRoute(finalUrl.pathname) &&
|
|
|
|
|
finalUrl.searchParams &&
|
|
|
|
|
resolveAs
|
|
|
|
|
) {
|
|
|
|
|
const query = searchParamsToUrlQuery(finalUrl.searchParams)
|
|
|
|
|
|
|
|
|
|
interpolatedAs = interpolateAs(
|
|
|
|
|
finalUrl.pathname,
|
|
|
|
|
finalUrl.pathname,
|
|
|
|
|
query
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-05 20:12:17 +02:00
|
|
|
|
// if the origin didn't change, it means we received a relative href
|
2020-09-02 18:23:26 +02:00
|
|
|
|
const resolvedHref =
|
|
|
|
|
finalUrl.origin === base.origin
|
|
|
|
|
? finalUrl.href.slice(finalUrl.origin.length)
|
|
|
|
|
: finalUrl.href
|
|
|
|
|
|
|
|
|
|
return (resolveAs ? [resolvedHref, interpolatedAs] : resolvedHref) as string
|
2020-08-05 20:12:17 +02:00
|
|
|
|
} catch (_) {
|
2020-09-02 18:23:26 +02:00
|
|
|
|
return (resolveAs ? [urlAsString] : urlAsString) as string
|
2020-08-05 20:12:17 +02:00
|
|
|
|
}
|
2020-06-29 16:50:45 +02:00
|
|
|
|
}
|
|
|
|
|
|
2020-08-10 19:15:37 +02:00
|
|
|
|
const PAGE_LOAD_ERROR = Symbol('PAGE_LOAD_ERROR')
|
|
|
|
|
export function markLoadingError(err: Error): Error {
|
|
|
|
|
return Object.defineProperty(err, PAGE_LOAD_ERROR, {})
|
|
|
|
|
}
|
|
|
|
|
|
2020-07-13 18:08:12 +02:00
|
|
|
|
function prepareUrlAs(router: NextRouter, url: Url, as: Url) {
|
2020-06-08 17:59:50 +02:00
|
|
|
|
// If url and as provided as an object representation,
|
|
|
|
|
// we'll format them into the string version here.
|
|
|
|
|
return {
|
2020-07-13 18:08:12 +02:00
|
|
|
|
url: addBasePath(resolveHref(router.pathname, url)),
|
|
|
|
|
as: as ? addBasePath(resolveHref(router.pathname, as)) : as,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-04-26 09:37:57 +02:00
|
|
|
|
export type BaseRouter = {
|
2019-03-13 15:56:20 +01:00
|
|
|
|
route: string
|
|
|
|
|
pathname: string
|
2019-05-20 17:21:15 +02:00
|
|
|
|
query: ParsedUrlQuery
|
2019-05-29 13:57:26 +02:00
|
|
|
|
asPath: string
|
2020-04-14 09:50:39 +02:00
|
|
|
|
basePath: string
|
2019-03-13 15:56:20 +01:00
|
|
|
|
}
|
|
|
|
|
|
2019-07-11 19:35:39 +02:00
|
|
|
|
export type NextRouter = BaseRouter &
|
|
|
|
|
Pick<
|
|
|
|
|
Router,
|
|
|
|
|
| 'push'
|
|
|
|
|
| 'replace'
|
|
|
|
|
| 'reload'
|
|
|
|
|
| 'back'
|
|
|
|
|
| 'prefetch'
|
|
|
|
|
| 'beforePopState'
|
|
|
|
|
| 'events'
|
2020-02-15 19:01:10 +01:00
|
|
|
|
| 'isFallback'
|
2019-07-11 19:35:39 +02:00
|
|
|
|
>
|
|
|
|
|
|
2020-02-17 21:46:15 +01:00
|
|
|
|
export type PrefetchOptions = {
|
|
|
|
|
priority?: boolean
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-13 19:39:33 +02:00
|
|
|
|
export type PrivateRouteInfo = {
|
2019-05-29 13:57:26 +02:00
|
|
|
|
Component: ComponentType
|
2020-08-26 18:34:53 +02:00
|
|
|
|
styleSheets: StyleSheetTuple[]
|
2020-03-06 05:15:10 +01:00
|
|
|
|
__N_SSG?: boolean
|
|
|
|
|
__N_SSP?: boolean
|
2020-08-13 19:39:33 +02:00
|
|
|
|
props?: Record<string, any>
|
2019-03-13 15:56:20 +01:00
|
|
|
|
err?: Error
|
2019-05-29 13:57:26 +02:00
|
|
|
|
error?: any
|
2019-03-13 15:56:20 +01:00
|
|
|
|
}
|
|
|
|
|
|
2020-08-13 19:39:33 +02:00
|
|
|
|
export type AppProps = Pick<PrivateRouteInfo, 'Component' | 'err'> & {
|
|
|
|
|
router: Router
|
|
|
|
|
} & Record<string, any>
|
|
|
|
|
export type AppComponent = ComponentType<AppProps>
|
|
|
|
|
|
|
|
|
|
type Subscription = (data: PrivateRouteInfo, App: AppComponent) => Promise<void>
|
2017-05-14 02:25:57 +02:00
|
|
|
|
|
2020-08-01 20:13:03 +02:00
|
|
|
|
type BeforePopStateCallback = (state: NextHistoryState) => boolean
|
2016-10-06 01:52:50 +02:00
|
|
|
|
|
2019-06-05 20:15:42 +02:00
|
|
|
|
type ComponentLoadCancel = (() => void) | null
|
|
|
|
|
|
2020-02-17 22:16:19 +01:00
|
|
|
|
type HistoryMethod = 'replaceState' | 'pushState'
|
|
|
|
|
|
2020-07-06 16:27:45 +02:00
|
|
|
|
const manualScrollRestoration =
|
|
|
|
|
process.env.__NEXT_SCROLL_RESTORATION &&
|
|
|
|
|
typeof window !== 'undefined' &&
|
|
|
|
|
'scrollRestoration' in window.history
|
|
|
|
|
|
2020-07-19 06:02:01 +02:00
|
|
|
|
function fetchRetry(url: string, attempts: number): Promise<any> {
|
|
|
|
|
return fetch(url, {
|
|
|
|
|
// Cookies are required to be present for Next.js' SSG "Preview Mode".
|
|
|
|
|
// Cookies may also be required for `getServerSideProps`.
|
|
|
|
|
//
|
|
|
|
|
// > `fetch` won’t send cookies, unless you set the credentials init
|
|
|
|
|
// > option.
|
|
|
|
|
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
|
|
|
|
|
//
|
|
|
|
|
// > For maximum browser compatibility when it comes to sending &
|
|
|
|
|
// > receiving cookies, always supply the `credentials: 'same-origin'`
|
|
|
|
|
// > option instead of relying on the default.
|
|
|
|
|
// https://github.com/github/fetch#caveats
|
|
|
|
|
credentials: 'same-origin',
|
|
|
|
|
}).then((res) => {
|
|
|
|
|
if (!res.ok) {
|
|
|
|
|
if (attempts > 1 && res.status >= 500) {
|
|
|
|
|
return fetchRetry(url, attempts - 1)
|
2020-01-27 23:50:59 +01:00
|
|
|
|
}
|
2020-07-19 06:02:01 +02:00
|
|
|
|
throw new Error(`Failed to load static props`)
|
|
|
|
|
}
|
2020-02-13 05:06:41 +01:00
|
|
|
|
|
2020-07-19 06:02:01 +02:00
|
|
|
|
return res.json()
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function fetchNextData(dataHref: string, isServerRender: boolean) {
|
|
|
|
|
return fetchRetry(dataHref, isServerRender ? 3 : 1).catch((err: Error) => {
|
|
|
|
|
// We should only trigger a server-side transition if this was caused
|
|
|
|
|
// on a client-side transition. Otherwise, we'd get into an infinite
|
|
|
|
|
// loop.
|
|
|
|
|
if (!isServerRender) {
|
2020-08-10 19:15:37 +02:00
|
|
|
|
markLoadingError(err)
|
2020-07-19 06:02:01 +02:00
|
|
|
|
}
|
|
|
|
|
throw err
|
|
|
|
|
})
|
2020-01-27 23:50:59 +01:00
|
|
|
|
}
|
|
|
|
|
|
2019-04-26 09:37:57 +02:00
|
|
|
|
export default class Router implements BaseRouter {
|
2019-03-13 15:56:20 +01:00
|
|
|
|
route: string
|
|
|
|
|
pathname: string
|
2019-05-20 17:21:15 +02:00
|
|
|
|
query: ParsedUrlQuery
|
2019-03-13 15:56:20 +01:00
|
|
|
|
asPath: string
|
2020-04-14 09:50:39 +02:00
|
|
|
|
basePath: string
|
|
|
|
|
|
2019-05-23 21:31:22 +02:00
|
|
|
|
/**
|
|
|
|
|
* Map of all components loaded in `Router`
|
|
|
|
|
*/
|
2020-08-13 19:39:33 +02:00
|
|
|
|
components: { [pathname: string]: PrivateRouteInfo }
|
2019-12-30 23:57:06 +01:00
|
|
|
|
// Static Data Cache
|
|
|
|
|
sdc: { [asPath: string]: object } = {}
|
2019-06-05 20:15:42 +02:00
|
|
|
|
sub: Subscription
|
|
|
|
|
clc: ComponentLoadCancel
|
2019-03-13 15:56:20 +01:00
|
|
|
|
pageLoader: any
|
2019-03-14 19:43:29 +01:00
|
|
|
|
_bps: BeforePopStateCallback | undefined
|
2019-07-11 19:35:39 +02:00
|
|
|
|
events: MittEmitter
|
2020-08-13 19:39:33 +02:00
|
|
|
|
_wrapApp: (App: AppComponent) => any
|
2019-11-12 22:37:47 +01:00
|
|
|
|
isSsr: boolean
|
2020-02-15 19:01:10 +01:00
|
|
|
|
isFallback: boolean
|
2020-07-20 22:03:49 +02:00
|
|
|
|
_inFlightRoute?: string
|
2020-08-22 23:51:14 +02:00
|
|
|
|
_shallow?: boolean
|
2019-03-13 15:56:20 +01:00
|
|
|
|
|
|
|
|
|
static events: MittEmitter = mitt()
|
|
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
|
constructor(
|
|
|
|
|
pathname: string,
|
|
|
|
|
query: ParsedUrlQuery,
|
|
|
|
|
as: string,
|
|
|
|
|
{
|
|
|
|
|
initialProps,
|
|
|
|
|
pageLoader,
|
|
|
|
|
App,
|
2019-07-30 20:00:19 +02:00
|
|
|
|
wrapApp,
|
2019-05-29 13:57:26 +02:00
|
|
|
|
Component,
|
2020-08-17 23:20:05 +02:00
|
|
|
|
initialStyleSheets,
|
2019-05-29 13:57:26 +02:00
|
|
|
|
err,
|
2019-06-05 20:15:42 +02:00
|
|
|
|
subscription,
|
2020-02-15 19:01:10 +01:00
|
|
|
|
isFallback,
|
2019-05-29 13:57:26 +02:00
|
|
|
|
}: {
|
2019-06-05 20:15:42 +02:00
|
|
|
|
subscription: Subscription
|
2019-05-29 13:57:26 +02:00
|
|
|
|
initialProps: any
|
|
|
|
|
pageLoader: any
|
|
|
|
|
Component: ComponentType
|
2020-08-26 18:34:53 +02:00
|
|
|
|
initialStyleSheets: StyleSheetTuple[]
|
2020-08-13 19:39:33 +02:00
|
|
|
|
App: AppComponent
|
|
|
|
|
wrapApp: (App: AppComponent) => any
|
2019-05-29 13:57:26 +02:00
|
|
|
|
err?: Error
|
2020-02-15 19:01:10 +01:00
|
|
|
|
isFallback: boolean
|
2019-05-29 13:57:26 +02:00
|
|
|
|
}
|
|
|
|
|
) {
|
2016-10-08 07:12:51 +02:00
|
|
|
|
// represents the current component key
|
2020-07-02 05:48:10 +02:00
|
|
|
|
this.route = removePathTrailingSlash(pathname)
|
2016-10-06 01:52:50 +02:00
|
|
|
|
|
|
|
|
|
// set up the component cache (by route keys)
|
2017-04-18 06:18:43 +02:00
|
|
|
|
this.components = {}
|
|
|
|
|
// We should not keep the cache, if there's an error
|
|
|
|
|
// Otherwise, this cause issues when when going back and
|
|
|
|
|
// come again to the errored page.
|
2019-01-31 21:45:36 +01:00
|
|
|
|
if (pathname !== '/_error') {
|
2020-03-06 05:15:10 +01:00
|
|
|
|
this.components[this.route] = {
|
|
|
|
|
Component,
|
2020-08-17 23:20:05 +02:00
|
|
|
|
styleSheets: initialStyleSheets,
|
2020-03-06 05:15:10 +01:00
|
|
|
|
props: initialProps,
|
|
|
|
|
err,
|
|
|
|
|
__N_SSG: initialProps && initialProps.__N_SSG,
|
|
|
|
|
__N_SSP: initialProps && initialProps.__N_SSP,
|
|
|
|
|
}
|
2017-04-18 06:18:43 +02:00
|
|
|
|
}
|
2017-02-15 20:29:42 +01:00
|
|
|
|
|
2020-08-17 23:20:05 +02:00
|
|
|
|
this.components['/_app'] = {
|
|
|
|
|
Component: App as ComponentType,
|
|
|
|
|
styleSheets: [
|
|
|
|
|
/* /_app does not need its stylesheets managed */
|
|
|
|
|
],
|
|
|
|
|
}
|
2018-05-31 11:47:29 +02:00
|
|
|
|
|
2018-07-31 21:04:14 +02:00
|
|
|
|
// Backwards compat for Router.router.events
|
|
|
|
|
// TODO: Should be remove the following major version as it was never documented
|
|
|
|
|
this.events = Router.events
|
2017-03-13 05:34:30 +01:00
|
|
|
|
|
2017-04-18 06:18:43 +02:00
|
|
|
|
this.pageLoader = pageLoader
|
2016-12-16 21:33:08 +01:00
|
|
|
|
this.pathname = pathname
|
|
|
|
|
this.query = query
|
2019-09-16 18:15:18 +02:00
|
|
|
|
// if auto prerendered and dynamic route wait to update asPath
|
|
|
|
|
// until after mount to prevent hydration mismatch
|
|
|
|
|
this.asPath =
|
|
|
|
|
// @ts-ignore this is temporarily global (attached to window)
|
2020-07-20 22:03:49 +02:00
|
|
|
|
isDynamicRoute(pathname) && __NEXT_DATA__.autoExport ? pathname : as
|
2020-04-14 09:50:39 +02:00
|
|
|
|
this.basePath = basePath
|
2019-06-05 20:15:42 +02:00
|
|
|
|
this.sub = subscription
|
|
|
|
|
this.clc = null
|
2019-07-30 20:00:19 +02:00
|
|
|
|
this._wrapApp = wrapApp
|
2019-11-12 22:37:47 +01:00
|
|
|
|
// make sure to ignore extra popState in safari on navigating
|
|
|
|
|
// back from external site
|
|
|
|
|
this.isSsr = true
|
2016-10-08 07:12:51 +02:00
|
|
|
|
|
2020-02-15 19:01:10 +01:00
|
|
|
|
this.isFallback = isFallback
|
|
|
|
|
|
2016-10-17 02:00:17 +02:00
|
|
|
|
if (typeof window !== 'undefined') {
|
2020-04-22 17:56:49 +02:00
|
|
|
|
// make sure "as" doesn't start with double slashes or else it can
|
|
|
|
|
// throw an error as it's considered invalid
|
|
|
|
|
if (as.substr(0, 2) !== '//') {
|
|
|
|
|
// in order for `e.state` to work on the `onpopstate` event
|
|
|
|
|
// we have to register the initial route upon initialization
|
|
|
|
|
this.changeState(
|
|
|
|
|
'replaceState',
|
2020-06-08 17:59:50 +02:00
|
|
|
|
formatWithValidation({ pathname: addBasePath(pathname), query }),
|
2020-07-02 11:11:57 +02:00
|
|
|
|
getURL()
|
2020-04-22 17:56:49 +02:00
|
|
|
|
)
|
|
|
|
|
}
|
2016-12-24 18:29:23 +01:00
|
|
|
|
|
2016-10-08 12:16:22 +02:00
|
|
|
|
window.addEventListener('popstate', this.onPopState)
|
2020-07-06 16:27:45 +02:00
|
|
|
|
|
|
|
|
|
// enable custom scroll restoration handling when available
|
|
|
|
|
// otherwise fallback to browser's default handling
|
|
|
|
|
if (process.env.__NEXT_SCROLL_RESTORATION) {
|
|
|
|
|
if (manualScrollRestoration) {
|
|
|
|
|
window.history.scrollRestoration = 'manual'
|
|
|
|
|
|
|
|
|
|
let scrollDebounceTimeout: undefined | NodeJS.Timeout
|
|
|
|
|
|
|
|
|
|
const debouncedScrollSave = () => {
|
|
|
|
|
if (scrollDebounceTimeout) clearTimeout(scrollDebounceTimeout)
|
|
|
|
|
|
|
|
|
|
scrollDebounceTimeout = setTimeout(() => {
|
|
|
|
|
const { url, as: curAs, options } = history.state
|
|
|
|
|
this.changeState(
|
|
|
|
|
'replaceState',
|
|
|
|
|
url,
|
|
|
|
|
curAs,
|
|
|
|
|
Object.assign({}, options, {
|
|
|
|
|
_N_X: window.scrollX,
|
|
|
|
|
_N_Y: window.scrollY,
|
|
|
|
|
})
|
|
|
|
|
)
|
|
|
|
|
}, 10)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
window.addEventListener('scroll', debouncedScrollSave)
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-10-08 12:16:22 +02:00
|
|
|
|
}
|
2016-10-06 01:52:50 +02:00
|
|
|
|
}
|
|
|
|
|
|
2019-03-14 19:43:29 +01:00
|
|
|
|
onPopState = (e: PopStateEvent): void => {
|
2020-08-01 20:13:03 +02:00
|
|
|
|
const state = e.state as HistoryState
|
|
|
|
|
|
|
|
|
|
if (!state) {
|
2017-02-05 09:58:44 +01:00
|
|
|
|
// We get state as undefined for two reasons.
|
|
|
|
|
// 1. With older safari (< 8) and older chrome (< 34)
|
|
|
|
|
// 2. When the URL changed with #
|
|
|
|
|
//
|
|
|
|
|
// In the both cases, we don't need to proceed and change the route.
|
|
|
|
|
// (as it's already changed)
|
|
|
|
|
// But we can simply replace the state with the new changes.
|
|
|
|
|
// Actually, for (1) we don't need to nothing. But it's hard to detect that event.
|
|
|
|
|
// So, doing the following for (1) does no harm.
|
|
|
|
|
const { pathname, query } = this
|
2019-05-29 13:57:26 +02:00
|
|
|
|
this.changeState(
|
|
|
|
|
'replaceState',
|
2020-06-08 17:59:50 +02:00
|
|
|
|
formatWithValidation({ pathname: addBasePath(pathname), query }),
|
2019-05-29 13:57:26 +02:00
|
|
|
|
getURL()
|
|
|
|
|
)
|
2017-01-25 17:58:26 +01:00
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-01 20:13:03 +02:00
|
|
|
|
if (!state.__N) {
|
2020-07-28 12:02:00 +02:00
|
|
|
|
return
|
|
|
|
|
}
|
2020-08-01 20:13:03 +02:00
|
|
|
|
|
|
|
|
|
const { url, as, options } = state
|
|
|
|
|
|
2020-07-13 18:08:12 +02:00
|
|
|
|
const { pathname } = parseRelativeUrl(url)
|
|
|
|
|
|
2019-04-09 23:58:44 +02:00
|
|
|
|
// Make sure we don't re-render on initial load,
|
|
|
|
|
// can be caused by navigating back from an external site
|
2020-07-13 18:08:12 +02:00
|
|
|
|
if (this.isSsr && as === this.asPath && pathname === this.pathname) {
|
2019-04-09 23:58:44 +02:00
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-31 16:21:51 +02:00
|
|
|
|
// If the downstream application returns falsy, return.
|
|
|
|
|
// They will then be responsible for handling the event.
|
2020-08-01 20:13:03 +02:00
|
|
|
|
if (this._bps && !this._bps(state)) {
|
2018-03-31 16:21:51 +02:00
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-22 23:51:14 +02:00
|
|
|
|
this.change(
|
|
|
|
|
'replaceState',
|
|
|
|
|
url,
|
|
|
|
|
as,
|
|
|
|
|
Object.assign({}, options, {
|
|
|
|
|
shallow: options.shallow && this._shallow,
|
|
|
|
|
})
|
|
|
|
|
)
|
2019-05-29 13:57:26 +02:00
|
|
|
|
}
|
2016-10-06 01:52:50 +02:00
|
|
|
|
|
2019-05-05 22:22:02 +02:00
|
|
|
|
reload(): void {
|
|
|
|
|
window.location.reload()
|
2016-10-24 09:22:15 +02:00
|
|
|
|
}
|
|
|
|
|
|
2019-05-23 21:31:22 +02:00
|
|
|
|
/**
|
|
|
|
|
* Go back in history
|
|
|
|
|
*/
|
2019-03-13 15:56:20 +01:00
|
|
|
|
back() {
|
2016-10-17 02:00:17 +02:00
|
|
|
|
window.history.back()
|
2016-10-06 01:52:50 +02:00
|
|
|
|
}
|
|
|
|
|
|
2019-05-23 21:31:22 +02:00
|
|
|
|
/**
|
|
|
|
|
* Performs a `pushState` with arguments
|
|
|
|
|
* @param url of the route
|
|
|
|
|
* @param as masks `url` for the browser
|
|
|
|
|
* @param options object you can define `shallow` and other options
|
|
|
|
|
*/
|
2020-08-01 20:13:03 +02:00
|
|
|
|
push(url: Url, as: Url = url, options: TransitionOptions = {}) {
|
2020-07-13 18:08:12 +02:00
|
|
|
|
;({ url, as } = prepareUrlAs(this, url, as))
|
2017-03-06 17:48:35 +01:00
|
|
|
|
return this.change('pushState', url, as, options)
|
2016-10-06 01:52:50 +02:00
|
|
|
|
}
|
|
|
|
|
|
2019-05-23 21:31:22 +02:00
|
|
|
|
/**
|
|
|
|
|
* Performs a `replaceState` with arguments
|
|
|
|
|
* @param url of the route
|
|
|
|
|
* @param as masks `url` for the browser
|
|
|
|
|
* @param options object you can define `shallow` and other options
|
|
|
|
|
*/
|
2020-08-01 20:13:03 +02:00
|
|
|
|
replace(url: Url, as: Url = url, options: TransitionOptions = {}) {
|
2020-07-13 18:08:12 +02:00
|
|
|
|
;({ url, as } = prepareUrlAs(this, url, as))
|
2017-03-06 17:48:35 +01:00
|
|
|
|
return this.change('replaceState', url, as, options)
|
2016-10-06 01:52:50 +02:00
|
|
|
|
}
|
|
|
|
|
|
2020-07-20 22:03:49 +02:00
|
|
|
|
async change(
|
2020-02-17 22:16:19 +01:00
|
|
|
|
method: HistoryMethod,
|
2020-06-08 17:59:50 +02:00
|
|
|
|
url: string,
|
|
|
|
|
as: string,
|
2020-08-01 20:13:03 +02:00
|
|
|
|
options: TransitionOptions
|
2020-02-17 22:16:19 +01:00
|
|
|
|
): Promise<boolean> {
|
2020-08-05 20:12:17 +02:00
|
|
|
|
if (!isLocalURL(url)) {
|
|
|
|
|
window.location.href = url
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-01 20:13:03 +02:00
|
|
|
|
if (!(options as any)._h) {
|
2020-07-20 22:03:49 +02:00
|
|
|
|
this.isSsr = false
|
|
|
|
|
}
|
|
|
|
|
// marking route changes as a navigation start entry
|
|
|
|
|
if (ST) {
|
|
|
|
|
performance.mark('routeChange')
|
|
|
|
|
}
|
2019-07-16 01:07:04 +02:00
|
|
|
|
|
2020-07-20 22:03:49 +02:00
|
|
|
|
if (this._inFlightRoute) {
|
|
|
|
|
this.abortComponentLoad(this._inFlightRoute)
|
|
|
|
|
}
|
2020-07-13 18:08:12 +02:00
|
|
|
|
|
2020-08-01 13:51:47 +02:00
|
|
|
|
const cleanedAs = hasBasePath(as) ? delBasePath(as) : as
|
2020-07-20 22:03:49 +02:00
|
|
|
|
this._inFlightRoute = as
|
|
|
|
|
|
|
|
|
|
// If the url change is only related to a hash change
|
|
|
|
|
// We should not proceed. We should only change the state.
|
|
|
|
|
|
|
|
|
|
// WARNING: `_h` is an internal option for handing Next.js client-side
|
|
|
|
|
// hydration. Your app should _never_ use this property. It may change at
|
|
|
|
|
// any time without notice.
|
2020-08-01 20:13:03 +02:00
|
|
|
|
if (!(options as any)._h && this.onlyAHashChange(cleanedAs)) {
|
2020-07-20 22:03:49 +02:00
|
|
|
|
this.asPath = cleanedAs
|
|
|
|
|
Router.events.emit('hashChangeStart', as)
|
2020-08-13 14:39:36 +02:00
|
|
|
|
// TODO: do we need the resolved href when only a hash change?
|
2020-07-20 22:03:49 +02:00
|
|
|
|
this.changeState(method, url, as, options)
|
|
|
|
|
this.scrollToHash(cleanedAs)
|
2020-08-07 00:04:47 +02:00
|
|
|
|
this.notify(this.components[this.route])
|
2020-07-20 22:03:49 +02:00
|
|
|
|
Router.events.emit('hashChangeComplete', as)
|
|
|
|
|
return true
|
|
|
|
|
}
|
2020-07-13 18:08:12 +02:00
|
|
|
|
|
2020-08-13 14:39:36 +02:00
|
|
|
|
// The build manifest needs to be loaded before auto-static dynamic pages
|
|
|
|
|
// get their query parameters to allow ensuring they can be parsed properly
|
|
|
|
|
// when rewritten to
|
|
|
|
|
const pages = await this.pageLoader.getPageList()
|
|
|
|
|
const { __rewrites: rewrites } = await this.pageLoader.promisedBuildManifest
|
|
|
|
|
|
2020-08-28 04:49:40 +02:00
|
|
|
|
let parsed = parseRelativeUrl(url)
|
2020-06-08 17:59:50 +02:00
|
|
|
|
|
2020-09-03 20:26:52 +02:00
|
|
|
|
let { pathname, query } = parsed
|
2020-08-13 14:39:36 +02:00
|
|
|
|
|
|
|
|
|
parsed = this._resolveHref(parsed, pages) as typeof parsed
|
|
|
|
|
|
|
|
|
|
if (parsed.pathname !== pathname) {
|
|
|
|
|
pathname = parsed.pathname
|
|
|
|
|
url = formatWithValidation(parsed)
|
|
|
|
|
}
|
|
|
|
|
|
2020-07-20 22:03:49 +02:00
|
|
|
|
// url and as should always be prefixed with basePath by this
|
|
|
|
|
// point by either next/link or router.push/replace so strip the
|
|
|
|
|
// basePath from the pathname to match the pages dir 1-to-1
|
|
|
|
|
pathname = pathname
|
|
|
|
|
? removePathTrailingSlash(delBasePath(pathname))
|
|
|
|
|
: pathname
|
2016-12-30 20:55:00 +01:00
|
|
|
|
|
2020-07-20 22:03:49 +02:00
|
|
|
|
// If asked to change the current URL we should reload the current page
|
|
|
|
|
// (not location.reload() but reload getInitialProps and other Next.js stuffs)
|
|
|
|
|
// We also need to set the method = replaceState always
|
|
|
|
|
// as this should not go into the history (That's how browsers work)
|
|
|
|
|
// We should compare the new asPath to the current asPath, not the url
|
|
|
|
|
if (!this.urlIsNew(cleanedAs)) {
|
|
|
|
|
method = 'replaceState'
|
|
|
|
|
}
|
2016-10-08 07:12:51 +02:00
|
|
|
|
|
2020-07-20 22:03:49 +02:00
|
|
|
|
const route = removePathTrailingSlash(pathname)
|
|
|
|
|
const { shallow = false } = options
|
2020-01-20 23:47:52 +01:00
|
|
|
|
|
2020-08-13 14:39:36 +02:00
|
|
|
|
// we need to resolve the as value using rewrites for dynamic SSG
|
|
|
|
|
// pages to allow building the data URL correctly
|
|
|
|
|
let resolvedAs = as
|
|
|
|
|
|
|
|
|
|
if (process.env.__NEXT_HAS_REWRITES) {
|
2020-08-22 07:15:45 +02:00
|
|
|
|
resolvedAs = resolveRewrites(
|
|
|
|
|
as,
|
|
|
|
|
pages,
|
|
|
|
|
basePath,
|
|
|
|
|
rewrites,
|
|
|
|
|
query,
|
|
|
|
|
(p: string) => this._resolveHref({ pathname: p }, pages).pathname!
|
|
|
|
|
)
|
2020-08-13 14:39:36 +02:00
|
|
|
|
}
|
|
|
|
|
resolvedAs = delBasePath(resolvedAs)
|
|
|
|
|
|
2020-07-20 22:03:49 +02:00
|
|
|
|
if (isDynamicRoute(route)) {
|
2020-08-13 14:39:36 +02:00
|
|
|
|
const { pathname: asPathname } = parseRelativeUrl(resolvedAs)
|
2020-07-20 22:03:49 +02:00
|
|
|
|
const routeRegex = getRouteRegex(route)
|
|
|
|
|
const routeMatch = getRouteMatcher(routeRegex)(asPathname)
|
|
|
|
|
if (!routeMatch) {
|
|
|
|
|
const missingParams = Object.keys(routeRegex.groups).filter(
|
|
|
|
|
(param) => !query[param]
|
|
|
|
|
)
|
2020-01-20 23:47:52 +01:00
|
|
|
|
|
2020-07-20 22:03:49 +02:00
|
|
|
|
if (missingParams.length > 0) {
|
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
|
|
|
console.warn(
|
|
|
|
|
`Mismatching \`as\` and \`href\` failed to manually provide ` +
|
|
|
|
|
`the params: ${missingParams.join(
|
|
|
|
|
', '
|
|
|
|
|
)} in the \`href\`'s \`query\``
|
2020-01-20 23:47:52 +01:00
|
|
|
|
)
|
2019-10-11 11:49:18 +02:00
|
|
|
|
}
|
2020-07-20 22:03:49 +02:00
|
|
|
|
|
|
|
|
|
throw new Error(
|
|
|
|
|
`The provided \`as\` value (${asPathname}) is incompatible with the \`href\` value (${route}). ` +
|
|
|
|
|
`Read more: https://err.sh/vercel/next.js/incompatible-href-as`
|
|
|
|
|
)
|
2019-05-27 20:20:33 +02:00
|
|
|
|
}
|
2020-09-02 18:23:26 +02:00
|
|
|
|
} else if (route === asPathname) {
|
|
|
|
|
as = interpolateAs(route, asPathname, query)
|
2020-07-20 22:03:49 +02:00
|
|
|
|
} else {
|
|
|
|
|
// Merge params into `query`, overwriting any specified in search
|
|
|
|
|
Object.assign(query, routeMatch)
|
2019-05-27 20:20:33 +02:00
|
|
|
|
}
|
2020-07-20 22:03:49 +02:00
|
|
|
|
}
|
2019-05-27 20:20:33 +02:00
|
|
|
|
|
2020-07-20 22:03:49 +02:00
|
|
|
|
Router.events.emit('routeChangeStart', as)
|
2017-03-06 17:48:35 +01:00
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
try {
|
|
|
|
|
const routeInfo = await this.getRouteInfo(
|
|
|
|
|
route,
|
|
|
|
|
pathname,
|
|
|
|
|
query,
|
|
|
|
|
as,
|
|
|
|
|
shallow
|
|
|
|
|
)
|
2020-08-22 13:47:21 +02:00
|
|
|
|
let { error } = routeInfo
|
2016-11-03 11:15:03 +01:00
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
Router.events.emit('beforeHistoryChange', as)
|
|
|
|
|
this.changeState(method, url, as, options)
|
2019-07-03 02:42:41 +02:00
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
|
|
|
const appComp: any = this.components['/_app'].Component
|
|
|
|
|
;(window as any).next.isPrerendered =
|
|
|
|
|
appComp.getInitialProps === appComp.origGetInitialProps &&
|
|
|
|
|
!(routeInfo.Component as any).getInitialProps
|
|
|
|
|
}
|
2020-02-07 14:09:06 +01:00
|
|
|
|
|
2020-08-22 13:47:21 +02:00
|
|
|
|
await this.set(route, pathname!, query, cleanedAs, routeInfo).catch(
|
|
|
|
|
(e) => {
|
|
|
|
|
if (e.cancelled) error = error || e
|
|
|
|
|
else throw e
|
|
|
|
|
}
|
|
|
|
|
)
|
2020-02-07 14:09:06 +01:00
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
if (error) {
|
|
|
|
|
Router.events.emit('routeChangeError', error, cleanedAs)
|
|
|
|
|
throw error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (process.env.__NEXT_SCROLL_RESTORATION) {
|
|
|
|
|
if (manualScrollRestoration && '_N_X' in options) {
|
2020-08-01 20:13:03 +02:00
|
|
|
|
window.scrollTo((options as any)._N_X, (options as any)._N_Y)
|
2020-07-20 22:03:49 +02:00
|
|
|
|
}
|
2020-07-21 19:33:11 +02:00
|
|
|
|
}
|
|
|
|
|
Router.events.emit('routeChangeComplete', as)
|
2020-07-20 22:03:49 +02:00
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
return true
|
|
|
|
|
} catch (err) {
|
|
|
|
|
if (err.cancelled) {
|
|
|
|
|
return false
|
2020-07-20 22:03:49 +02:00
|
|
|
|
}
|
2020-07-21 19:33:11 +02:00
|
|
|
|
throw err
|
|
|
|
|
}
|
2017-02-15 19:27:41 +01:00
|
|
|
|
}
|
2016-12-30 20:55:00 +01:00
|
|
|
|
|
2020-02-17 22:16:19 +01:00
|
|
|
|
changeState(
|
|
|
|
|
method: HistoryMethod,
|
|
|
|
|
url: string,
|
|
|
|
|
as: string,
|
2020-08-01 20:13:03 +02:00
|
|
|
|
options: TransitionOptions = {}
|
2020-02-17 22:16:19 +01:00
|
|
|
|
): void {
|
2018-09-27 21:10:53 +02:00
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
|
|
|
if (typeof window.history === 'undefined') {
|
|
|
|
|
console.error(`Warning: window.history is not available.`)
|
|
|
|
|
return
|
|
|
|
|
}
|
2020-02-17 22:16:19 +01:00
|
|
|
|
|
2018-09-27 21:10:53 +02:00
|
|
|
|
if (typeof window.history[method] === 'undefined') {
|
|
|
|
|
console.error(`Warning: window.history.${method} is not available`)
|
|
|
|
|
return
|
|
|
|
|
}
|
2018-02-25 15:19:38 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (method !== 'pushState' || getURL() !== as) {
|
2020-08-22 23:51:14 +02:00
|
|
|
|
this._shallow = options.shallow
|
2019-10-30 03:50:16 +01:00
|
|
|
|
window.history[method](
|
|
|
|
|
{
|
|
|
|
|
url,
|
|
|
|
|
as,
|
2019-11-12 22:37:47 +01:00
|
|
|
|
options,
|
2020-07-28 12:02:00 +02:00
|
|
|
|
__N: true,
|
2020-08-01 20:13:03 +02:00
|
|
|
|
} as HistoryState,
|
2020-02-17 22:16:19 +01:00
|
|
|
|
// Most browsers currently ignores this parameter, although they may use it in the future.
|
|
|
|
|
// Passing the empty string here should be safe against future changes to the method.
|
|
|
|
|
// https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState
|
|
|
|
|
'',
|
2019-10-30 03:50:16 +01:00
|
|
|
|
as
|
|
|
|
|
)
|
2016-12-30 20:55:00 +01:00
|
|
|
|
}
|
2016-10-06 01:52:50 +02:00
|
|
|
|
}
|
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
async handleRouteInfoError(
|
|
|
|
|
err: Error & { code: any; cancelled: boolean },
|
2019-05-29 13:57:26 +02:00
|
|
|
|
pathname: string,
|
2020-08-01 20:13:03 +02:00
|
|
|
|
query: ParsedUrlQuery,
|
2019-05-29 13:57:26 +02:00
|
|
|
|
as: string,
|
2020-07-21 19:33:11 +02:00
|
|
|
|
loadErrorFail?: boolean
|
2020-08-13 19:39:33 +02:00
|
|
|
|
): Promise<PrivateRouteInfo> {
|
2020-07-21 19:33:11 +02:00
|
|
|
|
if (err.cancelled) {
|
|
|
|
|
// bubble up cancellation errors
|
|
|
|
|
throw err
|
|
|
|
|
}
|
2020-02-20 22:25:41 +01:00
|
|
|
|
|
2020-08-10 19:15:37 +02:00
|
|
|
|
if (PAGE_LOAD_ERROR in err || loadErrorFail) {
|
2020-07-21 19:33:11 +02:00
|
|
|
|
Router.events.emit('routeChangeError', err, as)
|
2020-02-20 22:25:41 +01:00
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
// If we can't load the page it could be one of following reasons
|
|
|
|
|
// 1. Page doesn't exists
|
|
|
|
|
// 2. Page does exist in a different zone
|
|
|
|
|
// 3. Internal error while loading the page
|
|
|
|
|
|
|
|
|
|
// So, doing a hard reload is the proper way to deal with this.
|
|
|
|
|
window.location.href = as
|
|
|
|
|
|
|
|
|
|
// Changing the URL doesn't block executing the current code path.
|
|
|
|
|
// So let's throw a cancellation error stop the routing logic.
|
|
|
|
|
throw buildCancellationError()
|
2020-02-20 22:25:41 +01:00
|
|
|
|
}
|
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
try {
|
2020-08-17 23:20:05 +02:00
|
|
|
|
const { page: Component, styleSheets } = await this.fetchComponent(
|
|
|
|
|
'/_error'
|
|
|
|
|
)
|
|
|
|
|
const routeInfo: PrivateRouteInfo = {
|
|
|
|
|
Component,
|
|
|
|
|
styleSheets,
|
|
|
|
|
err,
|
|
|
|
|
error: err,
|
|
|
|
|
}
|
2020-07-21 19:33:11 +02:00
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
routeInfo.props = await this.getInitialProps(Component, {
|
|
|
|
|
err,
|
|
|
|
|
pathname,
|
|
|
|
|
query,
|
|
|
|
|
} as any)
|
|
|
|
|
} catch (gipErr) {
|
|
|
|
|
console.error('Error in error page `getInitialProps`: ', gipErr)
|
|
|
|
|
routeInfo.props = {}
|
2017-02-21 00:48:17 +01:00
|
|
|
|
}
|
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
return routeInfo
|
|
|
|
|
} catch (routeInfoErr) {
|
|
|
|
|
return this.handleRouteInfoError(routeInfoErr, pathname, query, as, true)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async getRouteInfo(
|
|
|
|
|
route: string,
|
|
|
|
|
pathname: string,
|
|
|
|
|
query: any,
|
|
|
|
|
as: string,
|
|
|
|
|
shallow: boolean = false
|
2020-08-13 19:39:33 +02:00
|
|
|
|
): Promise<PrivateRouteInfo> {
|
2020-07-21 19:33:11 +02:00
|
|
|
|
try {
|
|
|
|
|
const cachedRouteInfo = this.components[route]
|
|
|
|
|
|
|
|
|
|
if (shallow && cachedRouteInfo && this.route === route) {
|
|
|
|
|
return cachedRouteInfo
|
|
|
|
|
}
|
2017-12-06 00:35:30 +01:00
|
|
|
|
|
2020-08-13 19:39:33 +02:00
|
|
|
|
const routeInfo: PrivateRouteInfo = cachedRouteInfo
|
2020-07-21 19:33:11 +02:00
|
|
|
|
? cachedRouteInfo
|
2020-08-13 07:24:57 +02:00
|
|
|
|
: await this.fetchComponent(route).then((res) => ({
|
|
|
|
|
Component: res.page,
|
2020-08-17 23:20:05 +02:00
|
|
|
|
styleSheets: res.styleSheets,
|
2020-08-13 07:24:57 +02:00
|
|
|
|
__N_SSG: res.mod.__N_SSG,
|
|
|
|
|
__N_SSP: res.mod.__N_SSP,
|
|
|
|
|
}))
|
2020-07-21 19:33:11 +02:00
|
|
|
|
|
|
|
|
|
const { Component, __N_SSG, __N_SSP } = routeInfo
|
2020-06-29 17:14:45 +02:00
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
|
|
|
const { isValidElementType } = require('react-is')
|
|
|
|
|
if (!isValidElementType(Component)) {
|
|
|
|
|
throw new Error(
|
|
|
|
|
`The default export is not a React Component in page: "${pathname}"`
|
2020-06-29 17:14:45 +02:00
|
|
|
|
)
|
|
|
|
|
}
|
2020-07-21 19:33:11 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let dataHref: string | undefined
|
2020-06-29 17:14:45 +02:00
|
|
|
|
|
2020-07-21 19:33:11 +02:00
|
|
|
|
if (__N_SSG || __N_SSP) {
|
|
|
|
|
dataHref = this.pageLoader.getDataHref(
|
|
|
|
|
formatWithValidation({ pathname, query }),
|
2020-08-17 17:25:36 +02:00
|
|
|
|
delBasePath(as),
|
2020-03-06 05:15:10 +01:00
|
|
|
|
__N_SSG
|
2020-07-21 19:33:11 +02:00
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-13 19:39:33 +02:00
|
|
|
|
const props = await this._getData<PrivateRouteInfo>(() =>
|
2020-07-21 19:33:11 +02:00
|
|
|
|
__N_SSG
|
|
|
|
|
? this._getStaticData(dataHref!)
|
|
|
|
|
: __N_SSP
|
|
|
|
|
? this._getServerData(dataHref!)
|
|
|
|
|
: this.getInitialProps(
|
|
|
|
|
Component,
|
|
|
|
|
// we provide AppTree later so this needs to be `any`
|
|
|
|
|
{
|
|
|
|
|
pathname,
|
|
|
|
|
query,
|
|
|
|
|
asPath: as,
|
|
|
|
|
} as any
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
routeInfo.props = props
|
|
|
|
|
this.components[route] = routeInfo
|
|
|
|
|
return routeInfo
|
|
|
|
|
} catch (err) {
|
|
|
|
|
return this.handleRouteInfoError(err, pathname, query, as)
|
|
|
|
|
}
|
2016-12-31 02:15:22 +01:00
|
|
|
|
}
|
|
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
|
set(
|
|
|
|
|
route: string,
|
|
|
|
|
pathname: string,
|
2020-08-01 20:13:03 +02:00
|
|
|
|
query: ParsedUrlQuery,
|
2019-05-29 13:57:26 +02:00
|
|
|
|
as: string,
|
2020-08-13 19:39:33 +02:00
|
|
|
|
data: PrivateRouteInfo
|
2020-05-23 23:54:11 +02:00
|
|
|
|
): Promise<void> {
|
2020-02-15 19:01:10 +01:00
|
|
|
|
this.isFallback = false
|
|
|
|
|
|
2017-03-06 17:48:35 +01:00
|
|
|
|
this.route = route
|
2016-12-30 20:55:00 +01:00
|
|
|
|
this.pathname = pathname
|
|
|
|
|
this.query = query
|
2017-05-03 18:40:09 +02:00
|
|
|
|
this.asPath = as
|
2020-05-23 23:54:11 +02:00
|
|
|
|
return this.notify(data)
|
2016-10-06 01:52:50 +02:00
|
|
|
|
}
|
|
|
|
|
|
2019-05-23 21:31:22 +02:00
|
|
|
|
/**
|
|
|
|
|
* Callback to execute before replacing router state
|
|
|
|
|
* @param cb callback to be executed
|
|
|
|
|
*/
|
2019-03-13 15:56:20 +01:00
|
|
|
|
beforePopState(cb: BeforePopStateCallback) {
|
2019-03-14 19:43:29 +01:00
|
|
|
|
this._bps = cb
|
2018-03-31 16:21:51 +02:00
|
|
|
|
}
|
|
|
|
|
|
2019-03-13 15:56:20 +01:00
|
|
|
|
onlyAHashChange(as: string): boolean {
|
2017-05-03 18:40:09 +02:00
|
|
|
|
if (!this.asPath) return false
|
2019-05-29 13:57:26 +02:00
|
|
|
|
const [oldUrlNoHash, oldHash] = this.asPath.split('#')
|
|
|
|
|
const [newUrlNoHash, newHash] = as.split('#')
|
2017-02-28 18:31:17 +01:00
|
|
|
|
|
2018-06-28 20:56:18 +02:00
|
|
|
|
// Makes sure we scroll to the provided hash if the url/hash are the same
|
2019-05-29 13:57:26 +02:00
|
|
|
|
if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) {
|
2018-06-28 20:56:18 +02:00
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
2017-02-28 18:31:17 +01:00
|
|
|
|
// If the urls are change, there's more than a hash change
|
|
|
|
|
if (oldUrlNoHash !== newUrlNoHash) {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-27 21:55:49 +02:00
|
|
|
|
// If the hash has changed, then it's a hash only change.
|
|
|
|
|
// This check is necessary to handle both the enter and
|
|
|
|
|
// leave hash === '' cases. The identity case falls through
|
|
|
|
|
// and is treated as a next reload.
|
|
|
|
|
return oldHash !== newHash
|
2017-02-28 18:31:17 +01:00
|
|
|
|
}
|
|
|
|
|
|
2019-03-13 15:56:20 +01:00
|
|
|
|
scrollToHash(as: string): void {
|
2019-05-29 13:57:26 +02:00
|
|
|
|
const [, hash] = as.split('#')
|
2018-06-28 20:56:18 +02:00
|
|
|
|
// Scroll to top if the hash is just `#` with no value
|
|
|
|
|
if (hash === '') {
|
|
|
|
|
window.scrollTo(0, 0)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2018-08-23 20:20:45 +02:00
|
|
|
|
// First we check if the element by id is found
|
|
|
|
|
const idEl = document.getElementById(hash)
|
|
|
|
|
if (idEl) {
|
|
|
|
|
idEl.scrollIntoView()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
// If there's no element with the id, we check the `name` property
|
|
|
|
|
// To mirror browsers
|
|
|
|
|
const nameEl = document.getElementsByName(hash)[0]
|
|
|
|
|
if (nameEl) {
|
|
|
|
|
nameEl.scrollIntoView()
|
2017-06-09 21:32:28 +02:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-03-13 15:56:20 +01:00
|
|
|
|
urlIsNew(asPath: string): boolean {
|
2019-02-28 19:53:29 +01:00
|
|
|
|
return this.asPath !== asPath
|
2016-10-06 01:52:50 +02:00
|
|
|
|
}
|
|
|
|
|
|
2020-08-13 14:39:36 +02:00
|
|
|
|
_resolveHref(parsedHref: UrlObject, pages: string[]) {
|
|
|
|
|
const { pathname } = parsedHref
|
|
|
|
|
const cleanPathname = denormalizePagePath(delBasePath(pathname!))
|
|
|
|
|
|
|
|
|
|
if (cleanPathname === '/404' || cleanPathname === '/_error') {
|
|
|
|
|
return parsedHref
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// handle resolving href for dynamic routes
|
|
|
|
|
if (!pages.includes(cleanPathname!)) {
|
Reduce router code (#16159)
This reduces the code as suggested: https://github.com/vercel/next.js/pull/15231#discussion_r469691649.
Removes these bloated Babel helpers:
```diff
@@ -678,80 +678,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
var _createClass = __webpack_require__("W8MJ");
- function _createForOfIteratorHelper(o, allowArrayLike) {
- var it;
- if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
- if (
- Array.isArray(o) ||
- (it = _unsupportedIterableToArray(o)) ||
- (allowArrayLike && o && typeof o.length === "number")
- ) {
- if (it) o = it;
- var i = 0;
- var F = function F() {};
- return {
- s: F,
- n: function n() {
- if (i >= o.length) return { done: true };
- return { done: false, value: o[i++] };
- },
- e: function e(_e) {
- throw _e;
- },
- f: F
- };
- }
- throw new TypeError(
- "Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
- );
- }
- var normalCompletion = true,
- didErr = false,
- err;
- return {
- s: function s() {
- it = o[Symbol.iterator]();
- },
- n: function n() {
- var step = it.next();
- normalCompletion = step.done;
- return step;
- },
- e: function e(_e2) {
- didErr = true;
- err = _e2;
- },
- f: function f() {
- try {
- if (!normalCompletion && it["return"] != null) it["return"]();
- } finally {
- if (didErr) throw err;
- }
- }
- };
- }
-
- function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (
- n === "Arguments" ||
- /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)
- )
- return _arrayLikeToArray(o, minLen);
- }
-
- function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++) {
- arr2[i] = arr[i];
- }
- return arr2;
- }
-
exports.__esModule = true;
exports.hasBasePath = hasBasePath;
exports.addBasePath = addBasePath;
@@ -1864,28 +1790,16 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
} // handle resolving href for dynamic routes
if (!pages.includes(cleanPathname)) {
- var _iterator = _createForOfIteratorHelper(pages),
- _step;
-
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done; ) {
- var page = _step.value;
-
- if (
- (0, _isDynamic.isDynamicRoute)(page) &&
- (0, _routeRegex.getRouteRegex)(page).re.test(
- cleanPathname
- )
- ) {
- parsedHref.pathname = addBasePath(page);
- break;
- }
+ // eslint-disable-next-line array-callback-return
+ pages.some(function(page) {
+ if (
+ (0, _isDynamic.isDynamicRoute)(page) &&
+ (0, _routeRegex.getRouteRegex)(page).re.test(cleanPathname)
+ ) {
+ parsedHref.pathname = addBasePath(page);
+ return true;
}
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
+ });
}
return parsedHref;
@@ -2069,10 +1983,9 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
}
if (cancelled) {
- var _err = new Error("Loading initial props cancelled");
-
- _err.cancelled = true;
- throw _err;
+ var err = new Error("Loading initial props cancelled");
+ err.cancelled = true;
+ throw err;
}
return data;
```
2020-08-13 16:50:01 +02:00
|
|
|
|
// eslint-disable-next-line array-callback-return
|
|
|
|
|
pages.some((page) => {
|
2020-08-13 14:39:36 +02:00
|
|
|
|
if (
|
|
|
|
|
isDynamicRoute(page) &&
|
|
|
|
|
getRouteRegex(page).re.test(cleanPathname!)
|
|
|
|
|
) {
|
|
|
|
|
parsedHref.pathname = addBasePath(page)
|
Reduce router code (#16159)
This reduces the code as suggested: https://github.com/vercel/next.js/pull/15231#discussion_r469691649.
Removes these bloated Babel helpers:
```diff
@@ -678,80 +678,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
var _createClass = __webpack_require__("W8MJ");
- function _createForOfIteratorHelper(o, allowArrayLike) {
- var it;
- if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
- if (
- Array.isArray(o) ||
- (it = _unsupportedIterableToArray(o)) ||
- (allowArrayLike && o && typeof o.length === "number")
- ) {
- if (it) o = it;
- var i = 0;
- var F = function F() {};
- return {
- s: F,
- n: function n() {
- if (i >= o.length) return { done: true };
- return { done: false, value: o[i++] };
- },
- e: function e(_e) {
- throw _e;
- },
- f: F
- };
- }
- throw new TypeError(
- "Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
- );
- }
- var normalCompletion = true,
- didErr = false,
- err;
- return {
- s: function s() {
- it = o[Symbol.iterator]();
- },
- n: function n() {
- var step = it.next();
- normalCompletion = step.done;
- return step;
- },
- e: function e(_e2) {
- didErr = true;
- err = _e2;
- },
- f: function f() {
- try {
- if (!normalCompletion && it["return"] != null) it["return"]();
- } finally {
- if (didErr) throw err;
- }
- }
- };
- }
-
- function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (
- n === "Arguments" ||
- /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)
- )
- return _arrayLikeToArray(o, minLen);
- }
-
- function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++) {
- arr2[i] = arr[i];
- }
- return arr2;
- }
-
exports.__esModule = true;
exports.hasBasePath = hasBasePath;
exports.addBasePath = addBasePath;
@@ -1864,28 +1790,16 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
} // handle resolving href for dynamic routes
if (!pages.includes(cleanPathname)) {
- var _iterator = _createForOfIteratorHelper(pages),
- _step;
-
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done; ) {
- var page = _step.value;
-
- if (
- (0, _isDynamic.isDynamicRoute)(page) &&
- (0, _routeRegex.getRouteRegex)(page).re.test(
- cleanPathname
- )
- ) {
- parsedHref.pathname = addBasePath(page);
- break;
- }
+ // eslint-disable-next-line array-callback-return
+ pages.some(function(page) {
+ if (
+ (0, _isDynamic.isDynamicRoute)(page) &&
+ (0, _routeRegex.getRouteRegex)(page).re.test(cleanPathname)
+ ) {
+ parsedHref.pathname = addBasePath(page);
+ return true;
}
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
+ });
}
return parsedHref;
@@ -2069,10 +1983,9 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
}
if (cancelled) {
- var _err = new Error("Loading initial props cancelled");
-
- _err.cancelled = true;
- throw _err;
+ var err = new Error("Loading initial props cancelled");
+ err.cancelled = true;
+ throw err;
}
return data;
```
2020-08-13 16:50:01 +02:00
|
|
|
|
return true
|
2020-08-13 14:39:36 +02:00
|
|
|
|
}
|
Reduce router code (#16159)
This reduces the code as suggested: https://github.com/vercel/next.js/pull/15231#discussion_r469691649.
Removes these bloated Babel helpers:
```diff
@@ -678,80 +678,6 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
var _createClass = __webpack_require__("W8MJ");
- function _createForOfIteratorHelper(o, allowArrayLike) {
- var it;
- if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) {
- if (
- Array.isArray(o) ||
- (it = _unsupportedIterableToArray(o)) ||
- (allowArrayLike && o && typeof o.length === "number")
- ) {
- if (it) o = it;
- var i = 0;
- var F = function F() {};
- return {
- s: F,
- n: function n() {
- if (i >= o.length) return { done: true };
- return { done: false, value: o[i++] };
- },
- e: function e(_e) {
- throw _e;
- },
- f: F
- };
- }
- throw new TypeError(
- "Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
- );
- }
- var normalCompletion = true,
- didErr = false,
- err;
- return {
- s: function s() {
- it = o[Symbol.iterator]();
- },
- n: function n() {
- var step = it.next();
- normalCompletion = step.done;
- return step;
- },
- e: function e(_e2) {
- didErr = true;
- err = _e2;
- },
- f: function f() {
- try {
- if (!normalCompletion && it["return"] != null) it["return"]();
- } finally {
- if (didErr) throw err;
- }
- }
- };
- }
-
- function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (
- n === "Arguments" ||
- /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)
- )
- return _arrayLikeToArray(o, minLen);
- }
-
- function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++) {
- arr2[i] = arr[i];
- }
- return arr2;
- }
-
exports.__esModule = true;
exports.hasBasePath = hasBasePath;
exports.addBasePath = addBasePath;
@@ -1864,28 +1790,16 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
} // handle resolving href for dynamic routes
if (!pages.includes(cleanPathname)) {
- var _iterator = _createForOfIteratorHelper(pages),
- _step;
-
- try {
- for (_iterator.s(); !(_step = _iterator.n()).done; ) {
- var page = _step.value;
-
- if (
- (0, _isDynamic.isDynamicRoute)(page) &&
- (0, _routeRegex.getRouteRegex)(page).re.test(
- cleanPathname
- )
- ) {
- parsedHref.pathname = addBasePath(page);
- break;
- }
+ // eslint-disable-next-line array-callback-return
+ pages.some(function(page) {
+ if (
+ (0, _isDynamic.isDynamicRoute)(page) &&
+ (0, _routeRegex.getRouteRegex)(page).re.test(cleanPathname)
+ ) {
+ parsedHref.pathname = addBasePath(page);
+ return true;
}
- } catch (err) {
- _iterator.e(err);
- } finally {
- _iterator.f();
- }
+ });
}
return parsedHref;
@@ -2069,10 +1983,9 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
}
if (cancelled) {
- var _err = new Error("Loading initial props cancelled");
-
- _err.cancelled = true;
- throw _err;
+ var err = new Error("Loading initial props cancelled");
+ err.cancelled = true;
+ throw err;
}
return data;
```
2020-08-13 16:50:01 +02:00
|
|
|
|
})
|
2020-08-13 14:39:36 +02:00
|
|
|
|
}
|
|
|
|
|
return parsedHref
|
|
|
|
|
}
|
|
|
|
|
|
2019-05-23 21:31:22 +02:00
|
|
|
|
/**
|
2020-02-17 21:46:15 +01:00
|
|
|
|
* Prefetch page code, you may wait for the data during page rendering.
|
2019-05-23 21:31:22 +02:00
|
|
|
|
* This feature only works in production!
|
2020-02-17 21:46:15 +01:00
|
|
|
|
* @param url the href of prefetched page
|
|
|
|
|
* @param asPath the as path of the prefetched page
|
2019-05-23 21:31:22 +02:00
|
|
|
|
*/
|
2020-07-25 06:36:43 +02:00
|
|
|
|
async prefetch(
|
2020-02-17 21:46:15 +01:00
|
|
|
|
url: string,
|
|
|
|
|
asPath: string = url,
|
|
|
|
|
options: PrefetchOptions = {}
|
|
|
|
|
): Promise<void> {
|
2020-08-28 04:49:40 +02:00
|
|
|
|
let parsed = parseRelativeUrl(url)
|
2020-07-13 18:08:12 +02:00
|
|
|
|
|
2020-08-13 14:39:36 +02:00
|
|
|
|
let { pathname } = parsed
|
|
|
|
|
|
|
|
|
|
const pages = await this.pageLoader.getPageList()
|
|
|
|
|
|
|
|
|
|
parsed = this._resolveHref(parsed, pages) as typeof parsed
|
|
|
|
|
|
|
|
|
|
if (parsed.pathname !== pathname) {
|
|
|
|
|
pathname = parsed.pathname
|
|
|
|
|
url = formatWithValidation(parsed)
|
|
|
|
|
}
|
2019-12-20 22:30:58 +01:00
|
|
|
|
|
2020-07-25 06:36:43 +02:00
|
|
|
|
// Prefetch is not supported in development mode because it would trigger on-demand-entries
|
|
|
|
|
if (process.env.NODE_ENV !== 'production') {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const route = removePathTrailingSlash(pathname)
|
|
|
|
|
await Promise.all([
|
|
|
|
|
this.pageLoader.prefetchData(url, asPath),
|
|
|
|
|
this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](route),
|
|
|
|
|
])
|
2017-02-15 09:52:22 +01:00
|
|
|
|
}
|
|
|
|
|
|
2020-08-13 07:24:57 +02:00
|
|
|
|
async fetchComponent(route: string): Promise<GoodPageCache> {
|
2017-02-15 09:52:22 +01:00
|
|
|
|
let cancelled = false
|
2019-06-05 20:15:42 +02:00
|
|
|
|
const cancel = (this.clc = () => {
|
2017-02-15 09:52:22 +01:00
|
|
|
|
cancelled = true
|
2019-05-29 13:57:26 +02:00
|
|
|
|
})
|
2017-02-15 09:52:22 +01:00
|
|
|
|
|
2020-03-06 05:15:10 +01:00
|
|
|
|
const componentResult = await this.pageLoader.loadPage(route)
|
2017-02-15 09:52:22 +01:00
|
|
|
|
|
2018-01-30 16:40:52 +01:00
|
|
|
|
if (cancelled) {
|
2019-05-29 13:57:26 +02:00
|
|
|
|
const error: any = new Error(
|
|
|
|
|
`Abort fetching component for route: "${route}"`
|
|
|
|
|
)
|
2018-01-30 16:40:52 +01:00
|
|
|
|
error.cancelled = true
|
|
|
|
|
throw error
|
|
|
|
|
}
|
2017-02-15 09:52:22 +01:00
|
|
|
|
|
2019-06-05 20:15:42 +02:00
|
|
|
|
if (cancel === this.clc) {
|
|
|
|
|
this.clc = null
|
2017-07-18 09:00:23 +02:00
|
|
|
|
}
|
2018-01-30 16:40:52 +01:00
|
|
|
|
|
2020-03-06 05:15:10 +01:00
|
|
|
|
return componentResult
|
2016-10-08 07:12:51 +02:00
|
|
|
|
}
|
|
|
|
|
|
2019-12-29 20:01:46 +01:00
|
|
|
|
_getData<T>(fn: () => Promise<T>): Promise<T> {
|
2016-10-08 07:12:51 +02:00
|
|
|
|
let cancelled = false
|
2019-05-29 13:57:26 +02:00
|
|
|
|
const cancel = () => {
|
|
|
|
|
cancelled = true
|
|
|
|
|
}
|
2019-06-05 20:15:42 +02:00
|
|
|
|
this.clc = cancel
|
2020-05-18 21:24:37 +02:00
|
|
|
|
return fn().then((data) => {
|
2019-12-29 20:01:46 +01:00
|
|
|
|
if (cancel === this.clc) {
|
|
|
|
|
this.clc = null
|
|
|
|
|
}
|
2016-10-08 07:12:51 +02:00
|
|
|
|
|
2019-12-29 20:01:46 +01:00
|
|
|
|
if (cancelled) {
|
|
|
|
|
const err: any = new Error('Loading initial props cancelled')
|
|
|
|
|
err.cancelled = true
|
|
|
|
|
throw err
|
|
|
|
|
}
|
2019-08-12 03:56:57 +02:00
|
|
|
|
|
2019-12-29 20:01:46 +01:00
|
|
|
|
return data
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2020-07-19 06:02:01 +02:00
|
|
|
|
_getStaticData(dataHref: string): Promise<object> {
|
|
|
|
|
const { href: cacheKey } = new URL(dataHref, window.location.href)
|
|
|
|
|
if (process.env.NODE_ENV === 'production' && this.sdc[cacheKey]) {
|
|
|
|
|
return Promise.resolve(this.sdc[cacheKey])
|
|
|
|
|
}
|
|
|
|
|
return fetchNextData(dataHref, this.isSsr).then((data) => {
|
|
|
|
|
this.sdc[cacheKey] = data
|
|
|
|
|
return data
|
|
|
|
|
})
|
2020-01-27 23:50:59 +01:00
|
|
|
|
}
|
|
|
|
|
|
2020-07-19 06:02:01 +02:00
|
|
|
|
_getServerData(dataHref: string): Promise<object> {
|
2020-06-29 17:14:45 +02:00
|
|
|
|
return fetchNextData(dataHref, this.isSsr)
|
2019-12-30 19:40:23 +01:00
|
|
|
|
}
|
|
|
|
|
|
2019-12-29 20:01:46 +01:00
|
|
|
|
getInitialProps(
|
|
|
|
|
Component: ComponentType,
|
|
|
|
|
ctx: NextPageContext
|
|
|
|
|
): Promise<any> {
|
|
|
|
|
const { Component: App } = this.components['/_app']
|
2020-08-13 19:39:33 +02:00
|
|
|
|
const AppTree = this._wrapApp(App as AppComponent)
|
2019-12-29 20:01:46 +01:00
|
|
|
|
ctx.AppTree = AppTree
|
2019-12-30 19:40:23 +01:00
|
|
|
|
return loadGetInitialProps<AppContextType<Router>>(App, {
|
|
|
|
|
AppTree,
|
|
|
|
|
Component,
|
|
|
|
|
router: this,
|
|
|
|
|
ctx,
|
2019-12-29 20:01:46 +01:00
|
|
|
|
})
|
2016-10-06 01:52:50 +02:00
|
|
|
|
}
|
|
|
|
|
|
2019-03-14 19:43:29 +01:00
|
|
|
|
abortComponentLoad(as: string): void {
|
2019-06-05 20:15:42 +02:00
|
|
|
|
if (this.clc) {
|
2020-07-21 19:33:11 +02:00
|
|
|
|
Router.events.emit('routeChangeError', buildCancellationError(), as)
|
2019-06-05 20:15:42 +02:00
|
|
|
|
this.clc()
|
|
|
|
|
this.clc = null
|
2016-10-06 01:52:50 +02:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-13 19:39:33 +02:00
|
|
|
|
notify(data: PrivateRouteInfo): Promise<void> {
|
|
|
|
|
return this.sub(data, this.components['/_app'].Component as AppComponent)
|
2016-10-06 01:52:50 +02:00
|
|
|
|
}
|
|
|
|
|
}
|