| Earl Lee | 2e463fb | 2025-04-17 11:22:22 -0700 | [diff] [blame^] | 1 | /** |
| 2 | * Creates a copy button container with a functioning copy button |
| 3 | */ |
| 4 | export function createCopyButton(textToCopy: string): { |
| 5 | container: HTMLDivElement; |
| 6 | button: HTMLButtonElement; |
| 7 | } { |
| 8 | // Create container for the copy button |
| 9 | const copyButtonContainer = document.createElement("div"); |
| 10 | copyButtonContainer.className = "message-actions"; |
| 11 | |
| 12 | // Create the copy button itself |
| 13 | const copyButton = document.createElement("button"); |
| 14 | copyButton.className = "copy-button"; |
| 15 | copyButton.textContent = "Copy"; |
| 16 | copyButton.title = "Copy text to clipboard"; |
| 17 | |
| 18 | // Add click event listener to handle copying |
| 19 | copyButton.addEventListener("click", (e) => { |
| 20 | e.stopPropagation(); |
| 21 | navigator.clipboard |
| 22 | .writeText(textToCopy) |
| 23 | .then(() => { |
| 24 | copyButton.textContent = "Copied!"; |
| 25 | setTimeout(() => { |
| 26 | copyButton.textContent = "Copy"; |
| 27 | }, 2000); |
| 28 | }) |
| 29 | .catch((err) => { |
| 30 | console.error("Failed to copy text: ", err); |
| 31 | copyButton.textContent = "Failed"; |
| 32 | setTimeout(() => { |
| 33 | copyButton.textContent = "Copy"; |
| 34 | }, 2000); |
| 35 | }); |
| 36 | }); |
| 37 | |
| 38 | copyButtonContainer.appendChild(copyButton); |
| 39 | |
| 40 | return { |
| 41 | container: copyButtonContainer, |
| 42 | button: copyButton |
| 43 | }; |
| 44 | } |