Split index.js to separate files (#17315)

* split `index.js` to separate files

* tune clipboard

* fix promise

* fix document

* remove intermediate empty file

* fix async event listener

* use `export function` instead of `export {}`, add more comments

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: 6543 <6543@obermui.de>
This commit is contained in:
wxiaoguang 2021-10-17 01:28:04 +08:00 committed by GitHub
parent 3728f1daa0
commit 1a7473ff45
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
42 changed files with 3686 additions and 3501 deletions

View file

@ -1,4 +1,4 @@
const selector = '[data-clipboard-target], [data-clipboard-text]';
// For all DOM elements with [data-clipboard-target] or [data-clipboard-text], this copy-to-clipboard will work for them
// TODO: replace these with toast-style notifications
function onSuccess(btn) {
@ -16,23 +16,28 @@ function onError(btn) {
btn.dataset.content = btn.dataset.original;
}
export default async function initClipboard() {
for (const btn of document.querySelectorAll(selector) || []) {
btn.addEventListener('click', async () => {
export default function initGlobalCopyToClipboardListener() {
document.addEventListener('click', async (e) => {
let target = e.target;
// in case <button data-clipboard-text><svg></button>, so we just search up to 3 levels for performance.
for (let i = 0; i < 3 && target; i++) {
let text;
if (btn.dataset.clipboardText) {
text = btn.dataset.clipboardText;
} else if (btn.dataset.clipboardTarget) {
text = document.querySelector(btn.dataset.clipboardTarget)?.value;
if (target.dataset.clipboardText) {
text = target.dataset.clipboardText;
} else if (target.dataset.clipboardTarget) {
text = document.querySelector(target.dataset.clipboardTarget)?.value;
}
if (!text) return;
try {
await navigator.clipboard.writeText(text);
onSuccess(btn);
} catch {
onError(btn);
if (text) {
e.preventDefault();
try {
await navigator.clipboard.writeText(text);
onSuccess(target);
} catch {
onError(target);
}
break;
}
});
}
target = target.parentElement;
}
});
}