Skip to content

Commit

Permalink
Change how relative fragments are handled. (#1260)
Browse files Browse the repository at this point in the history
- Page-relative fragments (specifically, where the whole href starts with '#')
  are now demoted to plain `a` links in our link wrapper.

- The previous behavior that prepended to these links is now removed.

- The link wrapper `a` fallback has been expanded upon with comments, and now
  sets rel specifically on external links that don't already have it.
  • Loading branch information
rogermparent authored May 7, 2020
1 parent 43e090b commit 5c9a37d
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions src/components/Link/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,29 @@ const isMailto = (url: string): boolean => url.startsWith('mailto:')
const ResultLinkComponent: React.FC<ILinkProps> = ({
href,
children,
rel,
...restProps
}) => {
if (!isRelative(href) || isMailto(href) || restProps.target) {
let rel = 'noopener noreferrer'

if (restProps.rel) {
rel = `${rel} ${restProps.rel}`
// Handle all situations where a basic `a` must be used over Gatsby Link
const hrefIsRelative = isRelative(href)
const hrefIsMailto = isMailto(href)
const hrefHasTarget = restProps.target
// Fragments within the page should be `a`, but links to other pages
// that have anchors should be okay.
const hrefIsRelativeFragment = href.startsWith('#')

if (
!hrefIsRelative ||
hrefIsMailto ||
hrefHasTarget ||
hrefIsRelativeFragment
) {
/*
Change external links without an explicit rel to have 'noopener
noreferrer', but leave explicitly defined rels alone.
*/
if (!hrefIsRelative && typeof rel !== 'string') {
rel = 'noopener noreferrer'
}

return (
Expand Down Expand Up @@ -82,10 +98,6 @@ const Link: React.FC<ILinkProps> = ({ href, ...restProps }) => {
)

const location = new URL(href)
// Navigate from @reach/router handles hash links incorrectly. Fix it
if (href.startsWith('#')) {
href = currentLocation.pathname + href
}

if (location.host === currentLocation.host) {
// Replace link href with redirect if it exists
Expand Down

0 comments on commit 5c9a37d

Please sign in to comment.