1 import React from 'react'
2 import {Link as PrimerLink} from '@primer/react'
3 import {Link as GatsbyLink} from 'gatsby'
4 import omit from '../util/omit'
5
6 const FALLBACK = `http://_${Math.random().toString().slice(2)}._${Math.random().toString().slice(2)}`
7
8 const getLocalPath = href => {
9 if (!href || href.startsWith('#')) {
10 return null
11 }
12
13 try {
14 const url = new URL(href, FALLBACK)
15 if (url.host === 'docs.npmjs.com' || url.origin === FALLBACK) {
16 return `${url.pathname}${url.search}${url.hash}`
17 }
18 } catch {
19 // ignore errors which will just pass along all props to PrimerLink
20 }
21
22 return null
23 }
24
25 const GatsbyLinkWithoutSxProps = React.forwardRef(function GatsbyLinkWithoutSxProps(props, ref) {
26 return <GatsbyLink ref={ref} {...omit(props, 'sx', 'underline', 'hoverColor', 'muted')} />
27 })
28
29 const Link = React.forwardRef(function Link({to, href, ...props}, ref) {
30 const localPath = getLocalPath(href)
31
32 if (to || localPath !== null) {
33 return <PrimerLink ref={ref} as={GatsbyLinkWithoutSxProps} to={to || localPath} {...props} />
34 }
35
36 return <PrimerLink ref={ref} href={href} {...props} />
37 })
38
39 export const LinkNoUnderline = React.forwardRef(function LinkNoUnderline({sx, ...props}, ref) {
40 return (
41 <Link
42 ref={ref}
43 sx={{
44 ...sx,
45 '&:hover, &:focus': {
46 textDecoration: 'none',
47 },
48 }}
49 {...props}
50 />
51 )
52 })
53
54 export default Link