Skip to content

Commit

Permalink
Avoid innerHTML
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante committed Aug 24, 2024
1 parent e3e19a1 commit 9c50da5
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
14 changes: 13 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,19 @@ export function applyToLink(a, currentUrl) {
&& !a.firstElementChild
) {
const shortened = shortenRepoUrl(url, currentUrl);
a.innerHTML = shortened;
a.replaceChildren(
...shortened.split(
/<code>([^<]+)<\/code>/g,
).map((part, i) => {
if (i % 2 === 0) {
return part;
}

const codeElement = document.createElement('code');
codeElement.textContent = part;
return codeElement;
}),
);
return true;
}

Expand Down
20 changes: 19 additions & 1 deletion index.test.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down Expand Up @@ -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, '<code>master</code>/.gitignore');
});
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
},
"xo": {
"parser": "@typescript-eslint/parser",
"globals": [
"document"
],
"rules": {
"unicorn/better-regex": "off",
"unicorn/prefer-module": "off",
Expand All @@ -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"
},
Expand Down

0 comments on commit 9c50da5

Please sign in to comment.