File size: 1,136 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";

import { useState, useCallback, useRef } from "react";
import { copyToClipboard } from "@/shared/utils/clipboard";

/**

 * Hook for copy to clipboard with feedback.

 * Uses shared copyToClipboard utility that works on both HTTP and HTTPS.

 * @param {number} resetDelay - Time in ms before resetting copied state (default: 2000)

 * @returns {{ copied: string|null, copy: (text: string, id?: string) => Promise<boolean> }}

 */
export function useCopyToClipboard(resetDelay = 2000) {
  const [copied, setCopied] = useState<string | null>(null);
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const copy = useCallback(
    async (text: string, id = "default"): Promise<boolean> => {
      const success = await copyToClipboard(text);

      if (success) {
        setCopied(id);

        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current);
        }

        timeoutRef.current = setTimeout(() => {
          setCopied(null);
        }, resetDelay);
      }

      return success;
    },
    [resetDelay]
  );

  return { copied, copy };
}