diff --git a/src/pages/_utils-node.ts b/src/pages/_utils-node.ts index 063b96104f..fa89bf51d9 100644 --- a/src/pages/_utils-node.ts +++ b/src/pages/_utils-node.ts @@ -65,8 +65,10 @@ export const rewriteRelativeLink = (url: string): string => { } // Relative links to md files should be turned into pages - if (updatedUrl.endsWith('.md')) { - updatedUrl = updatedUrl.replace(/\.md$/, ''); + // Use includes() instead of endsWith() to handle cases like "file.md#section" + // Use lookahead (?=#|$) to avoid breaking .mdx, etc. + if (updatedUrl.includes('.md')) { + updatedUrl = updatedUrl.replace(/\.md(?=#|$)/, '/'); } } diff --git a/src/scripts/utils.ts b/src/scripts/utils.ts index 10a7825681..0bae8efde4 100644 --- a/src/scripts/utils.ts +++ b/src/scripts/utils.ts @@ -293,16 +293,31 @@ export const rewriteRelativeMdLinks = (markdownText: string): string => { * Regex to find relative links to a markdown document in a string of Markdown * Has 2 capture groups: * 1. Text for the link - * 2. Link url (but not the .md extension at the end) + * 2. Link url (including the .md extension and hash) */ - const regexPattern: RegExp = /(!?)\[([^\]]+)\]\(([^)]+)\)/g; - return markdownText.replace(regexPattern, (match, img, linkText, url: string) => { + const inlineLinkRegexPattern: RegExp = /(!?)\[([^\]]+)\]\(([^)]+)\)/g; + let out = markdownText.replace(inlineLinkRegexPattern, (match, img, linkText, url: string) => { // Don't convert images if (img) return match; const updatedUrl = rewriteRelativeLink(url); return `[${linkText}](${updatedUrl})`; }); + + /** + * Regex to find reference links to a markdown document in a string of Markdown + * Has 2 capture groups: + * 1. Text for the link + * 2. Link url (including the .md extension and hash) + */ + + const referenceLinkRegexPattern: RegExp = /^(\[[^\]]+\]):\s*(\.[^\s]+)$/gm; + out = out.replace(referenceLinkRegexPattern, (match, linkText, fullUrl: string) => { + const updatedUrl = rewriteRelativeLink(fullUrl); + return `${linkText}: ${updatedUrl}`; + }); + + return out; }; /** * Deletes the contents of the given directory. diff --git a/test/scripts/utils.test.ts b/test/scripts/utils.test.ts index c4dae5850d..7e7e6ed76f 100644 --- a/test/scripts/utils.test.ts +++ b/test/scripts/utils.test.ts @@ -38,3 +38,29 @@ test("rewriteRelativeMdLinks", () => { - [external](https://p5js.org/) `); }); + +test("rewriteRelativeMdLinks with reference links", () => { + expect( + rewriteRelativeMdLinks(` +# Documentation + +See [our guide][guide] and [access statement][access]. + +You can also check [external link][external]. + +[guide]: ./contributing_guide.md +[access]: ./access.md#intro +[external]: https://p5js.org/ + `), + ).toEqual(` +# Documentation + +See [our guide][guide] and [access statement][access]. + +You can also check [external link][external]. + +[guide]: ../contributing_guide/ +[access]: ../access/#intro +[external]: https://p5js.org/ + `); +});