antd
Version:
An enterprise-class UI design language and React components implementation
44 lines • 1.19 kB
JavaScript
import * as React from 'react';
import { useDelayState, useEvent } from '@rc-component/util';
import copy from '../../_util/copy';
import { isFunction } from '../../_util/is';
import toList from '../../_util/toList';
const useCopyClick = ({
copyConfig,
children
}) => {
const [copied, setCopied] = useDelayState(false);
const [copyLoading, setCopyLoading] = React.useState(false);
const copyOptions = {};
if (copyConfig.format) {
copyOptions.format = copyConfig.format;
}
// Keep copy action up to date
const onClick = useEvent(async e => {
e?.preventDefault();
e?.stopPropagation();
setCopyLoading(true);
try {
const text = isFunction(copyConfig.text) ? await copyConfig.text() : copyConfig.text;
await copy(text || toList(children, {
skipEmpty: true
}).join('') || '', copyOptions);
setCopyLoading(false);
setCopied(true, true);
// Trigger tips update
setCopied(false, {
ms: 3000
});
copyConfig.onCopy?.(e);
} catch (error) {
setCopyLoading(false);
throw error;
}
});
return {
copied,
copyLoading,
onClick
};
};
export default useCopyClick;