From 25cc91e36c853b0cb8671ef892ac8574c5e0b8d9 Mon Sep 17 00:00:00 2001 From: Sophie Stadler Date: Wed, 3 Feb 2021 12:43:36 -0500 Subject: [PATCH] DOP-1965: Enforce trailing slash on internal links (#348) --- src/components/Link.js | 4 +++ src/components/RefRole.js | 2 +- tests/unit/Link.test.js | 15 ++++++++++ .../__snapshots__/Breadcrumbs.test.js.snap | 4 +-- tests/unit/__snapshots__/Card.test.js.snap | 14 ++++----- .../InternalPageNav.test.js.snap | 8 ++--- tests/unit/__snapshots__/Link.test.js.snap | 29 ++++++++++++++++++- .../TableOfContents.test.js.snap | 8 ++--- tests/unit/__snapshots__/Target.test.js.snap | 6 ++-- 9 files changed, 68 insertions(+), 22 deletions(-) diff --git a/src/components/Link.js b/src/components/Link.js index 3aad78ca4..739441eb1 100644 --- a/src/components/Link.js +++ b/src/components/Link.js @@ -18,6 +18,10 @@ const Link = ({ children, to, activeClassName, partiallyActive, ...other }) => { // Use Gatsby Link for internal links, and for others if (to && !external && !anchor) { if (!to.startsWith('/')) to = `/${to}`; + + // Ensure trailing slash + to = to.replace(/\/?(\?|#|$)/, '/$1'); + return ( {children} diff --git a/src/components/RefRole.js b/src/components/RefRole.js index 48fdfb9db..e02629e5c 100644 --- a/src/components/RefRole.js +++ b/src/components/RefRole.js @@ -26,7 +26,7 @@ const RefRole = ({ nodeData: { children, domain, fileid, name, url }, slug }) => // :doc: link link = filename; } else { - link = `${filename}#${html_id}`; + link = `${filename}/#${html_id}`; } } diff --git a/tests/unit/Link.test.js b/tests/unit/Link.test.js index 59f281b3b..c61350d87 100644 --- a/tests/unit/Link.test.js +++ b/tests/unit/Link.test.js @@ -19,4 +19,19 @@ describe('Link component renders a variety of strings correctly', () => { const tree = setup({ to: 'drivers/c', text: 'C Driver', className: 'test-class' }); expect(tree).toMatchSnapshot(); }); + + it('internal link with hash', () => { + const tree = setup({ to: 'drivers/pymongo#installation', text: 'C Driver', className: 'test-class' }); + expect(tree).toMatchSnapshot(); + }); + + it('internal link query param', () => { + const tree = setup({ to: 'drivers/ruby?site=drivers', text: 'C Driver', className: 'test-class' }); + expect(tree).toMatchSnapshot(); + }); + + it('internal link that already includes trailing slash', () => { + const tree = setup({ to: 'drivers/nodejs/#installation', text: 'C Driver', className: 'test-class' }); + expect(tree).toMatchSnapshot(); + }); }); diff --git a/tests/unit/__snapshots__/Breadcrumbs.test.js.snap b/tests/unit/__snapshots__/Breadcrumbs.test.js.snap index 93d78647c..d8f4a3776 100644 --- a/tests/unit/__snapshots__/Breadcrumbs.test.js.snap +++ b/tests/unit/__snapshots__/Breadcrumbs.test.js.snap @@ -13,7 +13,7 @@ exports[`renders correctly 1`] = `