From 21d65fd9e51314d344ca2ee0ebfeffac0e1ecabb Mon Sep 17 00:00:00 2001 From: Paul Gottschling Date: Thu, 2 Nov 2023 11:21:42 -0400 Subject: [PATCH] Support anchor-only links within partials (#413) Let's say a partial includes a link like this: ```markdown [Link text](#anchor) ``` The link will render like this, which is incorrect: ```markdown [Link text](includes/#anchor) ``` This is because of the way `remark-includes` processes relative links in partials. Some partials need to link to an anchor within the same page. This change supports this by ignoring links with references that begin with `#`. Since all headings are flattened into the containing page, we can safely ignore file paths for anchor links. --- server/fixtures/includes/anchor-links.mdx | 5 +++++ server/remark-includes.ts | 10 +++++++-- uvu-tests/remark-includes.test.ts | 26 +++++++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 server/fixtures/includes/anchor-links.mdx diff --git a/server/fixtures/includes/anchor-links.mdx b/server/fixtures/includes/anchor-links.mdx new file mode 100644 index 0000000000..471f4a0887 --- /dev/null +++ b/server/fixtures/includes/anchor-links.mdx @@ -0,0 +1,5 @@ +This is a [link to an anchor](#this-is-a-section). + +## This is a section. + +This is content within the section. diff --git a/server/remark-includes.ts b/server/remark-includes.ts index b308257a6a..35321a8605 100644 --- a/server/remark-includes.ts +++ b/server/remark-includes.ts @@ -287,8 +287,14 @@ const handleURLPath = ( ) { const href = node.url; - // Ignore non-strings, absolute paths, or web URLs - if (typeof href !== "string" || href[0] === "/" || /^http/.test(href)) { + // Ignore non-strings, absolute paths, web URLs, and links consisting only + // of anchors (these will end up pointing to the containing page). + if ( + typeof href !== "string" || + href[0] === "/" || + /^http/.test(href) || + href[0] === "#" + ) { return href; } diff --git a/uvu-tests/remark-includes.test.ts b/uvu-tests/remark-includes.test.ts index 8ef9145201..1a68a8eae2 100644 --- a/uvu-tests/remark-includes.test.ts +++ b/uvu-tests/remark-includes.test.ts @@ -590,4 +590,30 @@ boundary" section. } ); +Suite.only( + "Interprets anchor-only links correctly when loading partials", + () => { + const actual = transformer({ + value: `Here is the outer page. + +(!anchor-links.mdx!) + +`, + path: "server/fixtures/mypage.mdx", + }).toString(); + + assert.equal( + actual, + `Here is the outer page. + +This is a [link to an anchor](#this-is-a-section). + +## This is a section. + +This is content within the section. +` + ); + } +); + Suite.run();