|
1 | 1 | document.addEventListener('DOMContentLoaded', () => { |
2 | | - const buttonTemplate = `<button class="copy-button button is-muted is-outlined has-margin-2">Copy</button>`; |
| 2 | + /** |
| 3 | + * @param {string} content |
| 4 | + * @returns {HTMLButtonElement} |
| 5 | + */ |
| 6 | + const createCopyButton = (content, isSmall = false) => { |
| 7 | + const button = document.createElement('button'); |
| 8 | + button.classList.add('copy-button', 'button', 'is-muted', 'is-outlined', 'has-margin-2'); |
| 9 | + button.textContent = 'Copy'; |
| 10 | + |
| 11 | + if (isSmall) { |
| 12 | + button.classList.add('is-small'); |
| 13 | + } |
| 14 | + |
| 15 | + button.addEventListener('click', async () => { |
| 16 | + const originalButtonText = button.textContent; |
| 17 | + |
| 18 | + try { |
| 19 | + await navigator.clipboard.writeText(content); |
| 20 | + button.textContent = 'Copied!'; |
| 21 | + } |
| 22 | + catch (e) { |
| 23 | + console.warn(e); |
| 24 | + button.textContent = 'Failed!'; |
| 25 | + } |
| 26 | + finally { |
| 27 | + setTimeout(() => { |
| 28 | + button.textContent = originalButtonText; |
| 29 | + }, 2000); |
| 30 | + } |
| 31 | + }); |
| 32 | + |
| 33 | + return button; |
| 34 | + }; |
| 35 | + |
| 36 | + /** |
| 37 | + * @param {HTMLElement} element |
| 38 | + * @returns {HTMLDivElement} |
| 39 | + */ |
| 40 | + const wrapRelative = (element) => { |
| 41 | + const wrapper = document.createElement('div'); |
| 42 | + wrapper.style.position = 'relative'; |
| 43 | + wrapper.append(element.cloneNode(true)); |
| 44 | + element.replaceWith(wrapper); |
| 45 | + return wrapper; |
| 46 | + }; |
| 47 | + |
| 48 | + if (!window.isSecureContext) { |
| 49 | + return; |
| 50 | + } |
3 | 51 |
|
4 | 52 | $('.post--content pre > code') |
5 | 53 | .parent() |
6 | | - .each(function () { |
7 | | - const $button = $(buttonTemplate); |
| 54 | + .each(function (_, element) { |
8 | 55 | const $content = $(this).text(); |
9 | 56 | const numLines = $content.trim().split(/\r?\n/).length; |
10 | 57 |
|
11 | | - if (numLines <= 1) { |
12 | | - $button.addClass('is-small'); |
13 | | - } |
14 | | - |
15 | | - $(this) |
16 | | - .wrap('<div style="position:relative;"></div>') |
17 | | - .parent() |
18 | | - .prepend( |
19 | | - $button.click(function () { |
20 | | - navigator.clipboard.writeText($content); |
21 | | - $(this).text('Copied!'); |
22 | | - setTimeout(() => { |
23 | | - $(this).text('Copy'); |
24 | | - }, 2000); |
25 | | - }), |
26 | | - ); |
| 58 | + const button = createCopyButton($content, numLines <= 1); |
| 59 | + const wrapper = wrapRelative(element); |
| 60 | + wrapper.prepend(button); |
27 | 61 | }); |
28 | 62 | }); |
29 | | - |
|
0 commit comments