ant-design/components/typography/hooks/useCopyClick.ts
叶枫 8cc1d30351
feat: copy support async (#48123)
* feat: copy support async

* feat: add test

* feat: doc

* feat: snap

* feat: add loading

* feat: 恢复 try

* feat: 判断是否是 Error

* feat: throw error

* feat: 为了醋包了饺子

* feat: remove code

* feat: add loading test

* fix: test

* fix: icon import way

* chore: improve test case code

* chore: improve test case code

---------

Co-authored-by: afc163 <afc163@gmail.com>
2024-03-29 13:20:02 +08:00

63 lines
1.4 KiB
TypeScript

import * as React from 'react';
import copy from 'copy-to-clipboard';
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, []);
return {
copied,
copyLoading,
onClick: async (e?: React.MouseEvent<HTMLDivElement>) => {
e?.preventDefault();
e?.stopPropagation();
setCopyLoading(true);
try {
const text =
typeof copyConfig.text === 'function' ? await copyConfig.text() : copyConfig.text;
copy(text || String(children) || '', copyOptions);
setCopyLoading(false);
setCopied(true);
// Trigger tips update
cleanCopyId();
copyIdRef.current = setTimeout(() => {
setCopied(false);
}, 3000);
copyConfig.onCopy?.(e);
} catch (error) {
setCopyLoading(false);
throw error;
}
},
};
};
export default useCopyClick;