230 lines
8.1 KiB
Vue
230 lines
8.1 KiB
Vue
<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';
|
||
|
||
interface PreviewFile {
|
||
name: string;
|
||
url: string;
|
||
}
|
||
|
||
const props = defineProps<{
|
||
modelValue: boolean;
|
||
file: PreviewFile | null;
|
||
}>();
|
||
|
||
const emit = defineEmits<{
|
||
(e: 'update:modelValue', value: boolean): void;
|
||
}>();
|
||
|
||
const isLoading = ref(false);
|
||
const error = ref('');
|
||
const markdownHtml = ref('');
|
||
|
||
/**
|
||
* Extract extension from URL or filename.
|
||
* - Drops query string first (for signed URLs).
|
||
* - Returns lowercase extension without dot.
|
||
*/
|
||
const getExt = (raw: string) => {
|
||
const clean = (raw.split('?')[0] ?? '').toLowerCase();
|
||
const i = clean.lastIndexOf('.');
|
||
return i >= 0 ? clean.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'>(() => {
|
||
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
|
||
if (['md', 'markdown', 'txt'].includes(ext.value)) return 'markdown';
|
||
return 'iframe';
|
||
});
|
||
const resolvedMode = ref<'markdown' | 'image' | 'iframe'>('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).
|
||
*/
|
||
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(() => isOfficeDoc.value && !canUseOfficeOnlineViewer.value);
|
||
|
||
/**
|
||
* Compute iframe source.
|
||
* - Office docs with public HTTPS: use Office Online embed endpoint.
|
||
* - Otherwise: fallback to raw file URL (browser/native handling).
|
||
*/
|
||
const iframeSrc = computed(() => {
|
||
if (!props.file?.url) return '';
|
||
if (isOfficeDoc.value && canUseOfficeOnlineViewer.value) {
|
||
return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(props.file.url)}`;
|
||
}
|
||
return props.file.url;
|
||
});
|
||
|
||
const close = () => emit('update:modelValue', false);
|
||
|
||
/**
|
||
* 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.
|
||
*/
|
||
const loadContent = async () => {
|
||
error.value = '';
|
||
markdownHtml.value = '';
|
||
if (!props.modelValue || !props.file) return;
|
||
if (!props.file?.url) return;
|
||
resolvedMode.value = preferredMode.value;
|
||
if (preferredMode.value !== 'markdown') return;
|
||
|
||
isLoading.value = true;
|
||
try {
|
||
const res = await fetch(props.file.url);
|
||
if (!res.ok) {
|
||
throw new 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();
|
||
markdownHtml.value = marked.parse(text) as string;
|
||
} catch (e: any) {
|
||
error.value = e?.message || 'Failed to load file';
|
||
} finally {
|
||
isLoading.value = false;
|
||
}
|
||
};
|
||
|
||
/**
|
||
* Reactively reload preview when:
|
||
* - modal visibility changes
|
||
* - file URL changes
|
||
* - file name changes
|
||
*/
|
||
watch(
|
||
() => [props.modelValue, props.file?.url, props.file?.name],
|
||
() => {
|
||
loadContent();
|
||
},
|
||
{ immediate: true }
|
||
);
|
||
</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-center justify-between gap-4">
|
||
<div class="min-w-0">
|
||
<div class="text-sm text-slate-500 dark:text-slate-400 uppercase tracking-wide">文件预览</div>
|
||
<div class="font-semibold text-slate-900 dark:text-slate-100 truncate">{{ file.name }}</div>
|
||
<a :href="file.url" target="_blank" class="text-xs text-brand-600 hover:text-brand-700 break-all">{{ file.url }}</a>
|
||
</div>
|
||
<button @click="close" class="px-3 py-1.5 rounded-lg text-slate-600 dark:text-slate-300 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 === '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="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="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"
|
||
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>
|