Open History to see the last commit
1import * as React from "react";
2
3export function useCopyToClipboard<TContext = void>({
4 timeout = 2000,
5 onCopy,
6 onError,
7}: {
8 timeout?: number;
9 onCopy?: (ctx: TContext) => void;
10 onError?: (error: Error, ctx: TContext) => void;
11} = {}): { copyToClipboard: (value: string, ctx: TContext) => void; isCopied: boolean } {
12 const [isCopied, setIsCopied] = React.useState(false);
13 const timeoutIdRef = React.useRef<NodeJS.Timeout | null>(null);
14 const onCopyRef = React.useRef(onCopy);
15 const onErrorRef = React.useRef(onError);
16 const timeoutRef = React.useRef(timeout);
17
18 onCopyRef.current = onCopy;
19 onErrorRef.current = onError;
20 timeoutRef.current = timeout;
21
22 const copyToClipboard = React.useCallback((value: string, ctx: TContext): void => {
23 if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
24 onErrorRef.current?.(new Error("Clipboard API unavailable."), ctx);
25 return;
26 }
27
28 if (!value) return;
29
30 navigator.clipboard.writeText(value).then(
31 () => {
32 if (timeoutIdRef.current) {
33 clearTimeout(timeoutIdRef.current);
34 }
35 setIsCopied(true);
36
37 onCopyRef.current?.(ctx);
38
39 if (timeoutRef.current !== 0) {
40 timeoutIdRef.current = setTimeout(() => {
41 setIsCopied(false);
42 timeoutIdRef.current = null;
43 }, timeoutRef.current);
44 }
45 },
46 (error) => {
47 if (onErrorRef.current) {
48 onErrorRef.current(error, ctx);
49 } else {
50 console.error(error);
51 }
52 },
53 );
54 }, []);
55
56 // Cleanup timeout on unmount
57 React.useEffect(() => {
58 return (): void => {
59 if (timeoutIdRef.current) {
60 clearTimeout(timeoutIdRef.current);
61 }
62 };
63 }, []);
64
65 return { copyToClipboard, isCopied };
66}