Skip to content

Commit

Permalink
Strip index path segment from link hrefs
Browse files Browse the repository at this point in the history
  • Loading branch information
kylegach committed Nov 21, 2023
1 parent cedbf9f commit c223f89
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/util/relative-to-root-links.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ function removeMdExtension(path) {
return path.replace(/\.md$/, '');
}

function removeTrailingIndex(path) {
return path.includes('#') ? path.replace(/\/index(?:\.md)?/, '/') : path.replace(/\/index$/, '');
}

/**
* Convert relative links in docs to relative but from the /docs root
*
Expand All @@ -25,7 +29,7 @@ function relativeToRootLinks(href, path = '', isIndexPage) {
// rewrite ../../../release-#-#/docs/parent/some-path style urls to /docs/version/parent/some-path
const overrideVersion = versionedUrl[1].split('-').join('.');
url = buildPathWithVersion(href.replace(/.*\/docs\/(.*)/, '/docs/$1'), overrideVersion);
return removeMdExtension(url);
return removeTrailingIndex(removeMdExtension(url));
}

if (isIndexPage && relativeUrlRegex.test(url)) {
Expand All @@ -41,13 +45,13 @@ function relativeToRootLinks(href, path = '', isIndexPage) {
const slugParts = path.split('/').filter((p) => !!p);
slugParts.splice(-1, 1, url.replace(relativeUrlRegex, '$2'));
url = `/${slugParts.join('/')}`;
return removeMdExtension(url);
return removeTrailingIndex(removeMdExtension(url));
}

if (multiLevelRelativeUrlRegex.test(url)) {
// rewrite ../parent/some-path style urls to /docs/version?/parent/some-path
url = buildPathWithVersion(url.replace(multiLevelRelativeUrlRegex, '/docs/$2'));
return removeMdExtension(url);
return removeTrailingIndex(removeMdExtension(url));
}

return url;
Expand Down
10 changes: 10 additions & 0 deletions src/util/relative-to-root-links.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ it('transforms specific-version links', () => {
expect(rootUrl).toEqual('/docs/6.5/api/csf');
});

it('removes trailing index pages', () => {
const rootUrl = relativeToRootLinks('../writing-stories/index.md', '/docs/api/csf');
expect(rootUrl).toEqual('/docs/writing-stories');
});

it('retains URL fragment on trailing index pages', () => {
const rootUrl = relativeToRootLinks('../writing-stories/index.md#foo', '/docs/api/csf');
expect(rootUrl).toEqual('/docs/writing-stories/#foo');
});

it('does not transform non-versioned upper-level links', () => {
const rootUrl = relativeToRootLinks('../../foo/bar/README.md', '/docs/writing-stories/args');
expect(rootUrl).toEqual('../../foo/bar/README.md');
Expand Down

0 comments on commit c223f89

Please sign in to comment.