Skip to content

Commit 072b874

Browse files
committed
feat: enhance copy button functionality with improved feedback and fallback mechanism
1 parent d57ce0a commit 072b874

1 file changed

Lines changed: 27 additions & 17 deletions

File tree

docs/_layouts/default.html

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -61,38 +61,48 @@
6161
btn.addEventListener('click', () => {
6262
const code = pre.querySelector('code');
6363
const text = code ? code.innerText : pre.innerText;
64-
navigator.clipboard.writeText(text).then(() => {
64+
65+
const markCopied = () => {
6566
btn.textContent = 'Copied!';
6667
btn.classList.add('copied');
6768
setTimeout(() => {
6869
btn.textContent = 'Copy';
6970
btn.classList.remove('copied');
7071
}, 2000);
71-
}).catch(() => {
72+
};
73+
74+
const markFailed = () => {
75+
btn.textContent = 'Copy failed';
76+
btn.classList.add('copy-error');
77+
setTimeout(() => {
78+
btn.textContent = 'Copy';
79+
btn.classList.remove('copy-error');
80+
}, 2000);
81+
};
82+
83+
const fallbackCopy = () => {
7284
const ta = document.createElement('textarea');
7385
ta.value = text;
7486
ta.style.position = 'fixed';
7587
ta.style.opacity = '0';
7688
document.body.appendChild(ta);
7789
ta.select();
7890
try {
79-
document.execCommand('copy');
80-
btn.textContent = 'Copied!';
81-
btn.classList.add('copied');
82-
setTimeout(() => {
83-
btn.textContent = 'Copy';
84-
btn.classList.remove('copied');
85-
}, 2000);
91+
const copied = document.execCommand('copy');
92+
if (copied) markCopied();
93+
else markFailed();
8694
} catch (e) {
87-
btn.textContent = 'Copy failed';
88-
btn.classList.add('copy-error');
89-
setTimeout(() => {
90-
btn.textContent = 'Copy';
91-
btn.classList.remove('copy-error');
92-
}, 2000);
95+
markFailed();
96+
} finally {
97+
document.body.removeChild(ta);
9398
}
94-
document.body.removeChild(ta);
95-
});
99+
};
100+
101+
if (navigator.clipboard?.writeText) {
102+
navigator.clipboard.writeText(text).then(markCopied).catch(fallbackCopy);
103+
} else {
104+
fallbackCopy();
105+
}
96106
});
97107

98108
wrapper.appendChild(btn);

0 commit comments

Comments
 (0)