- Add optional chaining check for navigator.clipboard - Fallback to textarea + execCommand for SSR/non-HTTPS contexts - Fixes TypeError when clipboard API is unavailable Co-authored-by: Дмитрий Золотарь <d.zolotar@solarl.ru>
44 lines
1.2 KiB
JavaScript
44 lines
1.2 KiB
JavaScript
"use client";
|
|
|
|
import { useState, useCallback, useRef } from "react";
|
|
|
|
/**
|
|
* Hook for copy to clipboard with feedback
|
|
* @param {number} resetDelay - Time in ms before resetting copied state (default: 2000)
|
|
* @returns {{ copied: string|null, copy: (text: string, id?: string) => void }}
|
|
*/
|
|
export function useCopyToClipboard(resetDelay = 2000) {
|
|
const [copied, setCopied] = useState(null);
|
|
const timeoutRef = useRef(null);
|
|
|
|
const copy = useCallback((text, id = "default") => {
|
|
const write = async () => {
|
|
if (navigator?.clipboard?.writeText) {
|
|
await navigator.clipboard.writeText(text);
|
|
} else {
|
|
const textarea = document.createElement("textarea");
|
|
textarea.value = text;
|
|
textarea.style.position = "fixed";
|
|
textarea.style.opacity = "0";
|
|
document.body.appendChild(textarea);
|
|
textarea.select();
|
|
document.execCommand("copy");
|
|
document.body.removeChild(textarea);
|
|
}
|
|
};
|
|
write();
|
|
setCopied(id);
|
|
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
}
|
|
|
|
timeoutRef.current = setTimeout(() => {
|
|
setCopied(null);
|
|
}, resetDelay);
|
|
}, [resetDelay]);
|
|
|
|
return { copied, copy };
|
|
}
|
|
|