| 'use client' |
|
|
| import type { |
| NextRouter, |
| PrefetchOptions as RouterPrefetchOptions, |
| } from '../shared/lib/router/router' |
|
|
| import React, { createContext, useContext } from 'react' |
| import type { UrlObject } from 'url' |
| import { resolveHref } from './resolve-href' |
| import { isLocalURL } from '../shared/lib/router/utils/is-local-url' |
| import { formatUrl } from '../shared/lib/router/utils/format-url' |
| import { isAbsoluteUrl } from '../shared/lib/utils' |
| import { addLocale } from './add-locale' |
| import { RouterContext } from '../shared/lib/router-context.shared-runtime' |
| import type { AppRouterInstance } from '../shared/lib/app-router-context.shared-runtime' |
| import { useIntersection } from './use-intersection' |
| import { getDomainLocale } from './get-domain-locale' |
| import { addBasePath } from './add-base-path' |
| import { useMergedRef } from './use-merged-ref' |
| import { errorOnce } from '../shared/lib/utils/error-once' |
|
|
| type Url = string | UrlObject |
| type RequiredKeys<T> = { |
| [K in keyof T]-?: {} extends Pick<T, K> ? never : K |
| }[keyof T] |
| type OptionalKeys<T> = { |
| [K in keyof T]-?: {} extends Pick<T, K> ? K : never |
| }[keyof T] |
|
|
| type OnNavigateEventHandler = (event: { preventDefault: () => void }) => void |
|
|
| type InternalLinkProps = { |
| |
| |
| |
| |
| |
| href: Url |
| |
| |
| |
| as?: Url |
| |
| |
| |
| |
| |
| replace?: boolean |
| |
| |
| |
| |
| |
| |
| |
| scroll?: boolean |
| |
| |
| |
| |
| |
| shallow?: boolean |
| |
| |
| |
| |
| |
| passHref?: boolean |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| prefetch?: boolean | 'auto' | null |
| |
| |
| |
| |
| |
| locale?: string | false |
| |
| |
| |
| |
| |
| |
| legacyBehavior?: boolean |
| |
| |
| |
| onMouseEnter?: React.MouseEventHandler<HTMLAnchorElement> |
| |
| |
| |
| onTouchStart?: React.TouchEventHandler<HTMLAnchorElement> |
| |
| |
| |
| onClick?: React.MouseEventHandler<HTMLAnchorElement> |
| |
| |
| |
| onNavigate?: OnNavigateEventHandler |
| } |
|
|
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| export interface LinkProps<RouteInferType = any> extends InternalLinkProps {} |
| type LinkPropsRequired = RequiredKeys<LinkProps> |
| type LinkPropsOptional = OptionalKeys<InternalLinkProps> |
|
|
| const prefetched = new Set<string>() |
|
|
| type PrefetchOptions = RouterPrefetchOptions & { |
| |
| |
| |
| |
| bypassPrefetchedCheck?: boolean |
| } |
|
|
| function prefetch( |
| router: NextRouter, |
| href: string, |
| as: string, |
| options: PrefetchOptions |
| ): void { |
| if (typeof window === 'undefined') { |
| return |
| } |
|
|
| if (!isLocalURL(href)) { |
| return |
| } |
|
|
| |
| |
| if (!options.bypassPrefetchedCheck) { |
| const locale = |
| |
| typeof options.locale !== 'undefined' |
| ? options.locale |
| : |
| 'locale' in router |
| ? router.locale |
| : undefined |
|
|
| const prefetchedKey = href + '%' + as + '%' + locale |
|
|
| |
| if (prefetched.has(prefetchedKey)) { |
| return |
| } |
|
|
| |
| prefetched.add(prefetchedKey) |
| } |
|
|
| |
| |
| |
| |
| router.prefetch(href, as, options).catch((err) => { |
| if (process.env.NODE_ENV !== 'production') { |
| |
| throw err |
| } |
| }) |
| } |
|
|
| function isModifiedEvent(event: React.MouseEvent): boolean { |
| const eventTarget = event.currentTarget as HTMLAnchorElement | SVGAElement |
| const target = eventTarget.getAttribute('target') |
| return ( |
| (target && target !== '_self') || |
| event.metaKey || |
| event.ctrlKey || |
| event.shiftKey || |
| event.altKey || |
| (event.nativeEvent && event.nativeEvent.which === 2) |
| ) |
| } |
|
|
| function linkClicked( |
| e: React.MouseEvent, |
| router: NextRouter | AppRouterInstance, |
| href: string, |
| as: string, |
| replace?: boolean, |
| shallow?: boolean, |
| scroll?: boolean, |
| locale?: string | false, |
| onNavigate?: OnNavigateEventHandler |
| ): void { |
| const { nodeName } = e.currentTarget |
|
|
| |
| const isAnchorNodeName = nodeName.toUpperCase() === 'A' |
|
|
| if ( |
| (isAnchorNodeName && isModifiedEvent(e)) || |
| e.currentTarget.hasAttribute('download') |
| ) { |
| |
| return |
| } |
|
|
| if (!isLocalURL(href)) { |
| if (replace) { |
| |
| |
| e.preventDefault() |
| location.replace(href) |
| } |
|
|
| |
| return |
| } |
|
|
| e.preventDefault() |
|
|
| const navigate = () => { |
| if (onNavigate) { |
| let isDefaultPrevented = false |
|
|
| onNavigate({ |
| preventDefault: () => { |
| isDefaultPrevented = true |
| }, |
| }) |
|
|
| if (isDefaultPrevented) { |
| return |
| } |
| } |
|
|
| |
| const routerScroll = scroll ?? true |
| if ('beforePopState' in router) { |
| router[replace ? 'replace' : 'push'](href, as, { |
| shallow, |
| locale, |
| scroll: routerScroll, |
| }) |
| } else { |
| router[replace ? 'replace' : 'push'](as || href, { |
| scroll: routerScroll, |
| }) |
| } |
| } |
|
|
| navigate() |
| } |
|
|
| type LinkPropsReal = React.PropsWithChildren< |
| Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, keyof LinkProps> & |
| LinkProps |
| > |
|
|
| function formatStringOrUrl(urlObjOrString: UrlObject | string): string { |
| if (typeof urlObjOrString === 'string') { |
| return urlObjOrString |
| } |
|
|
| return formatUrl(urlObjOrString) |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( |
| function LinkComponent(props, forwardedRef) { |
| let children: React.ReactNode |
|
|
| const { |
| href: hrefProp, |
| as: asProp, |
| children: childrenProp, |
| prefetch: prefetchProp = null, |
| passHref, |
| replace, |
| shallow, |
| scroll, |
| locale, |
| onClick, |
| onNavigate, |
| onMouseEnter: onMouseEnterProp, |
| onTouchStart: onTouchStartProp, |
| legacyBehavior = false, |
| ...restProps |
| } = props |
|
|
| children = childrenProp |
|
|
| if ( |
| legacyBehavior && |
| (typeof children === 'string' || typeof children === 'number') |
| ) { |
| children = <a>{children}</a> |
| } |
|
|
| const router = React.useContext(RouterContext) |
|
|
| const prefetchEnabled = prefetchProp !== false |
|
|
| if (process.env.NODE_ENV !== 'production') { |
| function createPropError(args: { |
| key: string |
| expected: string |
| actual: string |
| }) { |
| return new Error( |
| `Failed prop type: The prop \`${args.key}\` expects a ${args.expected} in \`<Link>\`, but got \`${args.actual}\` instead.` + |
| (typeof window !== 'undefined' |
| ? |
| "\nOpen your browser's console to view the Component stack trace." |
| : '') |
| ) |
| } |
|
|
| |
| const requiredPropsGuard: Record<LinkPropsRequired, true> = { |
| href: true, |
| } as const |
| const requiredProps: LinkPropsRequired[] = Object.keys( |
| requiredPropsGuard |
| ) as LinkPropsRequired[] |
| requiredProps.forEach((key: LinkPropsRequired) => { |
| if (key === 'href') { |
| if ( |
| props[key] == null || |
| (typeof props[key] !== 'string' && typeof props[key] !== 'object') |
| ) { |
| throw createPropError({ |
| key, |
| expected: '`string` or `object`', |
| actual: props[key] === null ? 'null' : typeof props[key], |
| }) |
| } |
| } else { |
| |
| |
| const _: never = key |
| } |
| }) |
|
|
| |
| const optionalPropsGuard: Record<LinkPropsOptional, true> = { |
| as: true, |
| replace: true, |
| scroll: true, |
| shallow: true, |
| passHref: true, |
| prefetch: true, |
| locale: true, |
| onClick: true, |
| onMouseEnter: true, |
| onTouchStart: true, |
| legacyBehavior: true, |
| onNavigate: true, |
| } as const |
| const optionalProps: LinkPropsOptional[] = Object.keys( |
| optionalPropsGuard |
| ) as LinkPropsOptional[] |
| optionalProps.forEach((key: LinkPropsOptional) => { |
| const valType = typeof props[key] |
|
|
| if (key === 'as') { |
| if (props[key] && valType !== 'string' && valType !== 'object') { |
| throw createPropError({ |
| key, |
| expected: '`string` or `object`', |
| actual: valType, |
| }) |
| } |
| } else if (key === 'locale') { |
| if (props[key] && valType !== 'string') { |
| throw createPropError({ |
| key, |
| expected: '`string`', |
| actual: valType, |
| }) |
| } |
| } else if ( |
| key === 'onClick' || |
| key === 'onMouseEnter' || |
| key === 'onTouchStart' || |
| key === 'onNavigate' |
| ) { |
| if (props[key] && valType !== 'function') { |
| throw createPropError({ |
| key, |
| expected: '`function`', |
| actual: valType, |
| }) |
| } |
| } else if ( |
| key === 'replace' || |
| key === 'scroll' || |
| key === 'shallow' || |
| key === 'passHref' || |
| key === 'legacyBehavior' |
| ) { |
| if (props[key] != null && valType !== 'boolean') { |
| throw createPropError({ |
| key, |
| expected: '`boolean`', |
| actual: valType, |
| }) |
| } |
| } else if (key === 'prefetch') { |
| if ( |
| props[key] != null && |
| valType !== 'boolean' && |
| props[key] !== 'auto' |
| ) { |
| throw createPropError({ |
| key, |
| expected: '`boolean | "auto"`', |
| actual: valType, |
| }) |
| } |
| } else { |
| |
| |
| const _: never = key |
| } |
| }) |
| } |
|
|
| const { href, as } = React.useMemo(() => { |
| if (!router) { |
| const resolvedHref = formatStringOrUrl(hrefProp) |
| return { |
| href: resolvedHref, |
| as: asProp ? formatStringOrUrl(asProp) : resolvedHref, |
| } |
| } |
|
|
| const [resolvedHref, resolvedAs] = resolveHref(router, hrefProp, true) |
|
|
| return { |
| href: resolvedHref, |
| as: asProp ? resolveHref(router, asProp) : resolvedAs || resolvedHref, |
| } |
| }, [router, hrefProp, asProp]) |
|
|
| const previousHref = React.useRef<string>(href) |
| const previousAs = React.useRef<string>(as) |
|
|
| |
| let child: any |
| if (legacyBehavior) { |
| if (process.env.NODE_ENV === 'development') { |
| if (onClick) { |
| console.warn( |
| `"onClick" was passed to <Link> with \`href\` of \`${hrefProp}\` but "legacyBehavior" was set. The legacy behavior requires onClick be set on the child of next/link` |
| ) |
| } |
| if (onMouseEnterProp) { |
| console.warn( |
| `"onMouseEnter" was passed to <Link> with \`href\` of \`${hrefProp}\` but "legacyBehavior" was set. The legacy behavior requires onMouseEnter be set on the child of next/link` |
| ) |
| } |
| try { |
| child = React.Children.only(children) |
| } catch (err) { |
| if (!children) { |
| throw new Error( |
| `No children were passed to <Link> with \`href\` of \`${hrefProp}\` but one child is required https://nextjs.org/docs/messages/link-no-children` |
| ) |
| } |
| throw new Error( |
| `Multiple children were passed to <Link> with \`href\` of \`${hrefProp}\` but only one child is supported https://nextjs.org/docs/messages/link-multiple-children` + |
| (typeof window !== 'undefined' |
| ? " \nOpen your browser's console to view the Component stack trace." |
| : '') |
| ) |
| } |
| } else { |
| child = React.Children.only(children) |
| } |
| } else { |
| if (process.env.NODE_ENV === 'development') { |
| if ((children as any)?.type === 'a') { |
| throw new Error( |
| 'Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor' |
| ) |
| } |
| } |
| } |
|
|
| const childRef: any = legacyBehavior |
| ? child && typeof child === 'object' && child.ref |
| : forwardedRef |
|
|
| const [setIntersectionRef, isVisible, resetVisible] = useIntersection({ |
| rootMargin: '200px', |
| }) |
|
|
| const setIntersectionWithResetRef = React.useCallback( |
| (el: Element | null) => { |
| |
| if (previousAs.current !== as || previousHref.current !== href) { |
| resetVisible() |
| previousAs.current = as |
| previousHref.current = href |
| } |
|
|
| setIntersectionRef(el) |
| }, |
| [as, href, resetVisible, setIntersectionRef] |
| ) |
|
|
| const setRef = useMergedRef(setIntersectionWithResetRef, childRef) |
|
|
| |
| React.useEffect(() => { |
| |
| if (process.env.NODE_ENV !== 'production') { |
| return |
| } |
|
|
| if (!router) { |
| return |
| } |
|
|
| |
| if (!isVisible || !prefetchEnabled) { |
| return |
| } |
|
|
| |
| prefetch(router, href, as, { locale }) |
| }, [as, href, isVisible, locale, prefetchEnabled, router?.locale, router]) |
|
|
| const childProps: { |
| onTouchStart?: React.TouchEventHandler<HTMLAnchorElement> |
| onMouseEnter: React.MouseEventHandler<HTMLAnchorElement> |
| onClick: React.MouseEventHandler<HTMLAnchorElement> |
| href?: string |
| ref?: any |
| } = { |
| ref: setRef, |
| onClick(e) { |
| if (process.env.NODE_ENV !== 'production') { |
| if (!e) { |
| throw new Error( |
| `Component rendered inside next/link has to pass click event to "onClick" prop.` |
| ) |
| } |
| } |
|
|
| if (!legacyBehavior && typeof onClick === 'function') { |
| onClick(e) |
| } |
|
|
| if ( |
| legacyBehavior && |
| child.props && |
| typeof child.props.onClick === 'function' |
| ) { |
| child.props.onClick(e) |
| } |
|
|
| if (!router) { |
| return |
| } |
|
|
| if (e.defaultPrevented) { |
| return |
| } |
|
|
| linkClicked( |
| e, |
| router, |
| href, |
| as, |
| replace, |
| shallow, |
| scroll, |
| locale, |
| onNavigate |
| ) |
| }, |
| onMouseEnter(e) { |
| if (!legacyBehavior && typeof onMouseEnterProp === 'function') { |
| onMouseEnterProp(e) |
| } |
|
|
| if ( |
| legacyBehavior && |
| child.props && |
| typeof child.props.onMouseEnter === 'function' |
| ) { |
| child.props.onMouseEnter(e) |
| } |
|
|
| if (!router) { |
| return |
| } |
|
|
| prefetch(router, href, as, { |
| locale, |
| priority: true, |
| |
| bypassPrefetchedCheck: true, |
| }) |
| }, |
| onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START |
| ? undefined |
| : function onTouchStart(e) { |
| if (!legacyBehavior && typeof onTouchStartProp === 'function') { |
| onTouchStartProp(e) |
| } |
|
|
| if ( |
| legacyBehavior && |
| child.props && |
| typeof child.props.onTouchStart === 'function' |
| ) { |
| child.props.onTouchStart(e) |
| } |
|
|
| if (!router) { |
| return |
| } |
|
|
| prefetch(router, href, as, { |
| locale, |
| priority: true, |
| |
| bypassPrefetchedCheck: true, |
| }) |
| }, |
| } |
|
|
| |
| |
| |
| if (isAbsoluteUrl(as)) { |
| childProps.href = as |
| } else if ( |
| !legacyBehavior || |
| passHref || |
| (child.type === 'a' && !('href' in child.props)) |
| ) { |
| const curLocale = typeof locale !== 'undefined' ? locale : router?.locale |
|
|
| |
| |
| const localeDomain = |
| router?.isLocaleDomain && |
| getDomainLocale(as, curLocale, router?.locales, router?.domainLocales) |
|
|
| childProps.href = |
| localeDomain || |
| addBasePath(addLocale(as, curLocale, router?.defaultLocale)) |
| } |
|
|
| if (legacyBehavior) { |
| if (process.env.NODE_ENV === 'development') { |
| errorOnce( |
| '`legacyBehavior` is deprecated and will be removed in a future ' + |
| 'release. A codemod is available to upgrade your components:\n\n' + |
| 'npx @next/codemod@latest new-link .\n\n' + |
| 'Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components' |
| ) |
| } |
| return React.cloneElement(child, childProps) |
| } |
|
|
| return ( |
| <a {...restProps} {...childProps}> |
| {children} |
| </a> |
| ) |
| } |
| ) |
|
|
| const LinkStatusContext = createContext<{ |
| pending: boolean |
| }>({ |
| |
| pending: false, |
| }) |
|
|
| export const useLinkStatus = () => { |
| |
| |
| return useContext(LinkStatusContext) |
| } |
|
|
| export default Link |
|
|