Skip to content

Conversation

low-perry
Copy link

This PR updates the copy-to-clipboard functionality in our code blocks. The previous implementation used the now‑deprecated document.execCommand('copy') per MDN guidance. To modernize our approach and ensure future compatibility, we've replaced the deprecated method with the new asynchronous Clipboard API. In addition, we've added immediate visual feedback to inform users when text has been successfully copied.
Key Changes

  • Modern Clipboard API:
    The code now leverages navigator.clipboard.writeText() to handle the copy operation, ensuring a more robust and future‑proof solution.
  • User Feedback:
    On successful copying, the copy button temporarily changes its icon to indicate success (displaying a checkmark icon), then reverts back after 1 second. This provides clear, actionable feedback to users.

Code Changes
Before:

function copyToClipboard(container) {
  const el = document.createElement('textarea');
  el.value = container.textContent.replace(/\n$/, '');
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
}

After:

function copyToClipboard(container) {
  const text = container.textContent.replace(/\n$/, '');
  
  // Use the Clipboard API
  navigator.clipboard.writeText(text)
    .then(() => {
    // Add success feedback
      const button = container.parentNode.querySelector('.copy-clipboard');
      const originalHTML = button.innerHTML;
      
      // Show success state
      button.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Copied!</title><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"></path></svg>';
      
      // Reset after 1 second
      setTimeout(() => {
        button.innerHTML = originalHTML;
      }, 1000);
    })
    .catch(err => {
      console.error('Failed to copy: ', err);
    });
}

Preview
New Feature

This update not only aligns our implementation with modern web standards but also enhances the overall user experience with clear visual feedback. Let me know if there are any questions or further improvements you'd like to discuss!

@MasterOdin MasterOdin changed the base branch from main to dev May 6, 2025 03:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant