@wordpress/compose
Version:
WordPress higher-order components (HOCs).
44 lines (43 loc) • 1.26 kB
JavaScript
// packages/compose/src/hooks/use-copy-on-click/index.js
import Clipboard from "clipboard";
import { useRef, useEffect, useState } from "@wordpress/element";
import deprecated from "@wordpress/deprecated";
function useCopyOnClick(ref, text, timeout = 4e3) {
deprecated("wp.compose.useCopyOnClick", {
since: "5.8",
alternative: "wp.compose.useCopyToClipboard"
});
const clipboardRef = useRef();
const [hasCopied, setHasCopied] = useState(false);
useEffect(() => {
let timeoutId;
if (!ref.current) {
return;
}
clipboardRef.current = new Clipboard(ref.current, {
text: () => typeof text === "function" ? text() : text
});
clipboardRef.current.on("success", ({ clearSelection, trigger }) => {
clearSelection();
if (trigger) {
trigger.focus();
}
if (timeout) {
setHasCopied(true);
clearTimeout(timeoutId);
timeoutId = setTimeout(() => setHasCopied(false), timeout);
}
});
return () => {
if (clipboardRef.current) {
clipboardRef.current.destroy();
}
clearTimeout(timeoutId);
};
}, [text, timeout, setHasCopied]);
return hasCopied;
}
export {
useCopyOnClick as default
};
//# sourceMappingURL=index.js.map