(message, setMessage, onMessageSend, saveMessages)
| 5 | import { ERROR_MESSAGES } from '../constants/playground.constants'; |
| 6 | |
| 7 | export const useMessageActions = (message, setMessage, onMessageSend, saveMessages) => { |
| 8 | const { t } = useTranslation(); |
| 9 | |
| 10 | // 复制消息 |
| 11 | const handleMessageCopy = useCallback((targetMessage) => { |
| 12 | const textToCopy = getTextContent(targetMessage); |
| 13 | |
| 14 | if (!textToCopy) { |
| 15 | Toast.warning({ |
| 16 | content: t(ERROR_MESSAGES.NO_TEXT_CONTENT), |
| 17 | duration: 2, |
| 18 | }); |
| 19 | return; |
| 20 | } |
| 21 | |
| 22 | const copyToClipboard = async (text) => { |
| 23 | if (navigator.clipboard?.writeText) { |
| 24 | try { |
| 25 | await navigator.clipboard.writeText(text); |
| 26 | Toast.success({ |
| 27 | content: t('消息已复制到剪贴板'), |
| 28 | duration: 2, |
| 29 | }); |
| 30 | } catch (err) { |
| 31 | console.error('Clipboard API 复制失败:', err); |
| 32 | fallbackCopy(text); |
| 33 | } |
| 34 | } else { |
| 35 | fallbackCopy(text); |
| 36 | } |
| 37 | }; |
| 38 | |
| 39 | const fallbackCopy = (text) => { |
| 40 | try { |
| 41 | const textArea = document.createElement('textarea'); |
| 42 | textArea.value = text; |
| 43 | textArea.style.cssText = ` |
| 44 | position: fixed; |
| 45 | top: -9999px; |
| 46 | left: -9999px; |
| 47 | opacity: 0; |
| 48 | pointer-events: none; |
| 49 | z-index: -1; |
| 50 | `; |
| 51 | textArea.setAttribute('readonly', ''); |
| 52 | |
| 53 | document.body.appendChild(textArea); |
| 54 | textArea.select(); |
| 55 | textArea.setSelectionRange(0, text.length); |
| 56 | |
| 57 | const successful = document.execCommand('copy'); |
| 58 | document.body.removeChild(textArea); |
| 59 | |
| 60 | if (successful) { |
| 61 | Toast.success({ |
| 62 | content: t('消息已复制到剪贴板'), |
| 63 | duration: 2, |
| 64 | }); |
no test coverage detected