Files
syops/frontend/src/components/FilePreviewModal.vue
T
2026-04-28 18:53:54 +08:00

518 lines
18 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.
<script setup lang="ts">
/**
* FilePreviewModal.vue
* 文件用途:文件预览弹窗,用于在聊天页预览来源文件内容
* 引用文件:vue, marked
* 逻辑关系:
* - 接收 ChatView 传入的 file(name/url)与弹窗显隐状态
* - 根据扩展名选择预览模式(markdown/image/iframe)
* - 对 Office 文档在可公网 HTTPS 访问时走 Office 在线预览,否则降级为打开/下载
*/
import { computed, ref, watch } from 'vue';
import { marked } from 'marked';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
import '@vue-office/docx/lib/index.css';
import '@vue-office/excel/lib/index.css';
interface PreviewFile {
name: string;
url: string;
}
interface ExcelPreviewData {
sheet_name: string;
sheets: string[];
columns: string[];
rows: Array<Array<string | number | boolean>>;
limit: number;
truncated: boolean;
}
type OfficeKind = 'docx' | 'excel' | null;
const props = defineProps<{
modelValue: boolean;
file: PreviewFile | null;
agentId?: number | null;
authHeaders?: Record<string, string>;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
}>();
const isLoading = ref(false);
const error = ref('');
const markdownHtml = ref('');
const excelPreview = ref<ExcelPreviewData | null>(null);
const officeSrc = ref<string | ArrayBuffer | Blob>('');
const officeKind = ref<OfficeKind>(null);
const officeObjectUrl = ref<string>('');
/**
* 从 URL 或文件名中提取扩展名。
* - 会先去掉 query 参数(兼容签名链接)。
* - 返回小写扩展名(不含点号)。
*/
const getExt = (raw: string) => {
const clean = (raw.split('?')[0] ?? '').toLowerCase();
const parts = clean.split('/');
const lastPart = parts[parts.length - 1] ?? '';
const i = lastPart.lastIndexOf('.');
return i >= 0 ? lastPart.slice(i + 1) : '';
};
const ext = computed(() => {
// URL extension has higher priority than display name.
const byUrl = getExt(props.file?.url || '');
if (byUrl) return byUrl;
return getExt(props.file?.name || '');
});
const preferredMode = computed<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>(() => {
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
if (['xlsx', 'xls'].includes(ext.value)) return 'office';
if (['docx', 'doc', 'pdf'].includes(ext.value)) return 'iframe';
return 'iframe';
});
const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe');
const isOfficeDoc = computed(() => ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext.value));
/**
* 判断当前文件是否可使用微软 Office 在线预览。
* 实际条件:
* - 必须是 Office 文档类型;
* - 必须是 HTTPS;
* - 主机必须公网可达(非 localhost/私网网段)。
*/
const canUseOfficeOnlineViewer = computed(() => {
const raw = props.file?.url || '';
if (!raw || !isOfficeDoc.value) return false;
try {
const u = new URL(raw, window.location.origin);
// Office online viewer usually requires a publicly reachable HTTPS URL.
// Private-network or local addresses typically render as blank pages.
if (u.protocol !== 'https:') return false;
const host = u.hostname;
if (
host === 'localhost' ||
host === '127.0.0.1' ||
host === '::1' ||
/^10\./.test(host) ||
/^192\.168\./.test(host) ||
/^172\.(1[6-9]|2\d|3[0-1])\./.test(host)
) {
return false;
}
return true;
} catch {
return false;
}
});
const needsOfficeFallback = computed(
() => ['ppt', 'pptx'].includes(ext.value) && !canUseOfficeOnlineViewer.value
);
const previewRawUrl = computed(() => {
if (!props.file?.url || !props.agentId) return '';
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
return `/api/chat/preview-file-raw?${params.toString()}`;
});
/**
* 计算 iframe 预览地址。
* - pdf/doc/docx 优先走后端同源代理地址;
* - Office 文档且满足公网 HTTPS 时,走微软在线预览;
* - 其余返回原始 URL,由浏览器自行处理。
*/
const iframeSrc = computed(() => {
if (!props.file?.url || !props.agentId) return '';
if (ext.value === 'pdf') {
// PDF must use authenticated fetched blob URL; do not fallback to raw URL.
return officeObjectUrl.value;
}
if (isOfficeDoc.value && canUseOfficeOnlineViewer.value) {
return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(previewRawUrl.value)}`;
}
if (['doc', 'docx'].includes(ext.value)) {
return previewRawUrl.value;
}
return props.file.url;
});
const close = () => emit('update:modelValue', false);
const isDownloading = ref(false);
const downloadFile = async () => {
if (!props.file?.url || !props.agentId) return;
isDownloading.value = true;
try {
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
download: '1'
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = props.file.name || 'download';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (err: any) {
console.error('Download failed:', err);
alert('下载失败: ' + (err.message || '未知错误'));
} finally {
isDownloading.value = false;
}
};
const clearOfficeObjectUrl = () => {
if (officeObjectUrl.value) {
URL.revokeObjectURL(officeObjectUrl.value);
officeObjectUrl.value = '';
}
officeSrc.value = '';
officeKind.value = null;
};
const loadOfficeContent = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for office preview');
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
}
const blob = await res.blob();
clearOfficeObjectUrl();
officeObjectUrl.value = URL.createObjectURL(blob);
officeSrc.value = officeObjectUrl.value;
if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx';
else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel';
else officeKind.value = null;
};
const loadPdfContent = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for pdf preview');
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
}
const buf = await res.arrayBuffer();
const head = new TextDecoder().decode(buf.slice(0, 5));
if (head !== '%PDF-') {
throw new Error('Invalid PDF binary from preview API');
}
clearOfficeObjectUrl();
const blob = new Blob([buf], { type: 'application/pdf' });
officeObjectUrl.value = URL.createObjectURL(blob);
};
/**
* 在弹窗/文件变化时加载预览内容。
* 流程:
* 1) 重置状态并按扩展名确定优先模式;
* 2) Excel 走后端 /preview-excel 返回表格数据;
* 3) 文本类走后端 /preview-text 返回文本并渲染 Markdown;
* 4) 其他格式交由 iframe 或降级策略处理;
* 5) 失败写入 error,前端展示可读错误信息。
*/
const loadContent = async () => {
error.value = '';
markdownHtml.value = '';
excelPreview.value = null;
clearOfficeObjectUrl();
if (!props.modelValue || !props.file) return;
if (!props.file?.url) return;
resolvedMode.value = preferredMode.value;
if (ext.value === 'pdf') {
isLoading.value = true;
try {
await loadPdfContent();
resolvedMode.value = 'iframe';
} catch (e: any) {
error.value = e?.message || 'Failed to preview pdf';
resolvedMode.value = 'iframe';
} finally {
isLoading.value = false;
}
return;
}
if (preferredMode.value === 'office') {
isLoading.value = true;
try {
await loadOfficeContent();
if (!officeKind.value) {
throw new Error(`Unsupported office preview extension: ${ext.value}`);
}
resolvedMode.value = 'office';
} catch (e: any) {
error.value = e?.message || 'Failed to preview office file';
resolvedMode.value = 'iframe';
} finally {
isLoading.value = false;
}
return;
}
if (preferredMode.value === 'sheet') {
if (!props.agentId) {
error.value = 'agent_id is required for excel preview';
return;
}
isLoading.value = true;
try {
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
limit: '100',
});
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
headers: props.authHeaders || {},
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data?.error || `HTTP ${res.status}`);
}
excelPreview.value = data as ExcelPreviewData;
resolvedMode.value = 'sheet';
} catch (e: any) {
error.value = e?.message || 'Failed to preview excel';
resolvedMode.value = 'iframe';
} finally {
isLoading.value = false;
}
return;
}
if (preferredMode.value !== 'markdown') return;
isLoading.value = true;
try {
if (!props.agentId) {
throw new Error('agent_id is required for text preview');
}
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || `HTTP ${res.status}`);
}
const payload = await res.json();
const text = String(payload?.content || '');
markdownHtml.value = marked.parse(text) as string;
} catch (e: any) {
error.value = e?.message || 'Failed to load file';
} finally {
isLoading.value = false;
}
};
/**
* 响应式重载:
* - 弹窗显隐变化;
* - 文件 URL 变化;
* - 文件名变化。
*/
watch(
() => [props.modelValue, props.file?.url, props.file?.name],
() => {
loadContent();
},
{ immediate: true }
);
watch(
() => props.modelValue,
(v) => {
if (!v) {
clearOfficeObjectUrl();
}
}
);
</script>
<template>
<div v-if="modelValue && file" class="fixed inset-0 z-[80] flex items-center justify-center bg-black/50 dark:bg-slate-950/70 backdrop-blur-sm p-4">
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-xl w-full max-w-5xl h-[85vh] flex flex-col overflow-hidden border border-slate-200 dark:border-slate-700">
<div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700 flex items-start justify-between gap-4">
<div class="min-w-0">
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">文件预览</div>
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
<button type="button" @click="downloadFile" :disabled="isDownloading" class="mt-2 inline-flex items-center justify-center px-3 py-1.5 text-xs font-medium rounded-lg bg-brand-50 text-brand-700 hover:bg-brand-100 border border-brand-200 dark:bg-brand-900/30 dark:text-brand-300 dark:border-brand-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
<svg v-if="!isDownloading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<svg v-else class="animate-spin -ml-1 mr-2 h-4 w-4 text-brand-700 dark:text-brand-300" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isDownloading ? '下载中...' : '下载文件' }}
</button>
</div>
<button type="button" @click="close" class="shrink-0 whitespace-nowrap inline-flex items-center justify-center px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 bg-white/80 dark:bg-slate-900/80 hover:bg-slate-100 dark:hover:bg-slate-800">关闭</button>
</div>
<div class="flex-1 overflow-auto p-4 bg-slate-50 dark:bg-slate-950">
<div v-if="isLoading" class="text-sm text-slate-500 dark:text-slate-400">加载中...</div>
<div v-else-if="error" class="text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg p-3">
预览失败:{{ error }}
</div>
<div
v-else-if="resolvedMode === 'markdown'"
class="prose prose-sm max-w-none bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg p-5"
v-html="markdownHtml"
></div>
<div
v-else-if="resolvedMode === 'sheet' && excelPreview"
class="h-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 p-4 overflow-auto"
>
<div class="mb-3 text-xs text-slate-500 dark:text-slate-400">
Sheet: {{ excelPreview.sheet_name }} | Rows: {{ excelPreview.rows.length }}
<span v-if="excelPreview.truncated"> (truncated)</span>
</div>
<table class="min-w-full text-xs border-collapse">
<thead>
<tr>
<th
v-for="(col, i) in excelPreview.columns"
:key="`h-${i}`"
class="sticky top-0 bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 px-2 py-1 text-left font-semibold"
>
{{ col }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, ri) in excelPreview.rows" :key="`r-${ri}`">
<td
v-for="(cell, ci) in row"
:key="`c-${ri}-${ci}`"
class="border border-slate-200 dark:border-slate-700 px-2 py-1 align-top whitespace-pre-wrap break-words"
>
{{ cell }}
</td>
</tr>
</tbody>
</table>
</div>
<div
v-else-if="resolvedMode === 'office' && officeKind"
class="h-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 p-2 overflow-auto"
>
<VueOfficeDocx
v-if="officeKind === 'docx'"
:src="officeSrc"
style="height: 100%; width: 100%;"
/>
<VueOfficeExcel
v-else-if="officeKind === 'excel'"
:src="officeSrc"
style="height: 100%; width: 100%;"
/>
</div>
<div v-else-if="resolvedMode === 'image'" class="h-full flex items-center justify-center bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg p-2">
<img :src="file.url" :alt="file.name" class="max-w-full max-h-full object-contain" />
</div>
<div
v-else-if="ext === 'pdf' && officeObjectUrl"
class="h-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 overflow-hidden"
>
<embed
:src="officeObjectUrl"
type="application/pdf"
class="w-full h-full min-h-[480px]"
/>
</div>
<div
v-else-if="needsOfficeFallback"
class="h-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 p-6"
>
<!-- Graceful fallback for private/non-HTTPS Office links:
show actions instead of an empty iframe. -->
<div class="text-sm text-slate-700 dark:text-slate-200 font-semibold">Preview not available for this file URL</div>
<div class="mt-2 text-sm text-slate-500 dark:text-slate-400">
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
</div>
<div class="mt-4 flex gap-3">
<a
:href="previewRawUrl || file.url"
target="_blank"
class="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700"
>
Open in new tab
</a>
<a
:href="previewRawUrl || file.url"
download
class="px-3 py-2 rounded-lg border border-slate-300 dark:border-slate-600 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-800"
>
Download file
</a>
</div>
</div>
<iframe
v-else
:src="iframeSrc"
class="w-full h-full min-h-[480px] bg-white dark:bg-slate-900 rounded-lg border border-slate-200 dark:border-slate-700"
allow="clipboard-read; clipboard-write"
></iframe>
</div>
</div>
</div>
</template>