|
12 | 12 | // See the License for the specific language governing permissions and |
13 | 13 | // limitations under the License. |
14 | 14 |
|
15 | | -function copyTextToClipboard(text) { |
| 15 | +const clipboardIcon = `<svg xmlns="http://www.w3.org/2000/svg" |
| 16 | + viewBox="0 0 24 24" fill="none" |
| 17 | + stroke="currentColor" |
| 18 | + stroke-width="2" |
| 19 | + stroke-linecap="round" |
| 20 | + stroke-linejoin="round"> |
| 21 | + <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect> |
| 22 | + <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path> |
| 23 | + </svg>`; |
| 24 | +const checkmarkIcon = `<svg xmlns="http://www.w3.org/2000/svg" |
| 25 | + viewBox="0 0 24 24" fill="none" |
| 26 | + stroke="green" |
| 27 | + stroke-width="2" |
| 28 | + stroke-linecap="round" |
| 29 | + stroke-linejoin="round"> |
| 30 | + <polyline points="20 6 9 17 4 12"></polyline> |
| 31 | + </svg>`; |
| 32 | + |
| 33 | +function createCopyButton(textProviderFunction, htmlProviderFunction) { |
| 34 | + if (!textProviderFunction) { |
| 35 | + throw new Error("textProviderFunction is null"); |
| 36 | + } |
| 37 | + const copyButton = document.createElement('button'); |
| 38 | + copyButton.className = 'copy-button'; |
| 39 | + copyButton.innerHTML = clipboardIcon; |
| 40 | + copyButton.addEventListener('click', async function () { |
| 41 | + try { |
| 42 | + await copyTextToClipboard(textProviderFunction(), htmlProviderFunction ? htmlProviderFunction() : null); |
| 43 | + copyButton.innerHTML = checkmarkIcon |
| 44 | + setTimeout(() => copyButton.innerHTML = clipboardIcon, 2000); |
| 45 | + } catch (err) { |
| 46 | + console.error('Failed to copy text:', err); |
| 47 | + } |
| 48 | + }); |
| 49 | + return copyButton; |
| 50 | +} |
| 51 | + |
| 52 | +async function copyTextToClipboard(text, html) { |
16 | 53 | // see https://stackoverflow.com/a/30810322/1653720 |
17 | 54 | if (navigator.clipboard) { |
18 | | - navigator.clipboard.writeText(text).then(function() { |
19 | | - }, function(err) { |
20 | | - console.error('could not copy text: ', err); |
21 | | - }); |
| 55 | + if (html && window.ClipboardItem && navigator.clipboard.write) { |
| 56 | + const data = [ |
| 57 | + new ClipboardItem({ |
| 58 | + "text/html": new Blob([html], { type: "text/html" }), |
| 59 | + "text/plain": new Blob([text], { type: "text/plain" }), |
| 60 | + }) |
| 61 | + ]; |
| 62 | + return navigator.clipboard.write(data); |
| 63 | + } else { |
| 64 | + // Fallback to text-only copy if ClipboardItem is not supported (or html is not needed) |
| 65 | + return navigator.clipboard.writeText(text); |
| 66 | + } |
22 | 67 | } else { |
23 | 68 | var textArea = document.createElement('textarea'); |
24 | 69 | textArea.value = text; |
|
0 commit comments