Handle URLs with a #hash correctly when rewriting link URLs
Signed-off-by: Oliver Sand <oliver.sand@sda-se.com>
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@backstage/plugin-techdocs': patch
|
||||
---
|
||||
|
||||
Handle URLs with a `#hash` correctly when rewriting link URLs.
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
import { createTestShadowDom, getSample } from '../../test-utils';
|
||||
import { rewriteDocLinks } from '../transformers';
|
||||
import { normalizeUrl } from './rewriteDocLinks';
|
||||
|
||||
describe('rewriteDocLinks', () => {
|
||||
it('should not do anything', () => {
|
||||
@@ -56,3 +57,17 @@ describe('rewriteDocLinks', () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeUrl', () => {
|
||||
it.each([
|
||||
['http://example.org', 'http://example.org/'],
|
||||
['http://example.org/', 'http://example.org/'],
|
||||
['http://example.org/folder', 'http://example.org/folder/'],
|
||||
['http://example.org/folder/', 'http://example.org/folder/'],
|
||||
['http://example.org/folder#intro', 'http://example.org/folder/#intro'],
|
||||
['http://example.org/folder/#intro', 'http://example.org/folder/#intro'],
|
||||
['http://example.org/folder#', 'http://example.org/folder/#'],
|
||||
])('should handle %s', (url, expected) => {
|
||||
expect(normalizeUrl(url)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -31,9 +31,7 @@ export const rewriteDocLinks = (): Transformer => {
|
||||
if (elemAttribute.match(/^https?:\/\//i)) {
|
||||
elem.setAttribute('target', '_blank');
|
||||
}
|
||||
const normalizedWindowLocation = window.location.href.endsWith('/')
|
||||
? window.location.href
|
||||
: `${window.location.href}/`;
|
||||
const normalizedWindowLocation = normalizeUrl(window.location.href);
|
||||
|
||||
elem.setAttribute(
|
||||
attributeName,
|
||||
@@ -48,3 +46,14 @@ export const rewriteDocLinks = (): Transformer => {
|
||||
return dom;
|
||||
};
|
||||
};
|
||||
|
||||
/** Make sure that the input url always ends with a '/' */
|
||||
export function normalizeUrl(input: string): string {
|
||||
const url = new URL(input);
|
||||
|
||||
if (!url.pathname.endsWith('/')) {
|
||||
url.pathname += '/';
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user