From c9d3bfd92ef129e13391b9916954cdba59717e00 Mon Sep 17 00:00:00 2001 From: Aaron Carlino Date: Wed, 1 Jul 2020 14:19:45 +1200 Subject: [PATCH] BUGFIX: Ensure .md links with hashes are rewritten properly (#228) * Upgrade gatsby * BUGFIX: ensure .md links with hashes are rewritten properly --- src/utils/rewriteLink.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/utils/rewriteLink.ts b/src/utils/rewriteLink.ts index 07b7575..a95dca6 100644 --- a/src/utils/rewriteLink.ts +++ b/src/utils/rewriteLink.ts @@ -20,6 +20,7 @@ const relativeLink = (currentNode: SilverstripeDocument, href: string): string = return slug; }; + /** * Ensure links use the Gatsby component. Client-side routing FTW * @@ -39,7 +40,6 @@ const rewriteLink = ( const currentNode = getCurrentNode(); const version = getCurrentVersion(); - // shorthand api links if (href.match(/^api\:/)) { const newHref = rewriteAPILink(href); @@ -90,7 +90,6 @@ const rewriteLink = ( // Relative to page if (currentNode && currentNode.parentSlug) { - // Relative links to markdown files should be resolved to their pretty urls. if (href.endsWith('.md')) { return createElement( @@ -102,6 +101,22 @@ const rewriteLink = ( domToReact(children, parseOptions) ) } + const hashMatches = href.match(/(\.md#([A-Za-z0-9_-]+))$/); + if (hashMatches) { + const newHashLink = href.replace( + new RegExp(`${hashMatches[1]}$`), + `#${hashMatches[2]}` + ); + + return createElement( + Link, + { + to: relativeLink(currentNode, newHashLink).replace(/\/$/, ''), + className: 'gatsby-link', + }, + domToReact(children, parseOptions) + ) + } return createElement( Link,