vue-office
This commit is contained in:
1 parent
e72889acdb
commit
62ec5a3513
6 files changed
+598
-56
No files matched your search
@@ -10,15 +10,32 @@
|
||||
*/
|
||||
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<{
|
||||
@@ -28,11 +45,15 @@ const emit = defineEmits<{
|
||||
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>('');
|
||||
|
||||
/**
|
||||
* Extract extension from URL or filename.
|
||||
* - Drops query string first (for signed URLs).
|
||||
* - Returns lowercase extension without dot.
|
||||
* 从 URL 或文件名中提取扩展名。
|
||||
* - 会先去掉 query 参数(兼容签名链接)。
|
||||
* - 返回小写扩展名(不含点号)。
|
||||
*/
|
||||
const getExt = (raw: string) => {
|
||||
const clean = (raw.split('?')[0] ?? '').toLowerCase();
|
||||
@@ -47,21 +68,23 @@ const ext = computed(() => {
|
||||
return getExt(props.file?.name || '');
|
||||
});
|
||||
|
||||
const preferredMode = computed<'markdown' | 'image' | 'iframe'>(() => {
|
||||
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'].includes(ext.value)) return 'markdown';
|
||||
if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
|
||||
if (['xlsx'].includes(ext.value)) return 'office';
|
||||
if (['docx'].includes(ext.value)) return 'office';
|
||||
return 'iframe';
|
||||
});
|
||||
const resolvedMode = ref<'markdown' | 'image' | 'iframe'>('iframe');
|
||||
const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe');
|
||||
|
||||
const isOfficeDoc = computed(() => ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext.value));
|
||||
|
||||
/**
|
||||
* Decide whether Office Online Viewer can be used safely.
|
||||
* Requirements (practical):
|
||||
* - Office-like file type.
|
||||
* - HTTPS URL.
|
||||
* - Publicly reachable host (not localhost/private subnet).
|
||||
* 判断当前文件是否可使用微软 Office 在线预览。
|
||||
* 实际条件:
|
||||
* - 必须是 Office 文档类型;
|
||||
* - 必须是 HTTPS;
|
||||
* - 主机必须公网可达(非 localhost/私网网段)。
|
||||
*/
|
||||
const canUseOfficeOnlineViewer = computed(() => {
|
||||
const raw = props.file?.url || '';
|
||||
@@ -88,60 +111,205 @@ const canUseOfficeOnlineViewer = computed(() => {
|
||||
}
|
||||
});
|
||||
|
||||
const needsOfficeFallback = computed(() => isOfficeDoc.value && !canUseOfficeOnlineViewer.value);
|
||||
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()}`;
|
||||
});
|
||||
|
||||
/**
|
||||
* Compute iframe source.
|
||||
* - Office docs with public HTTPS: use Office Online embed endpoint.
|
||||
* - Otherwise: fallback to raw file URL (browser/native handling).
|
||||
* 计算 iframe 预览地址。
|
||||
* - pdf/doc/docx 优先走后端同源代理地址;
|
||||
* - Office 文档且满足公网 HTTPS 时,走微软在线预览;
|
||||
* - 其余返回原始 URL,由浏览器自行处理。
|
||||
*/
|
||||
const iframeSrc = computed(() => {
|
||||
if (!props.file?.url) return '';
|
||||
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(props.file.url)}`;
|
||||
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 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') officeKind.value = 'docx';
|
||||
else if (ext.value === 'xlsx') 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);
|
||||
};
|
||||
|
||||
/**
|
||||
* Load preview content when modal/file changes.
|
||||
* Strategy:
|
||||
* 1) Reset state and choose preferred mode by extension.
|
||||
* 2) Only actively fetch for markdown/text mode.
|
||||
* 3) Auto-switch mode by response content-type (image/binary/text).
|
||||
* 4) Parse markdown to HTML on success; set error on failure.
|
||||
* 在弹窗/文件变化时加载预览内容。
|
||||
* 流程:
|
||||
* 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,
|
||||
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 {
|
||||
const res = await fetch(props.file.url);
|
||||
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,
|
||||
});
|
||||
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
|
||||
headers: props.authHeaders || {},
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status}`);
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||
}
|
||||
const contentType = (res.headers.get('content-type') || '').toLowerCase();
|
||||
if (contentType.startsWith('image/')) {
|
||||
resolvedMode.value = 'image';
|
||||
return;
|
||||
}
|
||||
if (
|
||||
contentType &&
|
||||
!contentType.includes('text/') &&
|
||||
!contentType.includes('markdown') &&
|
||||
!contentType.includes('application/json')
|
||||
) {
|
||||
resolvedMode.value = 'iframe';
|
||||
return;
|
||||
}
|
||||
const text = await res.text();
|
||||
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';
|
||||
@@ -151,10 +319,10 @@ const loadContent = async () => {
|
||||
};
|
||||
|
||||
/**
|
||||
* Reactively reload preview when:
|
||||
* - modal visibility changes
|
||||
* - file URL changes
|
||||
* - file name changes
|
||||
* 响应式重载:
|
||||
* - 弹窗显隐变化;
|
||||
* - 文件 URL 变化;
|
||||
* - 文件名变化。
|
||||
*/
|
||||
watch(
|
||||
() => [props.modelValue, props.file?.url, props.file?.name],
|
||||
@@ -163,6 +331,15 @@ watch(
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(v) => {
|
||||
if (!v) {
|
||||
clearOfficeObjectUrl();
|
||||
}
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -187,9 +364,67 @@ watch(
|
||||
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"
|
||||
@@ -202,14 +437,14 @@ watch(
|
||||
</div>
|
||||
<div class="mt-4 flex gap-3">
|
||||
<a
|
||||
:href="file.url"
|
||||
: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="file.url"
|
||||
: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"
|
||||
>
|
||||
|
||||
Reference in new issue
Block a user