All files / hooks/use-copy-to-clipboard/src useCopyToClipboard.ts

94.36% Statements 67/71
83.33% Branches 20/24
100% Functions 8/8
95.65% Lines 66/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246                                                                                          8x       8x 8x     8x   8x 8x   8x     8x 8x     8x   8x 8x 8x         8x 8x                                                                                             76x   76x 76x         76x 76x 76x     76x 76x 76x         76x     76x 104x 22x 22x         76x 38x 38x 38x 38x             76x   30x   29x 29x       30x 30x 28x 6x 6x       29x         76x     37x     37x 1x     1x 1x     36x   36x       35x     1x 1x           29x     7x 7x 7x 1x             6x     6x     7x 7x 7x           76x    
import { useCallback, useEffect, useRef, useState } from "react";
 
/**
 * Options for useCopyToClipboard hook
 */
export interface UseCopyToClipboardOptions {
  /**
   * Time in milliseconds before the copied state resets to null.
   * Set to 0 to disable auto-reset.
   * @default 2000
   */
  timeout?: number;
  /**
   * Callback function called when copy succeeds
   * @param text - The text that was copied
   */
  onSuccess?: (text: string) => void;
  /**
   * Callback function called when copy fails
   * @param error - The error that occurred
   */
  onError?: (error: Error) => void;
}
 
/**
 * Type for the copy function
 */
export type CopyFn = (text: string) => Promise<boolean>;
 
/**
 * Return type for useCopyToClipboard hook
 * Tuple format: [copiedText, copy]
 */
export type UseCopyToClipboardReturn = [
  copiedText: string | null,
  copy: CopyFn
];
 
/**
 * Fallback copy function for browsers that don't support the Clipboard API
 * @param text - Text to copy to clipboard
 * @returns Whether the copy was successful
 */
function fallbackCopyToClipboard(text: string): boolean {
  // Check if we're in a browser environment
  Iif (typeof document === "undefined") {
    return false;
  }
 
  const textarea = document.createElement("textarea");
  textarea.value = text;
 
  // Make the textarea invisible but still functional
  textarea.style.cssText =
    "position:fixed;left:-9999px;top:-9999px;opacity:0;pointer-events:none";
  textarea.setAttribute("readonly", "");
  textarea.setAttribute("aria-hidden", "true");
 
  document.body.appendChild(textarea);
 
  // Select the text
  textarea.focus();
  textarea.select();
 
  // For mobile devices
  textarea.setSelectionRange(0, text.length);
 
  let success = false;
  try {
    success = document.execCommand("copy");
  } catch {
    success = false;
  }
 
  document.body.removeChild(textarea);
  return success;
}
 
/**
 * Copies text to clipboard using the Clipboard API with fallback support.
 * Returns the copied text (or null if not copied) and a copy function.
 *
 * @param options - Configuration options for the hook
 * @returns Tuple of [copiedText, copy]
 *
 * @example
 * ```tsx
 * function CopyButton() {
 *   const [copiedText, copy] = useCopyToClipboard();
 *
 *   return (
 *     <button onClick={() => copy("Hello World")}>
 *       {copiedText ? "Copied!" : "Copy"}
 *     </button>
 *   );
 * }
 * ```
 *
 * @example
 * ```tsx
 * // With custom timeout
 * const [copiedText, copy] = useCopyToClipboard({ timeout: 3000 });
 * ```
 *
 * @example
 * ```tsx
 * // With callbacks
 * const [copiedText, copy] = useCopyToClipboard({
 *   onSuccess: (text) => console.log(`Copied: ${text}`),
 *   onError: (error) => console.error(`Failed to copy: ${error.message}`),
 * });
 * ```
 *
 * @example
 * ```tsx
 * // Disable auto-reset
 * const [copiedText, copy] = useCopyToClipboard({ timeout: 0 });
 * ```
 */
export function useCopyToClipboard(
  options: UseCopyToClipboardOptions = {}
): UseCopyToClipboardReturn {
  const { timeout = 2000, onSuccess, onError } = options;
 
  const [copiedText, setCopiedText] = useState<string | null>(null);
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(
    undefined
  );
 
  // Store callbacks in refs to avoid dependency issues
  const onSuccessRef = useRef(onSuccess);
  const onErrorRef = useRef(onError);
  const timeoutValueRef = useRef(timeout);
 
  // Update refs when options change
  onSuccessRef.current = onSuccess;
  onErrorRef.current = onError;
  timeoutValueRef.current = timeout;
 
  // Mounted flag — re-armed on (re-)mount so StrictMode's mount→unmount→mount
  // double-invoke does not leave it stuck at `false`. Guards post-await state
  // updates and timer scheduling that would otherwise run after unmount.
  const mountedRef = useRef(true);
 
  // Clear the pending auto-reset timer, if any.
  const clearResetTimer = useCallback(() => {
    if (timeoutRef.current !== undefined) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = undefined;
    }
  }, []);
 
  // Cleanup timeout on unmount + maintain the mounted flag.
  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
      clearResetTimer();
    };
  }, [clearResetTimer]);
 
  // Mark the copy as succeeded: update state, fire onSuccess, and (re)schedule
  // the auto-reset. Skips all state work once unmounted so a copy() resolving
  // after unmount never touches state or leaks a timer the cleanup can't clear.
  const commitSuccess = useCallback(
    (text: string): boolean => {
      if (!mountedRef.current) return true;
 
      setCopiedText(text);
      onSuccessRef.current?.(text);
 
      // Supersede any in-flight reset timer (e.g. from an overlapping copy)
      // right at the point of scheduling, so the latest copy always wins.
      clearResetTimer();
      if (timeoutValueRef.current > 0) {
        timeoutRef.current = setTimeout(() => {
          setCopiedText(null);
          timeoutRef.current = undefined;
        }, timeoutValueRef.current);
      }
 
      return true;
    },
    [clearResetTimer]
  );
 
  const copy: CopyFn = useCallback(
    async (text: string): Promise<boolean> => {
      // Clear any existing timeout
      clearResetTimer();
 
      // Check for SSR
      if (typeof window === "undefined") {
        const error = new Error(
          "Clipboard is not available in this environment"
        );
        onErrorRef.current?.(error);
        return false;
      }
 
      try {
        // Try the modern Clipboard API first
        if (
          navigator.clipboard &&
          typeof navigator.clipboard.writeText === "function"
        ) {
          await navigator.clipboard.writeText(text);
        } else {
          // Fall back to execCommand
          const success = fallbackCopyToClipboard(text);
          Iif (!success) {
            throw new Error("Failed to copy text using fallback method");
          }
        }
 
        // Success
        return commitSuccess(text);
      } catch (err) {
        // Try fallback if Clipboard API failed
        try {
          const success = fallbackCopyToClipboard(text);
          if (success) {
            return commitSuccess(text);
          }
        } catch {
          // Fallback also failed
        }
 
        // Both methods failed
        Iif (!mountedRef.current) return false;
 
        const error =
          err instanceof Error
            ? err
            : new Error("Failed to copy text to clipboard");
        setCopiedText(null);
        onErrorRef.current?.(error);
        return false;
      }
    },
    [clearResetTimer, commitSuccess]
  );
 
  return [copiedText, copy];
}