vue-office

This commit is contained in:
sophie committed 2026-04-08 09:06:37 +08:00
1 parent e72889acdb
commit 62ec5a3513
6 files changed
+598 -56

No files matched your search

+81 -8
View File
@@ -10,6 +10,9 @@
"dependencies": {
"@tailwindcss/forms": "^0.5.11",
"@tailwindcss/typography": "^0.5.19",
"@vue-office/docx": "^1.6.3",
"@vue-office/excel": "^1.7.14",
"@vue-office/pdf": "^1.6.5",
"axios": "^1.13.5",
"highlight.js": "^11.11.1",
"lucide-vue-next": "^0.575.0",
@@ -556,7 +559,6 @@
"integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"undici-types": "~7.16.0"
}
@@ -607,6 +609,57 @@
"vscode-uri": "^3.0.8"
}
},
"node_modules/@vue-office/docx": {
"version": "1.6.3",
"resolved": "https://registry.npmjs.org/@vue-office/docx/-/docx-1.6.3.tgz",
"integrity": "sha512-Cs+3CAaRBOWOiW4XAhTwwxJ0dy8cPIf6DqfNvYcD3YACiLwO4kuawLF2IAXxyijhbuOeoFsfvoVbOc16A/4bZA==",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
"@vue/composition-api": "^1.7.1",
"vue": "^2.0.0 || >=3.0.0",
"vue-demi": "^0.14.6"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
}
},
"node_modules/@vue-office/excel": {
"version": "1.7.14",
"resolved": "https://registry.npmjs.org/@vue-office/excel/-/excel-1.7.14.tgz",
"integrity": "sha512-pVUgt+emDQUnW7q22CfnQ+jl43mM/7IFwYzOg7lwOwPEbiVB4K4qEQf+y/bc4xGXz75w1/e3Kz3G6wAafmFBFg==",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
"@vue/composition-api": "^1.7.1",
"vue": "^2.0.0 || >=3.0.0",
"vue-demi": "^0.14.6"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
}
},
"node_modules/@vue-office/pdf": {
"version": "1.6.5",
"resolved": "https://registry.npmjs.org/@vue-office/pdf/-/pdf-1.6.5.tgz",
"integrity": "sha512-3BePzeA5wji2JoZGJhdlc3XEXs6gMcSnBXrBXlGGfhZHjNijxcHa9V5Ibm8dDKoEwPPsfg+kf4TGP9/2GBR8jQ==",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
"@vue/composition-api": "^1.7.1",
"vue": "^2.0.0 || >=3.0.0",
"vue-demi": "^0.14.6"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
}
},
"node_modules/@vue/compiler-core": {
"version": "3.5.28",
"resolved": "https://mirrors.tencent.com/npm/@vue/compiler-core/-/compiler-core-3.5.28.tgz",
@@ -912,7 +965,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759",
@@ -2003,7 +2055,6 @@
"resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -2048,7 +2099,6 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
@@ -2390,7 +2440,6 @@
"resolved": "https://mirrors.tencent.com/npm/tailwindcss/-/tailwindcss-3.4.17.tgz",
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
"license": "MIT",
"peer": true,
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
"arg": "^5.0.2",
@@ -2492,7 +2541,6 @@
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -2551,7 +2599,6 @@
"integrity": "sha512-RHX7IvsJlEfjyA1rS7MY0UsmF91etdLAamslHR5lfuO3W/BXRdXm2tRE64ztpSPZbKqB4wAAZ0AwtF6QzfKZLA==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@oxc-project/runtime": "0.114.0",
"lightningcss": "^1.31.1",
@@ -2637,7 +2684,6 @@
"resolved": "https://mirrors.tencent.com/npm/vue/-/vue-3.5.28.tgz",
"integrity": "sha512-BRdrNfeoccSoIZeIhyPBfvWSLFP4q8J3u8Ju8Ug5vu3LdD+yTM13Sg4sKtljxozbnuMu1NB1X5HBHRYUzFocKg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@vue/compiler-dom": "3.5.28",
"@vue/compiler-sfc": "3.5.28",
@@ -2654,6 +2700,33 @@
}
}
},
"node_modules/vue-demi": {
"version": "0.14.10",
"resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz",
"integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==",
"hasInstallScript": true,
"license": "MIT",
"peer": true,
"bin": {
"vue-demi-fix": "bin/vue-demi-fix.js",
"vue-demi-switch": "bin/vue-demi-switch.js"
},
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/antfu"
},
"peerDependencies": {
"@vue/composition-api": "^1.0.0-rc.1",
"vue": "^3.0.0-0 || ^2.6.0"
},
"peerDependenciesMeta": {
"@vue/composition-api": {
"optional": true
}
}
},
"node_modules/vue-i18n": {
"version": "11.2.8",
"resolved": "https://mirrors.tencent.com/npm/vue-i18n/-/vue-i18n-11.2.8.tgz",
+3
View File
@@ -11,6 +11,9 @@
"dependencies": {
"@tailwindcss/forms": "^0.5.11",
"@tailwindcss/typography": "^0.5.19",
"@vue-office/docx": "^1.6.3",
"@vue-office/excel": "^1.7.14",
"@vue-office/pdf": "^1.6.5",
"axios": "^1.13.5",
"highlight.js": "^11.11.1",
"lucide-vue-next": "^0.575.0",
+281 -46
View File
@@ -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"
>
+7 -2
View File
@@ -546,7 +546,7 @@ const submitFeedback = async () => {
</button>
<div>
<p class="font-semibold tracking-tight text-slate-900 dark:text-slate-100">{{ currentAgent?.name || $t('chat.defaultTitle') }}</p>
<p class="text-xs text-slate-500 dark:text-slate-400">HXOPS AI Assistant</p>
<p class="text-xs text-slate-500 dark:text-slate-400">{{ $t('chat.assistantLabel') }}</p>
</div>
</div>
<div class="flex items-center gap-2">
@@ -813,5 +813,10 @@ const submitFeedback = async () => {
</div>
</div>
<FilePreviewModal v-model="filePreviewVisible" :file="previewFile" />
<FilePreviewModal
v-model="filePreviewVisible"
:file="previewFile"
:agent-id="agentId"
:auth-headers="getAuthHeaders()"
/>
</template>