feat: add copyToClipboard() utility with execCommand fallback

This commit is contained in:
Siddharth Kumar Sah
2026-04-04 16:25:25 +08:00
parent f61ab9f85c
commit 19ce303123
2 changed files with 52 additions and 2 deletions
+21
View File
@@ -13,3 +13,24 @@ export function generateId(): string {
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
export async function copyToClipboard(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
try {
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.select();
const ok = document.execCommand("copy");
document.body.removeChild(textarea);
return ok;
} catch {
return false;
}
}
}
+31 -2
View File
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import { generateId } from "../../../apps/web/src/lib/utils";
import { afterEach, describe, expect, it, vi } from "vitest";
import { copyToClipboard, generateId } from "../../../apps/web/src/lib/utils";
describe("generateId", () => {
it("returns a valid UUID v4 string", () => {
@@ -13,3 +13,32 @@ describe("generateId", () => {
expect(ids.size).toBe(100);
});
});
describe("copyToClipboard", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("returns true when clipboard API succeeds", async () => {
Object.assign(navigator, {
clipboard: { writeText: vi.fn().mockResolvedValue(undefined) },
});
expect(await copyToClipboard("hello")).toBe(true);
expect(navigator.clipboard.writeText).toHaveBeenCalledWith("hello");
});
it("falls back to execCommand when clipboard API fails", async () => {
Object.assign(navigator, { clipboard: undefined });
document.execCommand = vi.fn().mockReturnValue(true);
expect(await copyToClipboard("hello")).toBe(true);
expect(document.execCommand).toHaveBeenCalledWith("copy");
});
it("returns false when both approaches fail", async () => {
Object.assign(navigator, { clipboard: undefined });
document.execCommand = vi.fn().mockImplementation(() => {
throw new Error("not supported");
});
expect(await copyToClipboard("hello")).toBe(false);
});
});