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 | 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 65x 65x 65x 65x 65x 65x 65x 65x 65x 65x 33x 33x 17x 65x 31x 1x 1x 31x 31x 31x 30x 1x 1x 25x 25x 31x 24x 5x 5x 25x 6x 6x 6x 1x 1x 1x 1x 1x 5x 6x 6x 6x 65x | 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;
// Cleanup timeout on unmount
useEffect(() => {
return () => {
if (timeoutRef.current !== undefined) {
clearTimeout(timeoutRef.current);
}
};
}, []);
const copy: CopyFn = useCallback(async (text: string): Promise<boolean> => {
// Clear any existing timeout
if (timeoutRef.current !== undefined) {
clearTimeout(timeoutRef.current);
timeoutRef.current = undefined;
}
// Check for SSR
Iif (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
setCopiedText(text);
onSuccessRef.current?.(text);
// Set timeout for auto-reset if enabled
if (timeoutValueRef.current > 0) {
timeoutRef.current = setTimeout(() => {
setCopiedText(null);
timeoutRef.current = undefined;
}, timeoutValueRef.current);
}
return true;
} catch (err) {
// Try fallback if Clipboard API failed
try {
const success = fallbackCopyToClipboard(text);
if (success) {
setCopiedText(text);
onSuccessRef.current?.(text);
Eif (timeoutValueRef.current > 0) {
timeoutRef.current = setTimeout(() => {
setCopiedText(null);
timeoutRef.current = undefined;
}, timeoutValueRef.current);
}
return true;
}
} catch {
// Fallback also failed
}
// Both methods failed
const error =
err instanceof Error ? err : new Error("Failed to copy text to clipboard");
setCopiedText(null);
onErrorRef.current?.(error);
return false;
}
}, []);
return [copiedText, copy];
}
|