Skip to content
This repository has been archived by the owner on Jan 8, 2025. It is now read-only.

Commit

Permalink
Support anchor-only links within partials (#413)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ptgott authored Nov 2, 2023
1 parent 631c3e3 commit 21d65fd
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
5 changes: 5 additions & 0 deletions server/fixtures/includes/anchor-links.mdx
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 8 additions & 2 deletions server/remark-includes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
26 changes: 26 additions & 0 deletions uvu-tests/remark-includes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

1 comment on commit 21d65fd

@vercel
Copy link

@vercel vercel bot commented on 21d65fd Nov 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.