1
1
mirror of https://github.com/go-gitea/gitea synced 2024-11-15 22:54:24 +00:00
gitea/web_src/js/features/clipboard.js
silverwind 37205039fc
Replace clipboard.js with async clipboard api (#15899)
Use async clipboard api [1] over this dependency, saving around 10kB
bundle size before minify while delivering the same functionality.

The issue comment button works but does not have a popup indication. We
could add some toast-style notifications in the future to fix that but I
think it's out of scope of this PR.

[1] https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText
2021-05-30 20:15:57 +01:00

39 lines
1.1 KiB
JavaScript

const selector = '[data-clipboard-target], [data-clipboard-text]';
// TODO: replace these with toast-style notifications
function onSuccess(btn) {
if (!btn.dataset.content) return;
$(btn).popup('destroy');
btn.dataset.content = btn.dataset.success;
$(btn).popup('show');
btn.dataset.content = btn.dataset.original;
}
function onError(btn) {
if (!btn.dataset.content) return;
$(btn).popup('destroy');
btn.dataset.content = btn.dataset.error;
$(btn).popup('show');
btn.dataset.content = btn.dataset.original;
}
export default async function initClipboard() {
for (const btn of document.querySelectorAll(selector) || []) {
btn.addEventListener('click', async () => {
let text;
if (btn.dataset.clipboardText) {
text = btn.dataset.clipboardText;
} else if (btn.dataset.clipboardTarget) {
text = document.querySelector(btn.dataset.clipboardTarget)?.value;
}
if (!text) return;
try {
await navigator.clipboard.writeText(text);
onSuccess(btn);
} catch {
onError(btn);
}
});
}
}