Files
FastGPT/packages/web/hooks/useCopyData.tsx
Archer aa55f059d4 perf: chat history api;perf: full text error (#4852)
* perf: chat history api

* perf: i18n

* perf: full text
2025-05-20 22:31:32 +08:00

98 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useTranslation } from 'next-i18next';
import { useToast } from './useToast';
import { useCallback } from 'react';
import MyModal from '../components/common/MyModal';
import React from 'react';
import { Box, ModalBody } from '@chakra-ui/react';
import Tag from '../components/common/Tag';
import { useCommonStore } from '../store/useCommonStore';
/**
* copy text data
*/
export const useCopyData = () => {
const { t } = useTranslation();
const { toast } = useToast();
const { setCopyContent } = useCommonStore();
const copyData = useCallback(
async (
data: string,
title: string | null | undefined = t('common:copy_successful'),
duration = 1000
) => {
data = data.trim();
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(data);
if (title) {
toast({
title,
status: 'success',
duration
});
}
} else {
let textArea = document.createElement('textarea');
textArea.value = data;
// 使text area不在viewport同时设置不可见
textArea.style.position = 'absolute';
// @ts-ignore
textArea.style.opacity = 0;
textArea.style.left = '-999999px';
textArea.style.top = '-999999px';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
await new Promise((res, rej) => {
document.execCommand('copy') ? res('') : rej();
textArea.remove();
}).then(() => {
if (title) {
toast({
title,
status: 'success',
duration
});
}
});
}
} catch (error) {
setCopyContent(data);
}
},
[setCopyContent, t, toast]
);
return {
copyData
};
};
export const ManualCopyModal = () => {
const { t } = useTranslation();
const { copyContent, setCopyContent } = useCommonStore();
return (
<MyModal
isOpen={!!copyContent}
iconSrc="copy"
iconColor="primary.600"
title={t('common:Copy')}
maxW={['90vw', '500px']}
w={'100%'}
onClose={() => setCopyContent(undefined)}
>
<ModalBody>
<Tag w={'100%'} colorSchema="blue">
{t('common:can_copy_content_tip')}
</Tag>
<Box mt={3} borderRadius={'md'} p={3} border={'base'} userSelect={'all'}>
{copyContent}
</Box>
</ModalBody>
</MyModal>
);
};