UNPKG

@wordpress/compose

Version:
69 lines (68 loc) 1.96 kB
// packages/compose/src/hooks/use-copy-on-click/index.ts import { useEffect, useState } from "@wordpress/element"; import deprecated from "@wordpress/deprecated"; import { clearSelection, copyToClipboard } from "../use-copy-to-clipboard/index.mjs"; function useCopyOnClick(ref, text, timeout = 4e3) { deprecated("wp.compose.useCopyOnClick", { since: "5.8", alternative: "wp.compose.useCopyToClipboard" }); const [hasCopied, setHasCopied] = useState(false); useEffect(() => { let isActive = true; let timeoutId; if (!ref.current) { return; } let targets; if (typeof ref.current === "string") { targets = typeof document !== "undefined" ? Array.from(document.querySelectorAll(ref.current)) : []; } else if ("length" in ref.current && typeof ref.current.length === "number") { targets = Array.from(ref.current); } else { targets = [ref.current]; } if (targets.length === 0) { return; } const handleClick = async (event) => { const trigger = event.currentTarget; if (!trigger) { return; } const success = await copyToClipboard( typeof text === "function" ? text() : text || "", trigger ); if (!isActive) { return; } if (success) { clearSelection(trigger); if (timeout) { setHasCopied(true); clearTimeout(timeoutId); timeoutId = setTimeout( () => setHasCopied(false), timeout ); } } }; for (const target of targets) { target.addEventListener("click", handleClick); } return () => { isActive = false; for (const target of targets) { target.removeEventListener("click", handleClick); } clearTimeout(timeoutId); }; }, [ref, text, timeout]); return hasCopied; } export { useCopyOnClick as default }; //# sourceMappingURL=index.mjs.map