Files
syops/frontend/src/components/FilePreviewModal.vue
T

549 lines
20 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 * as XLSX from 'xlsx';
import { useMessage } from '../composables/useMessage';
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 msg = useMessage();
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(() => {
// Display name extension has higher priority than URL.
const byName = getExt(props.file?.name || '');
if (byName) return byName;
return getExt(props.file?.url || '');
});
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 'sheet';
if (['docx'].includes(ext.value)) return 'office';
if (['doc', 'ppt', 'pptx', 'pdf'].includes(ext.value)) return 'iframe';
return 'iframe';
});
const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe');
const needsOfficeFallback = computed(() => {
// We no longer need fallback for doc/ppt/pptx because they are converted to PDF by the backend
return false;
});
/**
* 计算 iframe 预览地址。
* - pdf/doc/docx 优先走后端同源代理地址;
* - Office 文档且满足公网 HTTPS 时,走微软在线预览;
* - 其余返回原始 URL,由浏览器自行处理。
*/
const iframeSrc = computed(() => {
if (!props.file?.url) return '';
if (officeObjectUrl.value) return officeObjectUrl.value;
if (!props.agentId) return '';
if (['pdf', 'doc', 'ppt', 'pptx'].includes(ext.value)) {
// These formats must use the authenticated fetch -> blob flow only.
// Never fallback to a protected iframe URL, otherwise it returns Unauthorized.
return officeObjectUrl.value;
}
return props.file.url;
});
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
const close = () => emit('update:modelValue', false);
const isDownloading = ref(false);
const previewTooLarge = computed(() => /file too large for online preview/i.test(error.value));
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);
msg.error('下载失败: ' + (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 blob = await res.blob();
clearOfficeObjectUrl();
let fallbackType = 'application/octet-stream';
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) fallbackType = 'application/pdf';
else if (ext.value === 'docx') fallbackType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType });
officeObjectUrl.value = URL.createObjectURL(effectiveBlob);
};
const loadBinaryContent = async () => {
if (!props.file?.url) return;
if (!props.agentId) throw new Error('agent_id is required for binary 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);
};
/**
* 在弹窗/文件变化时加载预览内容。
* 流程:
* 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 (['pdf', 'doc', 'docx', 'ppt', 'pptx'].includes(ext.value) && preferredMode.value === 'iframe') {
if (needsOfficeFallback.value) {
resolvedMode.value = 'iframe';
return;
}
isLoading.value = true;
try {
await loadPdfContent(); // This fetches as Blob, and sets officeObjectUrl which will be used in iframeSrc
resolvedMode.value = 'iframe';
} catch (e: any) {
error.value = e?.message || `Failed to preview ${ext.value}`;
resolvedMode.value = 'iframe';
} finally {
isLoading.value = false;
}
return;
}
if (preferredMode.value === 'office' && !needsOfficeFallback.value) {
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 || '',
});
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
headers: props.authHeaders || {},
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data?.error || `HTTP ${res.status}`);
}
const buffer = await res.arrayBuffer();
const workbook = XLSX.read(buffer, { type: 'array' });
if (!workbook.SheetNames.length) {
throw new Error('workbook has no sheets');
}
const sheetName = workbook.SheetNames[0] || 'Sheet1';
const worksheet = workbook.Sheets[sheetName];
if (!worksheet) {
throw new Error(`worksheet not found: ${sheetName}`);
}
const matrix = XLSX.utils.sheet_to_json<(string | number | boolean)[]>(worksheet, {
header: 1,
raw: false,
defval: '',
});
const limit = 100;
const rows = matrix.slice(0, limit).map((row) => row.map((cell) => cell ?? ''));
const maxCols = rows.reduce((max, row) => Math.max(max, row.length), 0);
const normalizedRows = rows.map((row) =>
row.length < maxCols ? [...row, ...Array(maxCols - row.length).fill('')] : row
);
excelPreview.value = {
sheet_name: sheetName,
sheets: workbook.SheetNames,
columns: Array.from({ length: maxCols }, (_, i) => `COL_${i + 1}`),
rows: normalizedRows,
limit,
truncated: matrix.length > limit,
};
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 === 'image' || (preferredMode.value === 'iframe' && !/^https?:\/\//i.test(props.file.url || ''))) {
isLoading.value = true;
try {
await loadBinaryContent();
resolvedMode.value = preferredMode.value === 'image' ? 'image' : 'iframe';
} catch (e: any) {
error.value = e?.message || 'Failed to load file preview';
resolvedMode.value = preferredMode.value === 'image' ? 'image' : '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">
<template v-if="previewTooLarge">
文件较大,暂不支持在线预览,请直接点击上方“下载文件”获取原文件。
</template>
<template v-else>
预览失败:{{ error }}
</template>
</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="imageSrc" :alt="file.name" class="max-w-full max-h-full object-contain" />
</div>
<div
v-else-if="['pdf', 'doc', 'ppt', 'pptx'].includes(ext) && officeObjectUrl"
class="h-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 overflow-hidden"
>
<iframe
:src="officeObjectUrl"
class="w-full h-full min-h-[480px] border-0"
allow="clipboard-read; clipboard-write"
></iframe>
</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">
<button
type="button"
@click="downloadFile"
:disabled="isDownloading"
class="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center"
>
<svg v-if="isDownloading" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" 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>
</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>