UNPKG

@wordpress/compose

Version:
36 lines (35 loc) 992 B
// packages/compose/src/hooks/use-copy-to-clipboard/index.js import Clipboard from "clipboard"; import { useRef, useLayoutEffect } from "@wordpress/element"; import useRefEffect from "../use-ref-effect"; function useUpdatedRef(value) { const ref = useRef(value); useLayoutEffect(() => { ref.current = value; }, [value]); return ref; } function useCopyToClipboard(text, onSuccess) { const textRef = useUpdatedRef(text); const onSuccessRef = useUpdatedRef(onSuccess); return useRefEffect((node) => { const clipboard = new Clipboard(node, { text() { return typeof textRef.current === "function" ? textRef.current() : textRef.current || ""; } }); clipboard.on("success", ({ clearSelection }) => { clearSelection(); if (onSuccessRef.current) { onSuccessRef.current(); } }); return () => { clipboard.destroy(); }; }, []); } export { useCopyToClipboard as default }; //# sourceMappingURL=index.js.map