Files
shanxia2.0/web-admin/src/components/business/attachment-upload-field/index.vue
T
wuzilongandCursor 43e240ad6a feat(web-admin): add copy-to-clipboard for attachment images
Let users copy images next to download on shared attachment cards, preview toolbars, and list cells so they can paste into chat or docs without saving files first.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 23:18:34 +08:00

1431 lines
37 KiB
Vue
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.
<template>
<div
ref="rootRef"
class="attachment-upload"
:class="{
'attachment-upload--compact': compact && !useTiles,
'attachment-upload--readonly': compact && disabled && !useTiles,
'attachment-upload--tiles': useTiles,
'attachment-upload--drag-over': isDragOver && !disabled
}"
:tabindex="disabled ? undefined : 0"
@mouseenter="handlePointerEnter"
@mouseleave="handlePointerLeave"
@focusin="handlePointerEnter"
@focusout="handleFocusOut"
@dragenter.prevent="handleDragEnter"
@dragleave.prevent="handleDragLeave"
@dragover.prevent="handleDragOver"
@drop.prevent="handleDrop"
>
<ul v-if="useTiles" class="mp-crm-att-grid" aria-label="附件列表">
<li v-if="!disabled" class="att-item att-item--add">
<el-upload
ref="uploadRef"
class="att-upload"
:auto-upload="false"
:show-file-list="false"
:multiple="limit > 1"
:accept="accept"
@change="handleAttachmentChange"
>
<span class="att-add">
<span aria-hidden="true">+</span>
<small>{{ isDragOver ? '松开上传' : '上传' }}</small>
</span>
</el-upload>
</li>
<li
v-for="(file, index) in attachments"
:key="file.id || index"
class="att-item"
:class="{ 'is-uploading': file._uploading }"
>
<button
v-if="!disabled && !file._uploading"
type="button"
class="att-icon att-icon--del"
:aria-label="`删除附件:${file.fileName || '未命名附件'}`"
@click.stop="removeAttachment(index)"
>
<span aria-hidden="true">×</span>
</button>
<button
v-if="file.fileUrl && !file._uploading"
type="button"
class="att-icon att-icon--dl"
:aria-label="`下载附件:${file.fileName || '未命名附件'}`"
@click.stop="handleDownloadAttachment(file)"
>
<span aria-hidden="true">↓</span>
</button>
<button
v-if="file.fileUrl && !file._uploading"
type="button"
class="att-icon att-icon--copy"
:aria-label="
isImageFile(file)
? `复制图片:${file.fileName || '未命名附件'}`
: `复制链接:${file.fileName || '未命名附件'}`
"
:disabled="copyBusyId === (file.id || String(index))"
@click.stop="handleCopyAttachment(file)"
>
<span aria-hidden="true">⧉</span>
</button>
<button
class="att-preview"
type="button"
:disabled="!file.fileUrl || file._uploading"
@click="file.fileUrl ? handleAttachmentClick(file) : undefined"
>
<img
v-if="isImageFile(file) && file.fileUrl"
class="att-img"
:src="resolveFileUrl(file.fileUrl)"
:alt="file.fileName"
/>
<span v-else class="att-doc" :class="{ 'att-doc--word': isWordFile(file) }">
<strong>{{ getFileExtension(file.fileName) || 'FILE' }}</strong>
</span>
</button>
<span class="att-name">{{ file.fileName || '附件' }}</span>
<span v-if="file._uploading" class="att-uploading">上传中…</span>
</li>
</ul>
<div v-else class="attachment-list">
<el-upload
v-if="!disabled"
ref="uploadRef"
:auto-upload="false"
:show-file-list="false"
:multiple="limit > 1"
:accept="accept"
@change="handleAttachmentChange"
>
<div class="upload-card">
<el-icon :size="previewIconSize" color="#1ca851"><Plus /></el-icon>
<span class="upload-card-text">{{ isDragOver ? '松开上传' : '上传附件' }}</span>
</div>
</el-upload>
<div
v-for="(file, index) in attachments"
:key="file.id || index"
class="attachment-item"
:class="{ 'is-uploading': file._uploading }"
>
<div
class="attachment-preview"
:class="{ 'is-clickable': Boolean(file.fileUrl) }"
@click="file.fileUrl ? handleAttachmentClick(file) : undefined"
>
<template v-if="isImageFile(file) && file.fileUrl">
<img
:src="resolveFileUrl(file.fileUrl)"
:alt="file.fileName"
loading="lazy"
decoding="async"
/>
</template>
<template v-else-if="isImageFile(file) && !file.fileUrl">
<el-icon :size="previewIconSize" color="#94a3b8"><Loading /></el-icon>
</template>
<template v-else-if="isVideoFile(file)">
<div class="attachment-preview__icon attachment-preview__icon--video">
<el-icon :size="previewIconSize"><VideoPlay /></el-icon>
</div>
</template>
<template v-else>
<div
class="attachment-preview__icon"
:class="isPdfFile(file) ? 'attachment-preview__icon--pdf' : 'attachment-preview__icon--doc'"
>
<el-icon :size="previewIconSize"><Document /></el-icon>
<span v-if="getFileExtension(file.fileName)" class="attachment-preview__ext">
{{ getFileExtension(file.fileName) }}
</span>
</div>
</template>
<span v-if="getCategoryLabel(file)" class="attachment-preview__category">
{{ getCategoryLabel(file) }}
</span>
</div>
<button
v-if="compact && !disabled"
type="button"
class="attachment-compact-delete"
title="删除"
@click.stop="removeAttachment(index)"
>
<el-icon :size="12"><Delete /></el-icon>
</button>
<button
v-if="compact && disabled && file.fileUrl"
type="button"
class="attachment-compact-copy"
:title="isImageFile(file) ? '复制图片' : '复制链接'"
:disabled="copyBusyId === (file.id || String(index))"
@click.stop="handleCopyAttachment(file)"
>
<el-icon :size="12"><DocumentCopy /></el-icon>
</button>
<button
v-if="compact && disabled && file.fileUrl"
type="button"
class="attachment-compact-download"
title="下载"
@click.stop="handleDownloadAttachment(file)"
>
<el-icon :size="12"><Download /></el-icon>
</button>
<div class="attachment-footer">
<span class="attachment-name" :title="file.fileName">{{ file.fileName }}</span>
<div v-if="!disabled" class="attachment-actions">
<el-icon
class="action-btn"
:title="isImageFile(file) ? '复制图片' : '复制链接'"
@click="handleCopyAttachment(file)"
>
<DocumentCopy />
</el-icon>
<el-icon class="action-btn" title="下载" @click="handleDownloadAttachment(file)">
<Download />
</el-icon>
<el-icon
class="action-btn action-btn--danger"
title="删除"
@click="removeAttachment(index)"
>
<Delete />
</el-icon>
</div>
<div v-else class="attachment-actions">
<el-icon
class="action-btn"
:title="isImageFile(file) ? '复制图片' : '复制链接'"
@click="handleCopyAttachment(file)"
>
<DocumentCopy />
</el-icon>
<el-icon class="action-btn" title="下载" @click="handleDownloadAttachment(file)">
<Download />
</el-icon>
</div>
</div>
</div>
<slot name="beside" />
</div>
<span v-if="hint && !disabled && !compact" class="upload-hint">{{ hint }}</span>
<el-dialog
v-model="previewVisible"
:title="previewFile?.fileName || '附件预览'"
:class="{ 'attachment-upload-preview--mobile': useTiles }"
width="860px"
align-center
destroy-on-close
append-to-body
modal-class="order-module-dialog-mask"
@closed="handlePreviewClosed"
>
<div v-loading="previewLoading" class="preview-body">
<template v-if="previewFile && isImageFile(previewFile)">
<div class="preview-toolbar" :class="{ 'preview-toolbar--mp': isMpPreviewToolbar }">
<el-button :size="mpBtnSize" @click="rotatePreview(-90)">
<el-icon v-if="!isMpPreviewToolbar"><RefreshLeft /></el-icon>
左转
</el-button>
<el-button :size="mpBtnSize" @click="rotatePreview(90)">
<el-icon v-if="!isMpPreviewToolbar"><RefreshRight /></el-icon>
右转
</el-button>
<span class="preview-toolbar-sep" aria-hidden="true" />
<el-button
:size="mpBtnSize"
:disabled="previewZoom <= IMAGE_PREVIEW_ZOOM_MIN"
@click="nudgePreviewZoom(-1)"
>
<el-icon v-if="!isMpPreviewToolbar"><ZoomOut /></el-icon>
缩小
</el-button>
<el-button
:size="mpBtnSize"
:disabled="previewZoom >= IMAGE_PREVIEW_ZOOM_MAX"
@click="nudgePreviewZoom(1)"
>
<el-icon v-if="!isMpPreviewToolbar"><ZoomIn /></el-icon>
放大
</el-button>
<el-button :size="mpBtnSize" @click="resetPreviewZoomPan">
<el-icon v-if="!isMpPreviewToolbar"><Refresh /></el-icon>
重置
</el-button>
<span class="preview-toolbar-sep" aria-hidden="true" />
<el-button
:size="mpBtnSize"
:loading="previewCopyBusy"
:disabled="!previewFile?.fileUrl || previewCopyBusy"
@click="handleCopyPreviewImage"
>
<el-icon v-if="!isMpPreviewToolbar && !previewCopyBusy"><DocumentCopy /></el-icon>
复制
</el-button>
<span class="preview-status-chip">{{ previewStatusText }}</span>
</div>
<div
ref="previewStageRef"
class="preview-stage"
:class="{ 'is-dragging': previewDragging }"
title="滚轮缩放 · 按住拖拽平移"
@wheel.prevent="handlePreviewWheel"
@pointerdown="handlePreviewPointerDown"
@pointermove="handlePreviewPointerMove"
@pointerup="handlePreviewPointerUp"
@pointercancel="handlePreviewPointerUp"
>
<img
ref="previewImgRef"
:src="resolveFileUrl(previewFile.fileUrl)"
:alt="previewFile.fileName"
class="preview-stage-img"
:style="{ transform: previewTransformCss }"
@load="handlePreviewImageLoad"
draggable="false"
/>
</div>
</template>
<video
v-else-if="previewFile && isVideoFile(previewFile)"
:src="resolveFileUrl(previewFile.fileUrl)"
controls
class="preview-media"
/>
<iframe
v-else-if="previewFile && isPdfFile(previewFile) && previewPdfSrc"
:src="previewPdfSrc"
class="preview-media preview-media--iframe"
title="PDF 预览"
/>
<div
v-else-if="previewFile && isPdfFile(previewFile) && !previewLoading"
class="preview-fallback"
>
<el-icon :size="40" color="#94a3b8"><Document /></el-icon>
<p>PDF 暂无法在线预览,请使用下载查看。</p>
</div>
</div>
</el-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import {
Plus,
Loading,
VideoPlay,
Document,
DocumentCopy,
Download,
Delete,
RefreshLeft,
RefreshRight,
ZoomIn,
ZoomOut,
Refresh
} from '@element-plus/icons-vue'
import type { UploadFile, UploadInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { fetchUploadAttachment } from '@/api/admin'
import {
downloadAttachmentFile,
resolveAttachmentPreviewUrl
} from '@/utils/download-attachment'
import {
copyAttachmentImageToClipboard,
copyTextToClipboard
} from '@/utils/clipboard'
import { resolvePhotoDisplayUrl } from '@/utils/pl-photo'
import { buildAttachmentUploadFormData, type CrmUploadBizType } from '@/utils/crm-upload'
import {
IMAGE_PREVIEW_ZOOM_MIN,
IMAGE_PREVIEW_ZOOM_MAX,
IMAGE_PREVIEW_ZOOM_STEP,
clampPreviewZoom,
computeFitBaseScale,
buildPreviewTransformCss
} from '@/utils/image-preview-transform.js'
import { isMpWebviewPath } from '@/utils/mp-webview'
type AttachmentItem = {
id: string
fileName: string
fileUrl: string
fileType?: string
_uploading?: boolean
}
const props = withDefaults(
defineProps<{
modelValue?: string
folder?: string
limit?: number
accept?: string
hint?: string
disabled?: boolean
/** 紧凑模式:小缩略图,只读时隐藏文件名与操作栏 */
compact?: boolean
/** 附件 URL → 分类名称,用于查看态在缩略图上展示分类标签 */
categoryLabels?: Record<string, string>
/** CRM 等业务上传 bizType(与 folder 二选一或同时传) */
bizType?: CrmUploadBizType | string
}>(),
{
modelValue: '',
folder: 'crm/customer',
limit: 15,
accept: 'image/*,video/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar',
hint: '支持图片、视频、PDF、Word、Excel等文件;可拖拽或在此区域粘贴上传',
disabled: false,
compact: false,
categoryLabels: () => ({})
}
)
const emit = defineEmits<{
'update:modelValue': [value: string]
}>()
const route = useRoute()
const useTiles = computed(() => isMpWebviewPath(String(route.path || '')))
const isMpPreviewToolbar = computed(
() => props.compact || useTiles.value || isMpWebviewPath(String(route.path || ''))
)
const mpBtnSize = computed(() => (isMpPreviewToolbar.value ? 'small' : 'default'))
const rootRef = ref<HTMLElement>()
const uploadRef = ref<UploadInstance>()
const attachments = ref<AttachmentItem[]>([])
const previewVisible = ref(false)
const previewFile = ref<AttachmentItem | null>(null)
const previewPdfSrc = ref('')
const previewLoading = ref(false)
const previewStageRef = ref<HTMLElement>()
const previewImgRef = ref<HTMLImageElement>()
const previewAngle = ref(0)
const previewZoom = ref(1)
const previewOffsetX = ref(0)
const previewOffsetY = ref(0)
const previewDragging = ref(false)
const previewFitBase = ref(1)
const isPointerInside = ref(false)
const isDragOver = ref(false)
let dragEnterDepth = 0
let previewDragStartX = 0
let previewDragStartY = 0
let previewDragOriginX = 0
let previewDragOriginY = 0
const previewIconSize = computed(() => {
if (!props.compact) return 28
return props.disabled ? 14 : 20
})
const previewTransformCss = computed(() =>
buildPreviewTransformCss(
previewOffsetX.value,
previewOffsetY.value,
previewAngle.value,
previewFitBase.value * previewZoom.value
)
)
const previewStatusText = computed(() => {
const deg = ((previewAngle.value % 360) + 360) % 360
return `${deg}° · ${Math.round(previewZoom.value * 100)}%`
})
function resolveFileUrl(url: string) {
return resolvePhotoDisplayUrl(url)
}
function parseModelValue(raw?: string): AttachmentItem[] {
if (!raw) return []
return String(raw)
.split(',')
.map((item) => item.trim())
.filter(Boolean)
.map((fileUrl, index) => ({
id: `existing-${index}-${fileUrl}`,
fileName: fileUrl.split('/').pop() || `file-${index + 1}`,
fileUrl
}))
}
function attachmentsToModelValue(items: AttachmentItem[]) {
return items
.filter((item) => item.fileUrl && !item._uploading)
.map((item) => item.fileUrl)
.join(',')
}
function syncModelValue() {
emit('update:modelValue', attachmentsToModelValue(attachments.value))
}
watch(
() => props.modelValue,
(value) => {
const next = parseModelValue(value)
const current = attachmentsToModelValue(attachments.value)
if (current === (value || '')) return
attachments.value = next
},
{ immediate: true }
)
function isImageFile(file: AttachmentItem) {
const name = file.fileName.toLowerCase()
const type = String(file.fileType || '').toLowerCase()
return (
type.startsWith('image/') ||
/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(name)
)
}
function isVideoFile(file: AttachmentItem) {
const name = file.fileName.toLowerCase()
const type = String(file.fileType || '').toLowerCase()
return type.startsWith('video/') || /\.(mp4|webm|ogg|mov|avi)$/i.test(name)
}
function isPdfFile(file: AttachmentItem) {
const name = file.fileName.toLowerCase()
const type = String(file.fileType || '').toLowerCase()
const url = String(file.fileUrl || '').toLowerCase()
return (
type === 'application/pdf' ||
/\.pdf$/i.test(name) ||
/\.pdf(\?|$)/i.test(url)
)
}
function isWordFile(file: AttachmentItem) {
const ext = getFileExtension(file.fileName)
return /^(DOC|DOCX|XLS|XLSX|PPT)/.test(ext)
}
function getFileExtension(fileName: string) {
if (!fileName) return ''
const lastDotIndex = fileName.lastIndexOf('.')
if (lastDotIndex === -1) return ''
return fileName.substring(lastDotIndex + 1).toUpperCase()
}
function getCategoryLabel(file: AttachmentItem) {
const label = props.categoryLabels?.[file.fileUrl]
return label ? String(label).trim() : ''
}
function canPreview(file: AttachmentItem) {
return Boolean(file.fileUrl) && (isImageFile(file) || isVideoFile(file) || isPdfFile(file))
}
function isFileAccepted(file: File) {
const accept = String(props.accept || '')
.split(',')
.map((item) => item.trim().toLowerCase())
.filter(Boolean)
if (!accept.length) return true
const name = String(file.name || '').toLowerCase()
const type = String(file.type || '').toLowerCase()
return accept.some((token) => {
if (token === '*/*') return true
if (token.endsWith('/*')) {
return type.startsWith(token.slice(0, -1))
}
if (token.startsWith('.')) {
return name.endsWith(token)
}
return type === token
})
}
function normalizeIncomingFile(file: File, index = 0) {
if (file.name && file.name.trim()) return file
const ext = (file.type || '').split('/')[1] || 'bin'
return new File([file], `paste-${Date.now()}-${index}.${ext}`, {
type: file.type || 'application/octet-stream'
})
}
function collectClipboardFiles(event: ClipboardEvent) {
const files: File[] = []
const items = event.clipboardData?.items
if (items?.length) {
Array.from(items).forEach((item, index) => {
if (item.kind !== 'file') return
const file = item.getAsFile()
if (file) files.push(normalizeIncomingFile(file, index))
})
}
if (!files.length && event.clipboardData?.files?.length) {
Array.from(event.clipboardData.files).forEach((file, index) => {
files.push(normalizeIncomingFile(file, index))
})
}
return files
}
async function uploadRawFile(rawFile: File) {
if (attachments.value.length >= props.limit) {
ElMessage.warning(`最多上传 ${props.limit} 个附件`)
return false
}
if (!isFileAccepted(rawFile)) {
ElMessage.warning(`不支持的文件类型:${rawFile.name || '未知文件'}`)
return false
}
const item = reactive<AttachmentItem>({
id: `upload-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
fileName: rawFile.name,
fileUrl: '',
fileType: rawFile.type,
_uploading: true
})
attachments.value.push(item)
const formData = props.bizType
? buildAttachmentUploadFormData(rawFile, {
bizType: props.bizType,
folder: props.folder || undefined
})
: (() => {
const fd = new FormData()
fd.append('file', rawFile)
if (props.folder) {
fd.append('folder', props.folder)
}
return fd
})()
try {
const res = await fetchUploadAttachment(formData)
const fileUrl = res?.fileUrl
if (!fileUrl) {
throw new Error('上传失败')
}
item.fileUrl = fileUrl
item.fileName = res.fileName || item.fileName
item.fileType = res.fileType || item.fileType
item._uploading = false
syncModelValue()
return true
} catch (error: any) {
attachments.value = attachments.value.filter((entry) => entry.id !== item.id)
ElMessage.error(error?.message || '上传失败')
return false
}
}
async function uploadFiles(files: File[]) {
if (!files.length || props.disabled) return
for (const file of files) {
if (attachments.value.length >= props.limit) {
ElMessage.warning(`最多上传 ${props.limit} 个附件`)
break
}
await uploadRawFile(file)
}
}
async function handleAttachmentChange(uploadFile: UploadFile) {
const rawFile = uploadFile.raw
if (!rawFile) return
await uploadRawFile(rawFile)
await nextTick()
uploadRef.value?.clearFiles()
}
function handlePointerEnter() {
if (props.disabled) return
isPointerInside.value = true
}
function handlePointerLeave() {
isPointerInside.value = false
}
function handleFocusOut(event: FocusEvent) {
const next = event.relatedTarget as Node | null
if (next && rootRef.value?.contains(next)) return
isPointerInside.value = false
}
function handleDragEnter(event: DragEvent) {
if (props.disabled) return
dragEnterDepth += 1
isDragOver.value = true
isPointerInside.value = true
}
function handleDragLeave(_event: DragEvent) {
if (props.disabled) return
dragEnterDepth = Math.max(0, dragEnterDepth - 1)
if (dragEnterDepth === 0) {
isDragOver.value = false
}
}
function handleDragOver(event: DragEvent) {
if (props.disabled) return
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'copy'
}
}
async function handleDrop(event: DragEvent) {
if (props.disabled) return
dragEnterDepth = 0
isDragOver.value = false
const files = Array.from(event.dataTransfer?.files || [])
await uploadFiles(files)
}
/** 弹窗内粘贴截图/文件:悬停、聚焦,或同对话框内输入时均可触发(有文件时) */
function shouldAcceptPaste(): boolean {
if (props.disabled) return false
if (isPointerInside.value) return true
const root = rootRef.value
if (!root) return false
const active = document.activeElement
if (active && root.contains(active)) return true
const dialog = root.closest('.el-dialog') as HTMLElement | null
if (!dialog) return false
if (!active || !dialog.contains(active)) return false
const uploads = Array.from(
dialog.querySelectorAll<HTMLElement>(
'.attachment-upload:not(.attachment-upload--readonly)'
)
)
if (!uploads.length) return false
const hovered = uploads.find((el) => el.matches(':hover'))
if (hovered) return hovered === root
return uploads[0] === root
}
async function handleDocumentPaste(event: ClipboardEvent) {
const files = collectClipboardFiles(event)
if (!files.length) return
if (!shouldAcceptPaste()) return
event.preventDefault()
event.stopPropagation()
await uploadFiles(files)
}
const PREVIEW_STAGE_PAD = 32
function refreshPreviewFitBase() {
const stage = previewStageRef.value
const img = previewImgRef.value
if (!stage || !img) return
const stageW = Math.max(stage.clientWidth - PREVIEW_STAGE_PAD, 1)
const stageH = Math.max(stage.clientHeight - PREVIEW_STAGE_PAD, 1)
previewFitBase.value = computeFitBaseScale(
img.naturalWidth,
img.naturalHeight,
previewAngle.value,
stageW,
stageH
)
// 以自然尺寸驱动,避免 max-width 裁切
img.style.width = `${img.naturalWidth || 0}px`
img.style.height = `${img.naturalHeight || 0}px`
}
function resetAllPreviewView() {
previewAngle.value = 0
previewZoom.value = 1
previewOffsetX.value = 0
previewOffsetY.value = 0
previewDragging.value = false
nextTick(() => refreshPreviewFitBase())
}
function resetPreviewZoomPan() {
previewZoom.value = 1
previewOffsetX.value = 0
previewOffsetY.value = 0
nextTick(() => refreshPreviewFitBase())
}
function rotatePreview(delta: number) {
previewAngle.value += delta
nextTick(() => refreshPreviewFitBase())
}
function nudgePreviewZoom(direction: 1 | -1) {
const next = clampPreviewZoom(previewZoom.value + direction * IMAGE_PREVIEW_ZOOM_STEP)
previewZoom.value = next
if (next <= 1) {
previewOffsetX.value = 0
previewOffsetY.value = 0
}
}
function handlePreviewImageLoad() {
refreshPreviewFitBase()
}
function handlePreviewWheel(e: WheelEvent) {
const delta = e.deltaY > 0 ? -IMAGE_PREVIEW_ZOOM_STEP : IMAGE_PREVIEW_ZOOM_STEP
nudgePreviewZoom(delta > 0 ? 1 : -1)
}
function handlePreviewPointerDown(e: PointerEvent) {
if (e.button !== 0) return
const stage = previewStageRef.value
if (!stage) return
previewDragging.value = true
previewDragStartX = e.clientX
previewDragStartY = e.clientY
previewDragOriginX = previewOffsetX.value
previewDragOriginY = previewOffsetY.value
stage.setPointerCapture(e.pointerId)
}
function handlePreviewPointerMove(e: PointerEvent) {
if (!previewDragging.value) return
previewOffsetX.value = previewDragOriginX + (e.clientX - previewDragStartX)
previewOffsetY.value = previewDragOriginY + (e.clientY - previewDragStartY)
}
function handlePreviewPointerUp(e: PointerEvent) {
if (!previewDragging.value) return
previewDragging.value = false
const stage = previewStageRef.value
try {
stage?.releasePointerCapture(e.pointerId)
} catch {
/* ignore */
}
}
function handlePreviewKeydown(e: KeyboardEvent) {
if (!previewVisible.value || !previewFile.value || !isImageFile(previewFile.value)) return
if (e.key === 'ArrowLeft') rotatePreview(-90)
if (e.key === 'ArrowRight') rotatePreview(90)
if (e.key === '+' || e.key === '=') nudgePreviewZoom(1)
if (e.key === '-' || e.key === '_') nudgePreviewZoom(-1)
if (e.key === '0') resetPreviewZoomPan()
}
function handlePreviewWindowResize() {
if (!previewVisible.value) return
refreshPreviewFitBase()
}
onMounted(() => {
document.addEventListener('paste', handleDocumentPaste, true)
document.addEventListener('keydown', handlePreviewKeydown)
window.addEventListener('resize', handlePreviewWindowResize)
})
onBeforeUnmount(() => {
document.removeEventListener('paste', handleDocumentPaste, true)
document.removeEventListener('keydown', handlePreviewKeydown)
window.removeEventListener('resize', handlePreviewWindowResize)
})
function removeAttachment(index: number) {
attachments.value.splice(index, 1)
syncModelValue()
}
function handleDownloadAttachment(file: AttachmentItem) {
downloadAttachmentFile(file, { fullFileUrl: resolveFileUrl })
}
const copyBusyId = ref('')
const previewCopyBusy = ref(false)
async function handleCopyAttachment(file: AttachmentItem) {
const url = String(file.fileUrl || '').trim()
if (!url) {
ElMessage.warning('暂无可复制内容')
return
}
const busyKey = file.id || url
if (copyBusyId.value === busyKey) return
copyBusyId.value = busyKey
try {
if (isImageFile(file)) {
const ok = await copyAttachmentImageToClipboard(file, { fullFileUrl: resolveFileUrl })
if (ok) ElMessage.success('已复制到剪贴板')
else ElMessage.warning('复制失败,请允许剪贴板权限或改用下载')
return
}
const href = resolveFileUrl(url)
const ok = await copyTextToClipboard(href || url)
if (ok) ElMessage.success('已复制链接')
else ElMessage.warning('复制失败,请允许剪贴板权限或改用下载')
} finally {
if (copyBusyId.value === busyKey) copyBusyId.value = ''
}
}
async function handleCopyPreviewImage() {
const file = previewFile.value
if (!file?.fileUrl || previewCopyBusy.value) return
previewCopyBusy.value = true
try {
const ok = await copyAttachmentImageToClipboard(file, { fullFileUrl: resolveFileUrl })
if (ok) ElMessage.success('已复制到剪贴板')
else ElMessage.warning('复制失败,请允许剪贴板权限或改用下载')
} finally {
previewCopyBusy.value = false
}
}
function handlePreviewAttachment(file: AttachmentItem) {
if (!canPreview(file)) return
previewFile.value = file
previewPdfSrc.value = ''
resetAllPreviewView()
previewVisible.value = true
if (!isPdfFile(file)) return
previewLoading.value = true
resolveAttachmentPreviewUrl(file, { fullFileUrl: resolveFileUrl })
.then((url) => {
if (previewFile.value?.id !== file.id) return
previewPdfSrc.value = url
})
.finally(() => {
if (previewFile.value?.id === file.id) {
previewLoading.value = false
}
})
}
function handleAttachmentClick(file: AttachmentItem) {
if (!file.fileUrl) return
if (canPreview(file)) {
handlePreviewAttachment(file)
return
}
const url = resolveFileUrl(file.fileUrl)
if (url) {
window.open(url, '_blank', 'noopener,noreferrer')
}
}
function handlePreviewClosed() {
previewFile.value = null
previewPdfSrc.value = ''
previewLoading.value = false
resetAllPreviewView()
}
function hasUploading() {
return attachments.value.some((item) => item._uploading)
}
defineExpose({ hasUploading })
</script>
<style scoped lang="scss">
.attachment-upload {
width: 100%;
outline: none;
border-radius: 8px;
&:focus-visible {
box-shadow: 0 0 0 2px rgba(28, 168, 81, 0.25);
}
&--drag-over {
.attachment-list {
border-radius: 8px;
background: rgba(16, 185, 129, 0.06);
outline: 2px dashed #1ca851;
outline-offset: 4px;
padding: 4px;
}
.upload-card {
border-color: #1ca851;
border-style: solid;
background: #e6f8ed;
}
}
}
.attachment-list {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.upload-card {
width: 140px;
height: 96px;
border: 1px dashed #a8e0b8;
border-radius: 8px;
background: #f0fdf4;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
cursor: pointer;
&:hover {
border-color: #1ca851;
border-style: solid;
background: #e6f8ed;
}
}
.upload-card-text {
font-size: 12px;
color: #1ca851;
font-weight: 500;
line-height: 1;
}
.upload-hint {
display: block;
font-size: 11px;
color: #1e293b;
margin-top: 8px;
line-height: 1;
}
.attachment-item {
flex: 0 0 auto;
width: 140px;
border: 1px solid #e2e8f0;
border-radius: 8px;
background: #fff;
overflow: hidden;
&.is-uploading {
opacity: 0.6;
pointer-events: none;
}
&:hover {
border-color: #1ca851;
box-shadow: 0 2px 8px rgba(28, 168, 81, 0.1);
}
}
.attachment-preview {
position: relative;
width: 100%;
height: 96px;
display: flex;
align-items: center;
justify-content: center;
background: #f8fafc;
overflow: hidden;
&.is-clickable {
cursor: zoom-in;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
}
.attachment-preview__icon {
width: 48px;
min-height: 48px;
border-radius: 10px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
&--video {
background: #ede9fe;
color: #7c3aed;
}
&--doc {
background: #e0f2fe;
color: #0284c7;
}
&--pdf {
background: #fee2e2;
color: #dc2626;
}
}
.attachment-preview__ext {
margin-top: 4px;
font-size: 11px;
font-weight: 600;
color: #1e293b;
}
.attachment-preview__category {
position: absolute;
right: 0;
bottom: 0;
left: 0;
z-index: 1;
padding: 2px 4px;
background: rgba(15, 23, 42, 0.62);
color: #fff;
font-size: 11px;
line-height: 1.3;
text-align: center;
word-break: keep-all;
}
.attachment-footer {
display: flex;
flex-direction: column;
padding: 6px 8px;
}
.attachment-name {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
font-size: 11px;
color: #1e293b;
line-height: 1.4;
word-break: break-all;
}
.attachment-actions {
display: flex;
justify-content: center;
gap: 8px;
margin-top: 4px;
}
.action-btn {
width: 22px;
height: 22px;
border-radius: 4px;
background: #f1f5f9;
color: #1e293b;
cursor: pointer;
&:hover {
background: #1ca851;
color: #fff;
}
&--danger:hover {
background: #ef4444;
color: #fff;
}
}
.preview-media {
display: block;
width: 100%;
max-width: 100%;
max-height: 70vh;
margin: 0 auto;
object-fit: contain;
border-radius: 8px;
background: #f8fafc;
&--iframe {
height: 70vh;
border: 0;
}
}
.preview-toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 8px;
margin-bottom: 12px;
}
/* 小程序 WebView / compact:无 icon、更矮的文字按钮 */
.preview-toolbar--mp {
gap: 6px;
:deep(.el-button) {
height: 28px !important;
min-height: 28px !important;
padding: 0 8px !important;
font-size: 12px !important;
line-height: 1 !important;
border-radius: 8px !important;
}
.preview-toolbar-sep {
height: 16px;
margin: 0 2px;
}
.preview-status-chip {
min-width: 72px;
font-size: 11px;
}
}
.preview-toolbar-sep {
width: 1px;
height: 20px;
margin: 0 4px;
background: var(--mint-border, #d9e8e2);
}
.preview-status-chip {
min-width: 96px;
font-size: 12px;
color: var(--mint-text-muted, #64748b);
text-align: center;
font-variant-numeric: tabular-nums;
}
.preview-stage {
display: flex;
align-items: center;
justify-content: center;
height: min(62vh, 520px);
min-height: 320px;
padding: 16px;
overflow: hidden;
cursor: grab;
touch-action: none;
background: #f8fafc;
border: 1px solid var(--mint-border, #d9e8e2);
border-radius: 8px;
&.is-dragging {
cursor: grabbing;
}
}
.preview-stage-img {
display: block;
max-width: none;
max-height: none;
border-radius: 4px;
transform-origin: center center;
transition: transform 0.15s ease;
user-select: none;
-webkit-user-drag: none;
pointer-events: none;
will-change: transform;
}
.preview-stage.is-dragging .preview-stage-img {
transition: none;
}
.preview-body {
min-height: 240px;
}
.preview-fallback {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
min-height: 240px;
color: #1e293b;
font-size: 14px;
}
:deep(.el-upload) {
display: inline-flex;
flex: 0 0 auto;
}
.attachment-upload--compact {
.attachment-list {
gap: 6px;
}
.upload-card-text {
display: none;
}
.attachment-preview__ext {
display: none;
}
.attachment-footer {
display: none;
}
}
/* 表格编辑:中等缩略图,支持预览 + 角标删除 */
.attachment-upload--compact:not(.attachment-upload--readonly) {
.upload-card {
width: 88px;
height: 66px;
gap: 0;
border-radius: 8px;
}
.attachment-item {
position: relative;
width: 88px;
border-radius: 8px;
&:hover {
box-shadow: 0 2px 6px rgba(28, 168, 81, 0.12);
}
}
.attachment-preview {
height: 66px;
}
.attachment-preview__icon {
width: 36px;
min-height: 36px;
border-radius: 8px;
}
.attachment-compact-delete {
position: absolute;
top: 4px;
right: 4px;
z-index: 2;
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
border: none;
border-radius: 999px;
background: rgba(15, 23, 42, 0.72);
color: #fff;
cursor: pointer;
transition: background 0.15s ease;
&:hover {
background: #ef4444;
}
}
}
/* 只读紧凑:更小缩略图(查看弹窗等),保留角标下载 */
.attachment-upload--compact.attachment-upload--readonly {
.attachment-list {
gap: 4px;
}
.upload-card {
width: 40px;
height: 40px;
gap: 0;
border-radius: 6px;
}
.attachment-item {
position: relative;
width: 40px;
border-radius: 6px;
&:hover {
box-shadow: 0 1px 4px rgba(28, 168, 81, 0.12);
}
}
.attachment-preview {
height: 40px;
}
.attachment-preview__icon {
width: 24px;
min-height: 24px;
border-radius: 6px;
}
.attachment-compact-download,
.attachment-compact-copy {
position: absolute;
top: 2px;
z-index: 2;
display: flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
padding: 0;
border: none;
border-radius: 999px;
background: rgba(15, 23, 42, 0.72);
color: #fff;
cursor: pointer;
transition: background 0.15s ease;
&:hover {
background: #1ca851;
}
&:disabled {
opacity: 0.55;
cursor: not-allowed;
}
}
.attachment-compact-download {
right: 2px;
}
.attachment-compact-copy {
right: 22px;
}
}
</style>
<style lang="scss">
/* Keep desktop compact sizing; only /m dialogs receive the touch targets. */
.attachment-upload-preview--mobile {
.el-dialog__header {
padding-right: 56px !important;
}
.el-dialog__title {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.el-dialog__headerbtn {
width: 44px;
height: 44px;
}
.preview-toolbar .el-button {
min-width: 44px;
height: 30px !important;
min-height: 30px !important;
margin-left: 0;
}
}
</style>