Skip to main content

max / makenotwork

1.5 KB · 41 lines History Blame Raw
1 // Clipboard helper — consolidates the ~6 duplicated copy-then-flash-label
2 // snippets and the delegated [data-copy-link] handler from mnw.js:670. Falls
3 // back to a prompt in non-secure contexts (plain HTTP, some iframes), where the
4 // old inline snippets silently no-op'd.
5
6 /** Copy `text`, flashing `copiedLabel` on `el`, then restoring the label. */
7 export function copyWithFeedback(el: HTMLElement, text: string, copiedLabel = 'Copied!', resetMs = 1500): void {
8 const defaultLabel = el.textContent ?? '';
9 const restore = () => {
10 el.textContent = defaultLabel;
11 };
12 if (navigator.clipboard?.writeText) {
13 navigator.clipboard
14 .writeText(text)
15 .then(() => {
16 el.textContent = copiedLabel;
17 setTimeout(restore, resetMs);
18 })
19 .catch(() => {
20 window.prompt('Copy this link:', text);
21 });
22 } else {
23 window.prompt('Copy this link:', text);
24 }
25 }
26
27 /** Install the delegated `[data-copy-link]` handler. `href` stays the real
28 * destination (middle-click / no-JS / share still work); left-click copies.
29 * Ported from mnw.js:670. */
30 export function initCopyLink(): void {
31 document.addEventListener('click', (evt) => {
32 const el = (evt.target as Element | null)?.closest<HTMLElement>('[data-copy-link]');
33 if (!el) return;
34 evt.preventDefault();
35 let url = el.dataset.url || el.getAttribute('href') || window.location.href;
36 if (url.charAt(0) === '/') url = window.location.origin + url;
37 const copiedLabel = el.dataset.copiedLabel || 'Copied!';
38 copyWithFeedback(el, url, copiedLabel);
39 });
40 }
41