forked from Lilly-Protocol/lily-frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy-to-clipboard.ts
More file actions
49 lines (44 loc) · 1.34 KB
/
Copy pathcopy-to-clipboard.ts
File metadata and controls
49 lines (44 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
"use client";
export interface CopyToClipboardOptions {
/** Duration in ms to wait before resetting the copied state */
timeout?: number;
/** Callback invoked on successful copy */
onSuccess?: () => void;
/** Callback invoked if copy fails */
onError?: (error: unknown) => void;
}
export interface CopyToClipboardResult {
success: boolean;
error?: unknown;
}
/**
* Copies text to the clipboard with fallback support.
* Returns a result object indicating success or failure.
*/
export async function copyToClipboard(
text: string,
options: CopyToClipboardOptions = {},
): Promise<CopyToClipboardResult> {
const { onSuccess, onError } = options;
try {
if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
} else {
// Fallback for older browsers or non-secure contexts
const textarea = document.createElement("textarea");
textarea.value = text;
textarea.style.position = "fixed";
textarea.style.left = "-9999px";
textarea.style.opacity = "0";
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
}
onSuccess?.();
return { success: true };
} catch (error) {
onError?.(error);
return { success: false, error };
}
}