@gechiui/compose
Version:
GeChiUI higher-order components (HOCs).
84 lines (70 loc) • 2.3 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useCopyToClipboard;
var _clipboard = _interopRequireDefault(require("clipboard"));
var _element = require("@gechiui/element");
var _useRefEffect = _interopRequireDefault(require("../use-ref-effect"));
/**
* External dependencies
*/
/**
* GeChiUI dependencies
*/
/**
* Internal dependencies
*/
/**
* @template T
* @param {T} value
* @return {import('react').RefObject<T>} The updated ref
*/
function useUpdatedRef(value) {
const ref = (0, _element.useRef)(value);
ref.current = value;
return ref;
}
/**
* Copies the given text to the clipboard when the element is clicked.
*
* @template {HTMLElement} TElementType
* @param {string | (() => string)} text The text to copy. Use a function if not
* already available and expensive to compute.
* @param {Function} onSuccess Called when to text is copied.
*
* @return {import('react').Ref<TElementType>} A ref to assign to the target element.
*/
function useCopyToClipboard(text, onSuccess) {
// Store the dependencies as refs and continuesly update them so they're
// fresh when the callback is called.
const textRef = useUpdatedRef(text);
const onSuccessRef = useUpdatedRef(onSuccess);
return (0, _useRefEffect.default)(node => {
// Clipboard listens to click events.
const clipboard = new _clipboard.default(node, {
text() {
return typeof textRef.current === 'function' ? textRef.current() : textRef.current || '';
}
});
clipboard.on('success', _ref => {
let {
clearSelection
} = _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
node.focus();
if (onSuccessRef.current) {
onSuccessRef.current();
}
});
return () => {
clipboard.destroy();
};
}, []);
}
//# sourceMappingURL=index.js.map