Open History to see the last commit
1import * as React from "react";
2import * as Schema from "effect/Schema";
3
4export class ClipboardApiUnavailableError extends Schema.TaggedErrorClass<ClipboardApiUnavailableError>()(
5 "ClipboardApiUnavailableError",
6 {
7 target: Schema.String,
8 },
9) {
10 override get message(): string {
11 return `Clipboard API is unavailable while copying ${this.target}.`;
12 }
13}
14
15export class ClipboardWriteError extends Schema.TaggedErrorClass<ClipboardWriteError>()(
16 "ClipboardWriteError",
17 {
18 target: Schema.String,
19 cause: Schema.Defect(),
20 },
21) {
22 override get message(): string {
23 return `Failed to copy ${this.target} to the clipboard.`;
24 }
25}
26
27export async function writeTextToClipboard(value: string, target = "text") {
28 if (
29 typeof window === "undefined" ||
30 typeof navigator === "undefined" ||
31 !navigator.clipboard?.writeText
32 ) {
33 throw new ClipboardApiUnavailableError({
34 target,
35 });
36 }
37
38 if (!value) return false;
39
40 try {
41 await navigator.clipboard.writeText(value);
42 return true;
43 } catch (cause) {
44 throw new ClipboardWriteError({
45 target,
46 cause,
47 });
48 }
49}
50
51export function useCopyToClipboard<TContext = void>({
52 timeout = 2000,
53 target = "text",
54 onCopy,
55 onError,
56}: {
57 timeout?: number;
58 target?: string;
59 onCopy?: (ctx: TContext) => void;
60 onError?: (error: Error, ctx: TContext) => void;
61} = {}): { copyToClipboard: (value: string, ctx: TContext) => void; isCopied: boolean } {
62 const [isCopied, setIsCopied] = React.useState(false);
63 const timeoutIdRef = React.useRef<NodeJS.Timeout | null>(null);
64 const onCopyRef = React.useRef(onCopy);
65 const onErrorRef = React.useRef(onError);
66 const targetRef = React.useRef(target);
67 const timeoutRef = React.useRef(timeout);
68
69 onCopyRef.current = onCopy;
70 onErrorRef.current = onError;
71 targetRef.current = target;
72 timeoutRef.current = timeout;
73
74 const copyToClipboard = React.useCallback((value: string, ctx: TContext): void => {
75 void writeTextToClipboard(value, targetRef.current).then(
76 (didCopy) => {
77 if (!didCopy) return;
78 if (timeoutIdRef.current) {
79 clearTimeout(timeoutIdRef.current);
80 }
81 setIsCopied(true);
82
83 onCopyRef.current?.(ctx);
84
85 if (timeoutRef.current !== 0) {
86 timeoutIdRef.current = setTimeout(() => {
87 setIsCopied(false);
88 timeoutIdRef.current = null;
89 }, timeoutRef.current);
90 }
91 },
92 (error) => {
93 console.error(error);
94 onErrorRef.current?.(error, ctx);
95 },
96 );
97 }, []);
98
99 // Cleanup timeout on unmount
100 React.useEffect(() => {
101 return (): void => {
102 if (timeoutIdRef.current) {
103 clearTimeout(timeoutIdRef.current);
104 }
105 };
106 }, []);
107
108 return { copyToClipboard, isCopied };
109}