Skip to content

Commit 736c98b

Browse files
authored
Refactor copy button event handler (go-gitea#29379)
Use "closest" instead of "for-loop"
1 parent b616f66 commit 736c98b

File tree

1 file changed

+17
-24
lines changed

1 file changed

+17
-24
lines changed

web_src/js/features/clipboard.js

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,37 +5,30 @@ import {clippie} from 'clippie';
55
const {copy_success, copy_error} = window.config.i18n;
66

77
// Enable clipboard copy from HTML attributes. These properties are supported:
8-
// - data-clipboard-text: Direct text to copy, has highest precedence
8+
// - data-clipboard-text: Direct text to copy
99
// - data-clipboard-target: Holds a selector for a <input> or <textarea> whose content is copied
1010
// - data-clipboard-text-type: When set to 'url' will convert relative to absolute urls
1111
export function initGlobalCopyToClipboardListener() {
12-
document.addEventListener('click', (e) => {
13-
let target = e.target;
14-
// In case <button data-clipboard-text><svg></button>, so we just search
15-
// up to 3 levels for performance
16-
for (let i = 0; i < 3 && target; i++) {
17-
let text = target.getAttribute('data-clipboard-text');
12+
document.addEventListener('click', async (e) => {
13+
const target = e.target.closest('[data-clipboard-text], [data-clipboard-target]');
14+
if (!target) return;
1815

19-
if (!text && target.getAttribute('data-clipboard-target')) {
20-
text = document.querySelector(target.getAttribute('data-clipboard-target'))?.value;
21-
}
16+
e.preventDefault();
2217

23-
if (text && target.getAttribute('data-clipboard-text-type') === 'url') {
24-
text = toAbsoluteUrl(text);
25-
}
26-
27-
if (text) {
28-
e.preventDefault();
29-
30-
(async() => {
31-
const success = await clippie(text);
32-
showTemporaryTooltip(target, success ? copy_success : copy_error);
33-
})();
18+
let text;
19+
if (target.hasAttribute('data-clipboard-text')) {
20+
text = target.getAttribute('data-clipboard-text');
21+
} else {
22+
text = document.querySelector(target.getAttribute('data-clipboard-target'))?.value;
23+
}
3424

35-
break;
36-
}
25+
if (text && target.getAttribute('data-clipboard-text-type') === 'url') {
26+
text = toAbsoluteUrl(text);
27+
}
3728

38-
target = target.parentElement;
29+
if (text) {
30+
const success = await clippie(text);
31+
showTemporaryTooltip(target, success ? copy_success : copy_error);
3932
}
4033
});
4134
}

0 commit comments

Comments
 (0)