@mui/internal-docs-infra
Version:
MUI Infra - internal documentation creation tools.
61 lines • 2.24 kB
JavaScript
import _regenerator from "@babel/runtime/helpers/esm/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import * as React from 'react';
import copyToClipboard from 'clipboard-copy';
export function useCopier(contents, opts) {
var _ref = opts || {},
onCopied = _ref.onCopied,
onError = _ref.onError,
onClick = _ref.onClick,
_ref$timeout = _ref.timeout,
timeout = _ref$timeout === void 0 ? 2000 : _ref$timeout;
var copyTimeoutRef = React.useRef(undefined);
var _React$useState = React.useState(false),
_React$useState2 = _slicedToArray(_React$useState, 2),
recentlySuccessful = _React$useState2[0],
setRecentlySuccessful = _React$useState2[1];
var copy = React.useCallback(/*#__PURE__*/function () {
var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(event) {
var content, _t;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
clearTimeout(copyTimeoutRef.current);
setRecentlySuccessful(false);
_context.p = 1;
content = typeof contents === 'function' ? contents() : contents;
if (!content) {
_context.n = 2;
break;
}
_context.n = 2;
return copyToClipboard(content);
case 2:
onCopied == null || onCopied();
_context.n = 4;
break;
case 3:
_context.p = 3;
_t = _context.v;
onError == null || onError(_t);
case 4:
onClick == null || onClick(event);
copyTimeoutRef.current = setTimeout(function () {
clearTimeout(copyTimeoutRef.current);
setRecentlySuccessful(false);
}, timeout);
case 5:
return _context.a(2);
}
}, _callee, null, [[1, 3]]);
}));
return function (_x) {
return _ref2.apply(this, arguments);
};
}(), [contents, timeout, onCopied, onError, onClick]);
return {
copy: copy,
recentlySuccessful: recentlySuccessful
};
}