clipboard.ts raw

   1  import { toast } from "sonner";
   2  
   3  export async function copyToClipboard(content: string) {
   4    const copyPromise = new Promise((resolve, reject) => {
   5      if (navigator.clipboard && window.isSecureContext) {
   6        navigator.clipboard.writeText(content).then(resolve).catch(reject);
   7      } else {
   8        // Fallback for older browsers
   9        const textArea = document.createElement("textarea");
  10        textArea.value = content;
  11        textArea.style.position = "absolute";
  12        textArea.style.opacity = "0";
  13        document.body.appendChild(textArea);
  14        textArea.focus();
  15        textArea.select();
  16  
  17        if (document.execCommand("copy")) {
  18          resolve(content);
  19        } else {
  20          reject();
  21        }
  22  
  23        textArea.remove();
  24      }
  25    });
  26  
  27    try {
  28      await copyPromise;
  29      toast.success("Copied to clipboard");
  30    } catch {
  31      toast.error("Failed to copy to clipboard");
  32    }
  33  }
  34