useCopyClick.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
  2. function adopt(value) {
  3. return value instanceof P ? value : new P(function (resolve) {
  4. resolve(value);
  5. });
  6. }
  7. return new (P || (P = Promise))(function (resolve, reject) {
  8. function fulfilled(value) {
  9. try {
  10. step(generator.next(value));
  11. } catch (e) {
  12. reject(e);
  13. }
  14. }
  15. function rejected(value) {
  16. try {
  17. step(generator["throw"](value));
  18. } catch (e) {
  19. reject(e);
  20. }
  21. }
  22. function step(result) {
  23. result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
  24. }
  25. step((generator = generator.apply(thisArg, _arguments || [])).next());
  26. });
  27. };
  28. import * as React from 'react';
  29. import copy from 'copy-to-clipboard';
  30. import useEvent from "rc-util/es/hooks/useEvent";
  31. import toList from '../../_util/toList';
  32. const useCopyClick = ({
  33. copyConfig,
  34. children
  35. }) => {
  36. const [copied, setCopied] = React.useState(false);
  37. const [copyLoading, setCopyLoading] = React.useState(false);
  38. const copyIdRef = React.useRef(null);
  39. const cleanCopyId = () => {
  40. if (copyIdRef.current) {
  41. clearTimeout(copyIdRef.current);
  42. }
  43. };
  44. const copyOptions = {};
  45. if (copyConfig.format) {
  46. copyOptions.format = copyConfig.format;
  47. }
  48. React.useEffect(() => cleanCopyId, []);
  49. // Keep copy action up to date
  50. const onClick = useEvent(e => __awaiter(void 0, void 0, void 0, function* () {
  51. var _a;
  52. e === null || e === void 0 ? void 0 : e.preventDefault();
  53. e === null || e === void 0 ? void 0 : e.stopPropagation();
  54. setCopyLoading(true);
  55. try {
  56. const text = typeof copyConfig.text === 'function' ? yield copyConfig.text() : copyConfig.text;
  57. copy(text || toList(children, true).join('') || '', copyOptions);
  58. setCopyLoading(false);
  59. setCopied(true);
  60. // Trigger tips update
  61. cleanCopyId();
  62. copyIdRef.current = setTimeout(() => {
  63. setCopied(false);
  64. }, 3000);
  65. (_a = copyConfig.onCopy) === null || _a === void 0 ? void 0 : _a.call(copyConfig, e);
  66. } catch (error) {
  67. setCopyLoading(false);
  68. throw error;
  69. }
  70. }));
  71. return {
  72. copied,
  73. copyLoading,
  74. onClick
  75. };
  76. };
  77. export default useCopyClick;