@gechiui/compose
Version:
GeChiUI higher-order components (HOCs).
94 lines (77 loc) • 2.87 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useCopyOnClick;
var _clipboard = _interopRequireDefault(require("clipboard"));
var _element = require("@gechiui/element");
var _deprecated = _interopRequireDefault(require("@gechiui/deprecated"));
/**
* External dependencies
*/
/**
* GeChiUI dependencies
*/
/* eslint-disable jsdoc/no-undefined-types */
/**
* Copies the text to the clipboard when the element is clicked.
*
* @deprecated
*
* @param {import('react').RefObject<string | Element | NodeListOf<Element>>} ref Reference with the element.
* @param {string|Function} text The text to copy.
* @param {number} [timeout] Optional timeout to reset the returned
* state. 4 seconds by default.
*
* @return {boolean} Whether or not the text has been copied. Resets after the
* timeout.
*/
function useCopyOnClick(ref, text) {
let timeout = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 4000;
/* eslint-enable jsdoc/no-undefined-types */
(0, _deprecated.default)('gc.compose.useCopyOnClick', {
since: '5.8',
alternative: 'gc.compose.useCopyToClipboard'
});
/** @type {import('react').MutableRefObject<Clipboard | undefined>} */
const clipboard = (0, _element.useRef)();
const [hasCopied, setHasCopied] = (0, _element.useState)(false);
(0, _element.useEffect)(() => {
/** @type {number | undefined} */
let timeoutId;
if (!ref.current) {
return;
} // Clipboard listens to click events.
clipboard.current = new _clipboard.default(ref.current, {
text: () => typeof text === 'function' ? text() : text
});
clipboard.current.on('success', _ref => {
let {
clearSelection,
trigger
} = _ref;
// Clearing selection will move focus back to the triggering button,
// ensuring that it is not reset to the body, and further that it is
// kept within the rendered node.
clearSelection(); // Handle ClipboardJS focus bug, see https://github.com/zenorocha/clipboard.js/issues/680
if (trigger) {
/** @type {HTMLElement} */
trigger.focus();
}
if (timeout) {
setHasCopied(true);
clearTimeout(timeoutId);
timeoutId = setTimeout(() => setHasCopied(false), timeout);
}
});
return () => {
if (clipboard.current) {
clipboard.current.destroy();
}
clearTimeout(timeoutId);
};
}, [text, timeout, setHasCopied]);
return hasCopied;
}
//# sourceMappingURL=index.js.map