Skip to content
This repository has been archived by the owner on Sep 2, 2024. It is now read-only.

Commit

Permalink
chore: await copy promise
Browse files Browse the repository at this point in the history
  • Loading branch information
im-adithya committed Jun 13, 2024
1 parent 21e50fa commit fc70bd5
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions frontend/src/lib/clipboard.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,36 @@
import { toast } from "src/components/ui/use-toast";

export function copyToClipboard(content: string) {
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(content);
} else {
// Fallback for older browsers
const textArea = document.createElement("textarea");
textArea.value = content;
textArea.style.position = "absolute";
textArea.style.opacity = "0";
document.body.appendChild(textArea);
selectElement(textArea);
new Promise((res, rej) => {
document.execCommand("copy") ? res(content) : rej();
const copyPromise = new Promise((resolve, reject) => {
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(content).then(resolve).catch(reject);
} else {
// Fallback for older browsers
const textArea = document.createElement("textarea");
textArea.value = content;
textArea.style.position = "absolute";
textArea.style.opacity = "0";
document.body.appendChild(textArea);
selectElement(textArea);
if (document.execCommand("copy")) {
resolve(content);
} else {
reject();
}
textArea.remove();
}
});

copyPromise
.then(() => {
toast({ title: "Copied to clipboard." });
})
.catch(() => {
toast({
title: "Failed to copy",
variant: "destructive",
});
});
}
toast({ title: "Copied to clipboard." });
}

function selectElement(element: Element) {
Expand Down

0 comments on commit fc70bd5

Please sign in to comment.