feat(chat-fixed-assets): 支持资产履历直达预览并优化 Excel 预览体验
This commit is contained in:
1 parent
1164ae2e3c
commit
56b6ea06a8
14 files changed
+1051
-48
No files matched your search
@@ -1,4 +1,4 @@
|
||||
<script setup lang="ts">
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* shared/components/FilePreviewModal.vue
|
||||
* 文件预览弹窗(图片/PDF 等)。
|
||||
@@ -10,13 +10,15 @@
|
||||
* 引用文件:vue, marked
|
||||
* 逻辑关系:
|
||||
* - 接收 ChatView 传入的 file(name/url)与弹窗显隐状态
|
||||
* - 根据扩展名选择预览模式(markdown/image/iframe)
|
||||
* - 根据扩展名选择预览模式(markdown/image/iframe/office)
|
||||
* - Excel 预览优先走 Office 风格渲染,尽量还原原始表格观感;失败时再降级为简化表格
|
||||
* - 对 Office 文档在可公网 HTTPS 访问时走 Office 在线预览,否则降级为打开/下载
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { marked } from 'marked';
|
||||
import * as XLSX from 'xlsx';
|
||||
import { Minus, Plus, RotateCcw } from 'lucide-vue-next';
|
||||
import VueOfficeDocx from '@vue-office/docx';
|
||||
import VueOfficeExcel from '@vue-office/excel';
|
||||
import VueOfficePdf from '@vue-office/pdf';
|
||||
@@ -39,7 +41,7 @@ interface ExcelPreviewData {
|
||||
}
|
||||
|
||||
type OfficeKind = 'docx' | 'excel' | 'pdf' | null;
|
||||
type PreviewMode = 'markdown' | 'image' | 'iframe' | 'sheet' | 'office';
|
||||
type PreviewMode = 'markdown' | 'image' | 'iframe' | 'sheet' | 'sheetHtml' | 'office';
|
||||
|
||||
const props = defineProps<{
|
||||
modelValue: boolean;
|
||||
@@ -56,11 +58,17 @@ const { t } = useI18n();
|
||||
const isLoading = ref(false);
|
||||
const error = ref('');
|
||||
const markdownHtml = ref('');
|
||||
const excelHtml = ref('');
|
||||
const excelPreview = ref<ExcelPreviewData | null>(null);
|
||||
const officeSrc = ref<string | ArrayBuffer | Blob>('');
|
||||
const officeKind = ref<OfficeKind>(null);
|
||||
const officeObjectUrl = ref<string>('');
|
||||
const officeRenderKey = ref(0);
|
||||
const excelZoom = ref(1);
|
||||
|
||||
const EXCEL_ZOOM_STEP = 0.1;
|
||||
const EXCEL_ZOOM_MIN = 0.6;
|
||||
const EXCEL_ZOOM_MAX = 1.8;
|
||||
|
||||
/**
|
||||
* 从 URL 或文件名中提取扩展名。
|
||||
@@ -87,8 +95,7 @@ const ext = computed(() => {
|
||||
const preferredMode = computed<PreviewMode>(() => {
|
||||
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 (['xlsx', 'xls', 'docx'].includes(ext.value)) return 'office';
|
||||
if (['doc', 'ppt', 'pptx', 'pdf'].includes(ext.value)) return 'iframe';
|
||||
return 'iframe';
|
||||
});
|
||||
@@ -120,6 +127,13 @@ const iframeSrc = computed(() => {
|
||||
|
||||
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
|
||||
const officePreviewExts = new Set(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']);
|
||||
const isExcelPreviewFile = computed(() => ['xls', 'xlsx'].includes(ext.value));
|
||||
const excelZoomPercent = computed(() => `${Math.round(excelZoom.value * 100)}%`);
|
||||
const excelPreviewScaleStyle = computed(() => ({
|
||||
transform: `scale(${excelZoom.value})`,
|
||||
transformOrigin: 'top left',
|
||||
width: `${100 / excelZoom.value}%`,
|
||||
}));
|
||||
|
||||
const close = () => emit('update:modelValue', false);
|
||||
|
||||
@@ -134,6 +148,25 @@ const clearOfficeObjectUrl = () => {
|
||||
officeKind.value = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* 调整 Excel 预览缩放比例。
|
||||
* AI 触发时机:当用户点击弹窗头部的放大/缩小按钮,希望更清楚查看履历表格时调用。
|
||||
* 核心逻辑:按照固定步进调整缩放,并限制在可读范围内,避免放得过大或过小。
|
||||
* 参数与输出约束:delta 仅表示增量,不直接写死最终倍率;最终结果会被钳制到 60%~180%。
|
||||
*/
|
||||
const adjustExcelZoom = (delta: number) => {
|
||||
const nextZoom = excelZoom.value + delta;
|
||||
excelZoom.value = Math.min(EXCEL_ZOOM_MAX, Math.max(EXCEL_ZOOM_MIN, Number(nextZoom.toFixed(2))));
|
||||
};
|
||||
|
||||
/**
|
||||
* 重置 Excel 预览缩放比例。
|
||||
* 用途:让用户一键回到默认 100% 视图,避免多次缩放后难以恢复。
|
||||
*/
|
||||
const resetExcelZoom = () => {
|
||||
excelZoom.value = 1;
|
||||
};
|
||||
|
||||
const extractErrorMessage = (payload: any, fallback: string) => {
|
||||
if (!payload) return fallback;
|
||||
if (typeof payload === 'string' && payload.trim()) return payload.trim();
|
||||
@@ -186,6 +219,27 @@ const applyExcelPreview = (buffer: ArrayBuffer) => {
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 将 Excel 原始工作表转为 HTML 预览。
|
||||
* 用途:尽量保留原 Excel 的布局、合并单元格和表格观感,使履历预览更接近用户看到的原文件。
|
||||
* 约束:仅使用第一个工作表;若库无法解析原始布局,则抛错并交给表格矩阵模式兜底。
|
||||
*/
|
||||
const applyExcelHtmlPreview = (buffer: ArrayBuffer) => {
|
||||
const workbook = XLSX.read(buffer, { type: 'array', cellStyles: true });
|
||||
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}`);
|
||||
}
|
||||
excelHtml.value = XLSX.utils.sheet_to_html(worksheet, {
|
||||
id: 'hxops-excel-preview-table',
|
||||
editable: false,
|
||||
});
|
||||
};
|
||||
|
||||
const tryApplyExcelPreview = (buffer: ArrayBuffer) => {
|
||||
try {
|
||||
applyExcelPreview(buffer);
|
||||
@@ -214,6 +268,40 @@ const loadSheetPreview = async () => {
|
||||
excelPreview.value = await res.json();
|
||||
};
|
||||
|
||||
/**
|
||||
* 直接拉取原始 Excel 二进制并在前端解析。
|
||||
* 用途:当后端 `/preview-excel` 无法处理共享盘里的旧版 Excel 时,前端仍尽量展示首个工作表内容。
|
||||
* 约束:仅作为 Excel 预览兜底使用;解析失败时继续向上抛错,由统一错误 UI 呈现。
|
||||
*/
|
||||
const loadSheetPreviewFromRaw = async () => {
|
||||
if (!props.file?.url) return;
|
||||
if (!props.agentId) throw new Error('agent_id is required for excel 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) {
|
||||
throw new Error(await readErrorMessage(res));
|
||||
}
|
||||
|
||||
const buffer = await res.arrayBuffer();
|
||||
try {
|
||||
applyExcelHtmlPreview(buffer);
|
||||
resolvedMode.value = 'sheetHtml';
|
||||
return;
|
||||
} catch {
|
||||
if (!tryApplyExcelPreview(buffer)) {
|
||||
throw new Error('failed to parse excel file');
|
||||
}
|
||||
resolvedMode.value = 'sheet';
|
||||
}
|
||||
};
|
||||
|
||||
const loadOfficeContent = async () => {
|
||||
if (!props.file?.url) return;
|
||||
if (!props.agentId) throw new Error('agent_id is required for office preview');
|
||||
@@ -240,6 +328,23 @@ const loadOfficeContent = async () => {
|
||||
else officeKind.value = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Excel Office 风格渲染失败后的兜底处理。
|
||||
* AI 触发时机:当 `VueOfficeExcel` 无法正确渲染共享盘里的旧版/特殊 Excel 时调用。
|
||||
* 核心逻辑:优先走后端 `/preview-excel` 简化预览,失败后再回退到前端原始二进制解析,确保用户至少能看到表格内容。
|
||||
* 参数与输出约束:该方法只处理当前已加载文件,不接收外部参数;成功后会把 `resolvedMode` 切换为 `sheet`。
|
||||
*/
|
||||
const fallbackToSheetPreview = async () => {
|
||||
try {
|
||||
await loadSheetPreviewFromRaw();
|
||||
error.value = '';
|
||||
} catch {
|
||||
await loadSheetPreview();
|
||||
resolvedMode.value = 'sheet';
|
||||
error.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
|
||||
if (!props.file?.url) return 'iframe';
|
||||
if (!props.agentId) throw new Error('agent_id is required for pdf preview');
|
||||
@@ -342,7 +447,9 @@ const loadBinaryContent = async () => {
|
||||
const loadContent = async () => {
|
||||
error.value = '';
|
||||
markdownHtml.value = '';
|
||||
excelHtml.value = '';
|
||||
excelPreview.value = null;
|
||||
resetExcelZoom();
|
||||
clearOfficeObjectUrl();
|
||||
if (!props.modelValue || !props.file) return;
|
||||
if (!props.file?.url) return;
|
||||
@@ -374,8 +481,17 @@ const loadContent = async () => {
|
||||
}
|
||||
resolvedMode.value = 'office';
|
||||
} catch (e: any) {
|
||||
error.value = e?.message || 'Failed to preview office file';
|
||||
resolvedMode.value = 'iframe';
|
||||
if (['xlsx', 'xls'].includes(ext.value)) {
|
||||
try {
|
||||
await fallbackToSheetPreview();
|
||||
} catch {
|
||||
error.value = e?.message || 'Failed to preview excel';
|
||||
resolvedMode.value = 'iframe';
|
||||
}
|
||||
} else {
|
||||
error.value = e?.message || 'Failed to preview office file';
|
||||
resolvedMode.value = 'iframe';
|
||||
}
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
@@ -387,8 +503,13 @@ const loadContent = async () => {
|
||||
await loadSheetPreview();
|
||||
resolvedMode.value = 'sheet';
|
||||
} catch (e: any) {
|
||||
error.value = e?.message || 'Failed to preview excel';
|
||||
resolvedMode.value = 'iframe';
|
||||
try {
|
||||
await loadSheetPreviewFromRaw();
|
||||
resolvedMode.value = 'sheet';
|
||||
} catch {
|
||||
error.value = e?.message || 'Failed to preview excel';
|
||||
resolvedMode.value = 'iframe';
|
||||
}
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
@@ -464,14 +585,47 @@ watch(
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="modelValue && file" class="dialog-overlay dialog-overlay--z80 items-center">
|
||||
<div v-if="modelValue && file" class="dialog-overlay z-[140] items-center">
|
||||
<div class="dialog-panel max-w-5xl h-[85vh] overflow-hidden">
|
||||
<div class="dialog-header dialog-header--compact items-start">
|
||||
<div class="min-w-0">
|
||||
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">{{ t('filePreview.title') }}</div>
|
||||
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<div v-if="isExcelPreviewFile" class="flex items-center gap-2 rounded-full border border-default bg-surface px-2 py-1">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-icon-ds h-8 w-8"
|
||||
aria-label="缩小"
|
||||
:disabled="excelZoom <= EXCEL_ZOOM_MIN"
|
||||
@click="adjustExcelZoom(-EXCEL_ZOOM_STEP)"
|
||||
>
|
||||
<Minus class="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md px-2 py-1 text-xs font-medium text-secondary transition hover:bg-surface-soft"
|
||||
aria-label="重置缩放"
|
||||
@click="resetExcelZoom"
|
||||
>
|
||||
<span class="inline-flex items-center gap-1">
|
||||
<RotateCcw class="h-3.5 w-3.5" />
|
||||
{{ excelZoomPercent }}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-icon-ds h-8 w-8"
|
||||
aria-label="放大"
|
||||
:disabled="excelZoom >= EXCEL_ZOOM_MAX"
|
||||
@click="adjustExcelZoom(EXCEL_ZOOM_STEP)"
|
||||
>
|
||||
<Plus class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dialog-preview-body">
|
||||
@@ -493,34 +647,44 @@ watch(
|
||||
v-else-if="resolvedMode === 'sheet' && excelPreview"
|
||||
class="dialog-preview-frame h-full p-4 overflow-auto"
|
||||
>
|
||||
<div class="mb-3 text-xs text-muted">
|
||||
Sheet: {{ excelPreview.sheet_name }} | Rows: {{ excelPreview.rows.length }}
|
||||
<span v-if="excelPreview.truncated"> (truncated)</span>
|
||||
<div :style="excelPreviewScaleStyle" class="pb-6">
|
||||
<div class="mb-3 text-xs text-muted">
|
||||
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-surface-soft border border-default px-2 py-1 text-left font-semibold text-secondary"
|
||||
>
|
||||
{{ 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-default px-2 py-1 align-top whitespace-pre-wrap break-words text-secondary"
|
||||
>
|
||||
{{ cell }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="resolvedMode === 'sheetHtml' && excelHtml"
|
||||
class="dialog-preview-frame h-full overflow-auto bg-white p-4"
|
||||
>
|
||||
<div :style="excelPreviewScaleStyle" class="pb-6">
|
||||
<div class="excel-html-preview min-w-max" v-html="excelHtml"></div>
|
||||
</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-surface-soft border border-default px-2 py-1 text-left font-semibold text-secondary"
|
||||
>
|
||||
{{ 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-default px-2 py-1 align-top whitespace-pre-wrap break-words text-secondary"
|
||||
>
|
||||
{{ cell }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div
|
||||
v-else-if="resolvedMode === 'office' && officeKind"
|
||||
@@ -538,6 +702,8 @@ watch(
|
||||
v-else-if="officeKind === 'excel'"
|
||||
:key="`excel-${officeRenderKey}`"
|
||||
:src="officeSrc"
|
||||
@rendered="error = ''"
|
||||
@error="fallbackToSheetPreview().catch(() => { error = 'Excel render failed'; resolvedMode = 'sheet'; })"
|
||||
style="height: 100%; width: 100%;"
|
||||
/>
|
||||
<VueOfficePdf
|
||||
@@ -581,3 +747,26 @@ watch(
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.excel-html-preview :deep(table) {
|
||||
border-collapse: collapse;
|
||||
background: #fff;
|
||||
color: #111827;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.excel-html-preview :deep(td),
|
||||
.excel-html-preview :deep(th) {
|
||||
min-width: 52px;
|
||||
border: 1px solid #111827;
|
||||
padding: 4px 6px;
|
||||
vertical-align: middle;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.excel-html-preview :deep(tr:nth-child(-n + 2) td),
|
||||
.excel-html-preview :deep(tr:nth-child(-n + 2) th) {
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user