ant-design/components/typography/hooks/useCopyClick.ts
EmilyyyLiu a339f81c83
feat: V6 abandons copy-to-clipboard dependency (#53427)
* feat: 用原生方法重写copy

* feat: 优化copy方法,并修改test

* feat: 优化copy方法,并修改test

* feat: 修改copy逻辑,并恢复使用到的单测

* 调整格式。恢复不需要改动的格式

* 控制台提示使用util封装的

---------

Co-authored-by: 刘欢 <lh01217311@antgroup.com>
2025-04-09 16:24:47 +08:00

68 lines
1.6 KiB
TypeScript

import * as React from 'react';
import useEvent from '@rc-component/util/lib/hooks/useEvent';
import copy from '../../_util/copy';
import toList from '../../_util/toList';
import type { CopyConfig } from '../Base';
const useCopyClick = ({
copyConfig,
children,
}: {
copyConfig: CopyConfig;
children?: React.ReactNode;
}) => {
const [copied, setCopied] = React.useState(false);
const [copyLoading, setCopyLoading] = React.useState(false);
const copyIdRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const cleanCopyId = () => {
if (copyIdRef.current) {
clearTimeout(copyIdRef.current);
}
};
const copyOptions: Pick<CopyConfig, 'format'> = {};
if (copyConfig.format) {
copyOptions.format = copyConfig.format;
}
React.useEffect(() => cleanCopyId, []);
// Keep copy action up to date
const onClick = useEvent(async (e?: React.MouseEvent<HTMLButtonElement>) => {
e?.preventDefault();
e?.stopPropagation();
setCopyLoading(true);
try {
const text =
typeof copyConfig.text === 'function' ? await copyConfig.text() : copyConfig.text;
copy(text || toList(children, true).join('') || '', copyOptions);
setCopyLoading(false);
setCopied(true);
// Trigger tips update
cleanCopyId();
copyIdRef.current = setTimeout(() => {
setCopied(false);
}, 3000);
copyConfig.onCopy?.(e);
} catch (error) {
setCopyLoading(false);
throw error;
}
});
return {
copied,
copyLoading,
onClick,
};
};
export default useCopyClick;