diff --git a/index.js b/index.js index aebdc7f..bfd861f 100644 --- a/index.js +++ b/index.js @@ -289,7 +289,19 @@ export function applyToLink(a, currentUrl) { && !a.firstElementChild ) { const shortened = shortenRepoUrl(url, currentUrl); - a.innerHTML = shortened; + a.replaceChildren( + ...shortened.split( + /([^<]+)<\/code>/g, + ).map((part, i) => { + if (i % 2 === 0) { + return part; + } + + const codeElement = document.createElement('code'); + codeElement.textContent = part; + return codeElement; + }), + ); return true; } diff --git a/index.test.js b/index.test.js index 1a4e9f0..7b60bda 100644 --- a/index.test.js +++ b/index.test.js @@ -1,7 +1,9 @@ import test from 'ava'; -import shortenUrl from './index.js'; +import {Window} from 'happy-dom'; +import shortenUrl, {applyToLink} from './index.js'; const currentLocation = 'https://github.com/fregante/shorten-repo-url/issue/1'; +globalThis.document = new Window({url: currentLocation}).document; function urlMatcherMacro(t, shouldMatch = []) { for (const [originalUrl, expectedShortenedUrl] of shouldMatch) { @@ -534,3 +536,19 @@ test('External URLs', urlMatcherMacro, new Map([ 'example.com/nodejs/node/blob/cc8fc46/.gitignore', ], ])); + +test('applyToLink', t => { + const a = document.createElement('a'); + a.href = 'https://github.com'; + a.textContent = 'https://github.com'; + t.true(applyToLink(a, currentLocation)); + t.is(a.textContent, 'github.com'); +}); + +test('applyToLink with a link that generates a HTML child element', t => { + const a = document.createElement('a'); + a.href = 'https://github.com/fregante/shorten-repo-url/blob/master/.gitignore'; + a.textContent = 'https://github.com/fregante/shorten-repo-url/blob/master/.gitignore'; + t.true(applyToLink(a, currentLocation)); + t.is(a.innerHTML, 'master/.gitignore'); +}); diff --git a/package.json b/package.json index d0c05f5..3bc7b24 100644 --- a/package.json +++ b/package.json @@ -32,6 +32,9 @@ }, "xo": { "parser": "@typescript-eslint/parser", + "globals": [ + "document" + ], "rules": { "unicorn/better-regex": "off", "unicorn/prefer-module": "off", @@ -44,6 +47,7 @@ "devDependencies": { "@sindresorhus/tsconfig": "^5.0.0", "ava": "^6.1.3", + "happy-dom": "^15.0.0", "tsd": "^0.31.1", "xo": "^0.58.0" },