/** * 剪贴板工具函数 */ import { buildRetrieveUrl, buildWgetCommand } from '@/utils/share-url' type CopyNotifyType = 'success' | 'error' interface CopyOptions { successMsg?: string errorMsg?: string showMsg?: boolean notify?: (message: string, type: CopyNotifyType) => void } /** * 复制文本到剪贴板 * @param text 要复制的文本 * @param options 配置选项 * @returns Promise 是否复制成功 */ export const copyToClipboard = async ( text: string, options: CopyOptions = {} ): Promise => { const { successMsg = '复制成功', errorMsg = '复制失败,请手动复制', showMsg = true, notify } = options const showCopyMessage = (message: string, type: CopyNotifyType) => { if (showMsg) { notify?.(message, type) } } const showManualCopyDialog = () => { window.prompt('复制下面内容', text) } try { if (navigator.clipboard && window.isSecureContext) { try { await navigator.clipboard.writeText(text) showCopyMessage(successMsg, 'success') return true } catch { // Continue to the DOM fallback. } } const textarea = document.createElement('textarea') textarea.value = text textarea.setAttribute('readonly', '') textarea.style.cssText = 'position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1;' document.body.appendChild(textarea) textarea.focus() textarea.select() textarea.setSelectionRange(0, textarea.value.length) let success = false try { success = document.execCommand('copy') } finally { document.body.removeChild(textarea) } if (success) { showCopyMessage(successMsg, 'success') return true } showManualCopyDialog() showCopyMessage('已打开手动复制窗口', 'error') return false } catch (err) { console.error('复制失败:', err) showManualCopyDialog() showCopyMessage(errorMsg, 'error') return false } } /** * 生成并复制取件链接 * @param code 取件码 * @returns Promise 是否复制成功 */ export const copyRetrieveLink = async ( code: string, options: Pick = {} ): Promise => { const link = buildRetrieveUrl(code) return copyToClipboard(link, { successMsg: '取件链接已复制到剪贴板', errorMsg: '复制失败,请手动复制取件链接', ...options }) } /** * 复制取件码 * @param code 取件码 * @returns Promise 是否复制成功 */ export const copyRetrieveCode = async ( code: string, options: Pick = {} ): Promise => { return copyToClipboard(code, { successMsg: '取件码已复制到剪贴板', errorMsg: '复制失败,请手动复制取件码', ...options }) } export const copyWgetCommand = ( retrieveCode: string, fileName: string, options: Pick = {} ) => { const command = buildWgetCommand(retrieveCode, fileName) void copyToClipboard(command, { successMsg: '命令已复制到剪贴板', errorMsg: '复制失败,请手动复制命令', ...options }) }