UNPKG

@react-hook/copy

Version:
73 lines (52 loc) 2.85 kB
"use strict"; exports.__esModule = true; exports.default = void 0; var React = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("react")); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _ref2(copied) { return copied; } function useCopy(text) { const [copied, setCopied] = React.useState(false); const reset = React.useRef(() => setCopied(false)); // Resets 'copied' if text changes React.useEffect(() => reset.current, [text]); function _ref() { return setCopied(true); } function _ref3() { return setCopied(_ref2); } return { copied, copy: React.useCallback(() => copyToClipboard(text).then(_ref).catch(_ref3), [text]), reset: reset.current }; } /* istanbul ignore next */ function copyToClipboard(text) { // uses the Async Clipboard API when available. Requires a secure browing // context (i.e. HTTPS) if (navigator.clipboard) return navigator.clipboard.writeText(text); // puts the text to copy into a <span> const span = document.createElement('span'); span.textContent = text; // preserves consecutive spaces and newlines span.style.whiteSpace = 'pre'; // adds the <span> to the page document.body.appendChild(span); // makes a selection object representing the range of text selected by the user const selection = window.getSelection(); if (!selection) return Promise.reject(); const range = window.document.createRange(); selection.removeAllRanges(); range.selectNode(span); selection.addRange(range); // copies text to the clipboard try { window.document.execCommand('copy'); } catch (err) { return Promise.reject(); } // cleans up the dom element and selection selection.removeAllRanges(); window.document.body.removeChild(span); // the Async Clipboard API returns a promise that may reject with `undefined` // so we match that here for consistency return Promise.resolve(); } var _default = useCopy; exports.default = _default;