@@ -4,6 +4,7 @@ import NextLink, { type LinkProps as NextLinkProps } from 'next/link';
44import React from 'react' ;
55
66import { tcls } from '@/lib/tailwind' ;
7+ import { SiteExternalLinksTarget } from '@gitbook/api' ;
78import { type TrackEventInput , useTrackEvent } from '../Insights' ;
89import { type DesignTokenName , useClassnames } from './StyleProvider' ;
910
@@ -30,6 +31,15 @@ export type LinkProps = Omit<BaseLinkProps, 'href'> &
3031 classNames ?: DesignTokenName [ ] ;
3132 } ;
3233
34+ /**
35+ * Context to configure the default behavior of links.
36+ */
37+ export const LinkSettingsContext = React . createContext < {
38+ externalLinksTarget : SiteExternalLinksTarget ;
39+ } > ( {
40+ externalLinksTarget : SiteExternalLinksTarget . Self ,
41+ } ) ;
42+
3343/**
3444 * Low-level Link component that handles navigation to external urls.
3545 * It does not contain any styling.
@@ -39,6 +49,7 @@ export const Link = React.forwardRef(function Link(
3949 ref : React . Ref < HTMLAnchorElement >
4050) {
4151 const { href, prefetch, children, insights, classNames, className, ...domProps } = props ;
52+ const { externalLinksTarget } = React . useContext ( LinkSettingsContext ) ;
4253 const trackEvent = useTrackEvent ( ) ;
4354 const forwardedClassNames = useClassnames ( classNames || [ ] ) ;
4455
@@ -53,9 +64,14 @@ export const Link = React.forwardRef(function Link(
5364 } ) ;
5465 }
5566
56- // When the page is embedded in an iframe, for security reasons other urls cannot be opened.
57- // In this case, we open the link in a new tab.
58- if ( window . self !== window . top && isExternalLink ( href , window . location . origin ) ) {
67+ if (
68+ isExternalLink ( href , window . location . origin ) &&
69+ // When the page is embedded in an iframe, for security reasons other urls cannot be opened.
70+ // In this case, we open the link in a new tab.
71+ ( window . self !== window . top ||
72+ // If the site is configured to open links in a new tab
73+ externalLinksTarget === SiteExternalLinksTarget . Blank )
74+ ) {
5975 event . preventDefault ( ) ;
6076 window . open ( href , '_blank' ) ;
6177 }
@@ -73,6 +89,9 @@ export const Link = React.forwardRef(function Link(
7389 { ...domProps }
7490 href = { href }
7591 onClick = { onClick }
92+ { ...( externalLinksTarget === SiteExternalLinksTarget . Blank
93+ ? { target : '_blank' , rel : 'noopener noreferrer' }
94+ : { } ) }
7695 >
7796 { children }
7897 </ a >
0 commit comments