右侧加上文件预览窗口

This commit is contained in:
2026-10-18 19:35:47 +08:00
parent 3df7505fb1
commit 4cde1ea91e
7 changed files with 456 additions and 80 deletions
+2 -2
View File
@@ -1089,8 +1089,8 @@ function deleteSession(sessionId, deleteDir) {
const session = getSession(sessionId);
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
stop(sessionId);
// 尽力清理该会话在 officecli 桥里的预览槽位(没配 officecli 则静默;失败只记日志,不阻断删除)
mcp.notifyTool('officecli', { command: 'unwatch --session ' + String(sessionId).replace(/[^0-9A-Za-z_-]/g, '') }, 5000, { 'X-Session-Dir': taskDirOf(sessionId) });
// 尽力清理该会话在 officecli 桥里的预览槽位与工作区目录副本(--purge;没配 officecli 则静默,失败只记日志,不阻断删除)
mcp.notifyTool('officecli', { command: 'unwatch --session ' + String(sessionId).replace(/[^0-9A-Za-z_-]/g, '') + ' --purge' }, 5000, { 'X-Session-Dir': taskDirOf(sessionId) });
db.prepare('DELETE FROM messages WHERE session_id = ?').run(sessionId);
db.prepare('DELETE FROM files WHERE session_id = ?').run(sessionId);
db.prepare('DELETE FROM sessions WHERE id = ?').run(sessionId);
+47
View File
@@ -1256,3 +1256,50 @@ label.icon-btn { cursor: pointer; }
/* toast 相对会话区(而非整个视口)居中 */
body.drawer-open #toast { left: calc(50% + var(--sidebar-w) / 2); }
}
/* ---------- 文档预览右栏(桌面端≥960px;移动端 office 走全屏 #fs-viewer,本栏隐藏) ---------- */
#pv-pane { display: none; }
@media (min-width: 960px) {
body.pv-open #pv-pane {
display: flex; flex-direction: column;
position: fixed; top: 0; right: 0; bottom: 0;
width: var(--pv-w, min(50vw, 900px)); min-width: 320px;
background: var(--page); border-left: 1px solid var(--border);
z-index: 55;
}
body.pv-open.pv-max #pv-pane { left: 0; width: auto; border-left: none; z-index: 120; }
/* 挤压式分栏:会话列让位;打开右栏时左侧历史栏会自动折叠(若手动再展开则两者同时让位) */
body.pv-open #app { width: calc(100% - var(--pv-w, min(50vw, 900px))); margin-left: 0; }
body.pv-open.drawer-open #app { width: calc(100% - var(--sidebar-w) - var(--pv-w, min(50vw, 900px))); margin-left: var(--sidebar-w); }
body.pv-open.pv-max #app { width: 100%; margin-left: 0; }
}
.pv-head { flex: none; display: flex; align-items: center; gap: 8px; padding: 8px 10px 8px 14px; border-bottom: 1px solid var(--border); background: var(--drawer-bg); }
.pv-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; font-weight: 600; }
.pv-actions { flex: none; display: flex; align-items: center; gap: 6px; margin-left: 8px; }
.pv-body { flex: 1; min-height: 0; position: relative; overflow: auto; display: flex; flex-direction: column; background: #fff; }
.pv-frame { flex: 1; width: 100%; height: 100%; border: 0; background: #fff; }
.pv-doc { width: 100%; max-width: 860px; margin: 0 auto; padding: 16px 20px 40px; }
.pv-img { margin: auto; max-width: 92%; max-height: 92%; object-fit: contain; cursor: zoom-in; }
.pv-err { margin: auto; display: flex; flex-direction: column; align-items: center; gap: 14px; padding: 32px; text-align: center; color: var(--gray-light); font-size: 13px; line-height: 1.7; }
.pv-err button { border: 0; background: var(--active); color: #fff; border-radius: 8px; padding: 8px 20px; font-size: 13px; cursor: pointer; }
.pv-err button:hover { opacity: .88; }
.pv-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; background: #fff; }
.pv-loading::after { content: ''; width: 28px; height: 28px; border: 3px solid var(--border); border-top-color: var(--active); border-radius: 50%; animation: pvspin 0.8s linear infinite; }
@keyframes pvspin { to { transform: rotate(360deg); } }
/* ---------- preview pane v2: drag resize / info card / plain text ---------- */
.pv-resizer { position: absolute; left: 0; top: 0; bottom: 0; width: 6px; cursor: col-resize; z-index: 6; touch-action: none; }
.pv-resizer:hover, .pv-resizer:active { background: var(--active); opacity: .3; }
body.pv-resizing { cursor: col-resize; user-select: none; }
body.pv-resizing #pv-pane iframe { pointer-events: none; }
.pv-plain { width: 100%; }
.pv-pre { width: 100%; max-width: 920px; margin: 0 auto; padding: 14px 20px 40px; font: 12.5px/1.65 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: pre-wrap; word-break: break-all; }
.pv-trunc { max-width: 880px; margin: 12px auto 0; padding: 0 20px; font-size: 12px; color: var(--gray-light); }
.pv-loading.inline { position: static; background: transparent; padding: 56px 0; }
.pv-none { margin: auto; display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 44px 24px; text-align: center; }
.pv-none svg { width: 54px; height: 54px; color: var(--gray-light); opacity: .8; }
.pv-none .nm { font-size: 15px; font-weight: 600; word-break: break-all; }
.pv-none .meta { font-size: 12px; color: var(--gray-light); }
.pv-none .hint { font-size: 13px; color: var(--gray-light); line-height: 1.7; max-width: 420px; }
.pv-none button { margin-top: 8px; border: 0; background: var(--active); color: #fff; border-radius: 8px; padding: 9px 22px; font-size: 13px; cursor: pointer; }
.pv-none button:hover { opacity: .88; }
+24
View File
@@ -401,6 +401,29 @@
<img id="img-viewer-img" alt="">
</div>
<!-- ================= 文档预览右栏(桌面端≥960px;office/全部文档类型统一承载;移动端走全屏 #fs-viewer,本栏隐藏) -->
<aside id="pv-pane" aria-label="文档预览">
<header class="pv-head">
<span class="pv-title" id="pv-title"></span>
<span class="pv-actions">
<button class="icon-btn hidden" id="pv-download" title="下载文件" aria-label="下载文件">
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>
</button>
<button class="icon-btn hidden" id="pv-refresh" title="重新载入" aria-label="重新载入">
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"></polyline><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path></svg>
</button>
<button class="icon-btn hidden" id="pv-popup" title="新窗口打开" aria-label="新窗口打开">
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>
</button>
<button class="icon-btn" id="pv-max" title="放大" aria-label="放大">
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3"></path><path d="M21 8V5a2 2 0 0 0-2-2h-3"></path><path d="M16 21h3a2 2 0 0 0 2-2v-3"></path><path d="M3 16v3a2 2 0 0 0 2 2h3"></path></svg>
</button>
<button class="icon-btn" id="pv-close" title="关闭预览" aria-label="关闭预览">✕</button>
</span>
</header>
<div class="pv-body" id="pv-body"></div>
</aside>
<!-- 消息全屏查看器(双击气泡/工具卡打开;支持双指缩放) -->
<div id="fs-viewer" class="hidden" onclick="if(event.target===this)closeFullscreen()">
<button class="fs-close" onclick="closeFullscreen()">✕</button>
@@ -417,6 +440,7 @@
<script src="/js/sessions.js"></script>
<script src="/js/stream.js"></script>
<script src="/js/files.js"></script>
<script src="/js/preview.js"></script>
<script src="/js/settings.js"></script>
</body>
</html>
+6 -76
View File
@@ -311,16 +311,16 @@
}
function fileRowHtml(f) {
// 预览策略:md/txt/html/pdf + 图片在 fs-viewer 预览(pdf 按 pdfViewerEnabled 页内/下载分流)
// 预览策略:所有文件点击一律进预览窗(preview.js openFilePreview);此处仅决定图标(可预览=眼睛,其余=文档)
const low = f.filename.toLowerCase();
const fsPv = /\.(md|txt|html?|pdf|png|jpe?g|gif|webp|svg)$/.test(low);
const fsPv = /\.(md|txt|html?|pdf|png|jpe?g|gif|webp|svg|docx|xlsx|pptx|csv|tsv|json|jsonl|xml|yml|yaml|toml|ini|conf|cfg|properties|env|log|py|pyw|js|mjs|cjs|ts|tsx|jsx|java|kt|c|h|cpp|hpp|cc|cs|go|rs|rb|php|swift|sh|bash|zsh|bat|ps1|sql|lua|r|dart|vue|css|less|scss|srt|vtt)$/.test(low);
const ico = fsPv
? '<svg class="file-ico eye" viewBox="0 0 24 24" aria-label="可预览"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>'
: '<svg class="file-ico doc" viewBox="0 0 24 24" aria-label="可下载"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>';
const name = esc(String(f.filename).split('/').pop() || f.filename);
const ftime = fmtTime(f.mtime || f.ctime);
const sel = isFileEffectivelySelected(f.filename);
return '<div class="file-row' + (fsPv ? ' clickable' : '') + (sel ? ' selected' : '') + '" data-path="' + esc(f.filename) + '" data-preview="' + (fsPv ? '1' : '0') + '">' +
return '<div class="file-row clickable' + (sel ? ' selected' : '') + '" data-path="' + esc(f.filename) + '" data-preview="' + (fsPv ? '1' : '0') + '" data-size="' + esc(fmtSize(f.size)) + '">' +
'<span class="file-check" role="checkbox" aria-checked="' + (sel ? 'true' : 'false') + '" aria-label="选择"></span>' +
'<div class="file-main">' +
'<div class="file-name">' + name + '</div>' +
@@ -501,76 +501,7 @@
});
return '<!DOCTYPE html>\n' + doc.documentElement.outerHTML;
}
// 单击可预览文件 → 全屏预览(#fs-viewer):md 按 markdown 渲染、txt 原文排版、html 用沙箱 iframe、pdf 按 pdfViewerEnabled 页内/下载分流、图片用 <img>
async function previewInFs(name) {
try {
const r = await fetch('/api/sessions/' + state.sessionId + '/files/download?path=' + encodeURIComponent(name));
if (r.status === 401) { location.href = '/login?next=' + encodeURIComponent(location.pathname + location.search); return; }
if (!r.ok) { let msg = 'HTTP ' + r.status; try { msg = (await r.json()).error || msg; } catch (_) {} throw new Error(msg); }
if (/\.html?$/i.test(name)) {
const html = await r.text();
const body = $('fs-body');
body.innerHTML = '';
const iframe = document.createElement('iframe');
iframe.className = 'fs-html-frame';
iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts');
iframe.srcdoc = rewriteHtmlDocSrcs(html, name); // 相对资源改写,否则 about:srcdoc 基准下全 404
body.appendChild(iframe);
setFsSource(html); // 源码钮可看页面原码
$('fs-viewer').classList.remove('hidden');
} else if (/\.pdf$/i.test(name)) {
// H5 方案 A:navigator.pdfViewerEnabled 是专为「能否内嵌渲染 PDF」设计的检测位
// (桌面各浏览器/iOS Safari = true;Android Chrome/微信 webview = false)
if (navigator.pdfViewerEnabled) {
const blob = await r.blob(); // 响应 Content-Type 即 application/pdf
const url = URL.createObjectURL(blob);
if (state.lastPdfBlobUrl) { try { URL.revokeObjectURL(state.lastPdfBlobUrl); } catch (_) {} }
state.lastPdfBlobUrl = url;
const body = $('fs-body');
body.innerHTML = '';
body.style.zoom = '';
const frame = document.createElement('iframe');
frame.className = 'fs-html-frame';
frame.title = name; // 不加 sandbox:内建查看器插件需要 unrestricted 帧
frame.src = url;
body.appendChild(frame);
setFsSource(null); // 二进制无源码可看,隐藏 eye 钮
$('fs-viewer').classList.remove('hidden');
} else {
// 不支持页内嵌的浏览器:交给既有签名直链下载链路(Android 通知栏用系统查看器打开)
toast('当前浏览器不支持页内预览 PDF,已开始下载');
downloadFile(name);
}
} else if (/\.(png|jpe?g|gif|webp|svg)$/i.test(name)) {
// 图片:复用会话里单击图片的全屏查看器(双指缩放+拖动+双击放大),大图也能看完
const blob = await r.blob();
const url = URL.createObjectURL(blob);
// 上一次的 blob URL 顺手释放;避免反复预览图片泄漏
if (state.lastImgBlobUrl) { try { URL.revokeObjectURL(state.lastImgBlobUrl); } catch (_) {} }
state.lastImgBlobUrl = url;
openImageViewer(url, name);
} else {
// md/txt:复用双击气泡的全屏查看器
const text = await r.text();
let cls = 'bubble-ai', html;
if (/\.(md|markdown)$/i.test(name)) {
const r2 = mdHtml(text);
html = r2.html;
if (r2.fmt) {
cls += ' md';
html = rewriteMdImageSrcs(html, name);
}
} else {
html = esc(text);
}
const wrap = document.createElement('div');
wrap.className = 'msg other';
wrap.innerHTML = '<div class="' + cls + '">' + html + '</div>';
decorateCodePre(wrap); // 先装饰再克隆:按钮随 openFullscreen 的深拷贝进查看器,fs-viewer 已有 .act-copy 委托
openFullscreen(wrap.firstChild, text); // 文件原文供 eye 钮看源码
}
} catch (e) { toast('预览失败:' + e.message); }
}
// 预览路由已迁至 js/preview.js(openFilePreview):office 走 /preview 预览服务;其余类型桌面进 #pv-pane、移动端进 #fs-viewer。
async function downloadFile(name) {
if (!state.sessionId) return;
try {
@@ -618,9 +549,8 @@
updateFilesFooter();
return;
}
// 默认模式:依据是否可预览选择预览/下载
if (row.dataset.preview === '1') previewInFs(path);
else downloadFile(path);
// 默认模式:所有文件一律进预览窗(不支持类型窗内展示占位与下载入口),不再直接下载
openFilePreview(path, row.dataset.size || '');
});
// 整体选中/取消一个文件夹:目录作为单条选中项(d: 前缀),行视觉态由 refreshFileSelStates 重算。
+374
View File
@@ -0,0 +1,374 @@
// 通用文档预览窗(桌面右侧 #pv-pane / 移动端全屏 #fs-viewer)
// —— 文件列表的点击一律进预览窗:office 走 /preview 预览网关(固定格式前端自拼);
// md/txt/代码/json/csv 等文本渲染;html/pdf/图片专用渲染;其余类型显示文件信息占位 + 下载。
// 桌面打开时自动折叠左侧历史栏让位,关闭恢复;左右边界可拖拽调宽(记忆在 localStorage)。
// 依赖(core.js/chat.js/stream.js/files.js 顶层声明):state $ esc toast mdHtml decorateCodePre
// rewriteHtmlDocSrcs rewriteMdImageSrcs openFullscreen setFsSource closeFullscreen
// openImageViewer downloadFile openDrawer
'use strict';
const PV_OFFICE = /\.(docx|xlsx|pptx)$/i;
const PV_IMG = /\.(png|jpe?g|gif|webp|svg|bmp|avif|ico)$/i;
const PV_MD = /\.(md|markdown)$/i;
const PV_PLAIN = /\.(txt|log)$/i;
// 常见代码/配置/数据文本扩展名;无扩展名的文件(Dockerfile/LICENSE 等)也按文本尝试,二进制嗅探兜底
const PV_TEXT = /\.(md|markdown|txt|log|csv|tsv|json|jsonl|xml|yml|yaml|toml|ini|conf|cfg|properties|env|py|pyw|js|mjs|cjs|ts|tsx|jsx|java|kt|c|h|cpp|hpp|cc|cs|go|rs|rb|php|swift|sh|bash|zsh|bat|ps1|sql|lua|r|dart|vue|css|less|scss|srt|vtt)$/i;
const PV_TEXT_MAX = 512 * 1024; // 文本预览截断阈值(字符),超出提示下载看全文
let pvSeq = 0; // 预览序号:快速连点时旧请求不许再动 DOM
const pvState = { name: null, url: null, blobUrl: null, drawerWasOpen: false, mobilePush: false };
function pvDesktop() { return window.matchMedia('(min-width: 960px)').matches; }
function pvOfficeUrl(rel) {
return '/preview/' + encodeURIComponent(state.sessionId) + '/' +
String(rel).split('/').filter(Boolean).map(encodeURIComponent).join('/') + '/';
}
function pvKind(name) {
const low = String(name).toLowerCase();
if (/\.html?$/i.test(low)) return 'html';
if (/\.pdf$/i.test(low)) return 'pdf';
if (PV_IMG.test(low)) return 'img';
const base = String(name).split('/').pop();
if (PV_TEXT.test(base) || !/\.[a-z0-9]{1,8}$/i.test(base)) return 'text';
return 'none';
}
function pvToolbar(o) {
document.getElementById('pv-refresh').classList.toggle('hidden', !o.refresh);
document.getElementById('pv-popup').classList.toggle('hidden', !o.popup);
}
// 每次展示内容都过一遍:标题显示相对路径(子目录可见),右上角下载钮随文件走
function pvHeader(name, sizeText) {
pvState.name = name;
const t = document.getElementById('pv-title');
t.textContent = String(name || '');
t.title = sizeText ? name + ' · ' + sizeText : String(name || '');
document.getElementById('pv-download').classList.toggle('hidden', !name);
}
function pvClearBody() {
document.getElementById('pv-body').innerHTML = '';
if (pvState.blobUrl) { try { URL.revokeObjectURL(pvState.blobUrl); } catch (_) {} pvState.blobUrl = null; }
}
function pvLoadingBox() {
const d = document.createElement('div');
d.className = 'pv-loading';
return d;
}
// 占位信息卡:不支持/读不到/缺失 共用。带文件名、大小与下载按钮(点击一律走这里,不再直接下载)
function pvInfoNode(name, sizeText, hint) {
const box = document.createElement('div');
box.className = 'pv-none';
box.innerHTML =
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">' +
'<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>' +
'<div class="nm"></div><div class="meta"></div><div class="hint"></div>';
box.querySelector('.nm').textContent = String(name || '');
box.querySelector('.meta').textContent = sizeText ? sizeText : '';
box.querySelector('.hint').textContent = String(hint || '');
const btn = document.createElement('button');
btn.textContent = '下载文件';
btn.addEventListener('click', () => { if (typeof downloadFile === 'function') downloadFile(name); });
box.appendChild(btn);
return box;
}
function pvOpenPane() {
if (!document.body.classList.contains('pv-open')) {
pvState.drawerWasOpen = document.getElementById('drawer').classList.contains('open');
if (pvState.drawerWasOpen && typeof openDrawer === 'function') openDrawer(false); // 挤压式分栏:折叠左侧让位
document.body.classList.add('pv-open');
}
}
function pvCloseDoc() {
if (!document.body.classList.contains('pv-open')) return;
document.body.classList.remove('pv-open', 'pv-max');
pvClearBody();
pvState.name = null; pvState.url = null;
if (pvState.drawerWasOpen) {
pvState.drawerWasOpen = false;
if (typeof openDrawer === 'function') openDrawer(true); // 恢复打开预览前的折叠态
}
}
// 移动端全屏承载:把节点塞进 #fs-viewer 并展开
function pvOverlayShow(node) {
const body = document.getElementById('fs-body');
body.innerHTML = ''; body.style.zoom = '';
if (typeof setFsSource === 'function') setFsSource(null);
body.appendChild(node);
document.getElementById('fs-viewer').classList.remove('hidden');
}
// ---------- office:iframe 直挂预览网关(HEAD 预探顺便触发冷槽复活) ----------
async function pvOpenOffice(name, sizeText) {
const url = pvOfficeUrl(name);
const desk = pvDesktop();
const my = ++pvSeq;
let load;
if (desk) {
pvOpenPane(); pvClearBody();
pvHeader(name, sizeText); pvToolbar({ refresh: true, popup: false });
load = pvLoadingBox();
document.getElementById('pv-body').appendChild(load); // 开窗即刻可见,冷启动转圈等首帧
} else {
load = pvLoadingBox(); load.classList.add('inline');
pvOverlayShow(load);
if (!pvState.mobilePush) { try { history.pushState({ pvOffice: 1 }, ''); pvState.mobilePush = true; } catch (_) {} }
}
let head = null;
try { head = await fetch(url, { method: 'HEAD' }); } catch (_) {}
if (my !== pvSeq) return;
const missing = head && head.status === 404;
if (missing) {
const node = pvInfoNode(name, sizeText, '预览服务中暂无这份文档 —— 只有 AI 在本任务中生成/编辑过的文档才能在线预览(较旧的文档可能已被自动清理)。');
if (desk) { pvClearBody(); document.getElementById('pv-body').appendChild(node); }
else { const b = document.getElementById('fs-body'); b.innerHTML = ''; b.appendChild(node); }
return;
}
const fr = document.createElement('iframe');
fr.className = desk ? 'pv-frame' : 'fs-html-frame';
fr.title = String(name);
fr.src = url;
if (desk) { try { load.remove(); } catch (_) {} document.getElementById('pv-body').appendChild(fr); pvToolbar({ refresh: true, popup: true }); }
else { const b = document.getElementById('fs-body'); b.innerHTML = ''; b.appendChild(fr); }
pvState.url = url;
}
// ---------- 统一入口:所有文件点击都走这 ----------
async function openFilePreview(name, sizeText) {
if (!state.sessionId) return;
if (PV_OFFICE.test(name)) { try { await pvOpenOffice(name, sizeText); } catch (e) { toast('预览失败:' + e.message); } return; }
let kind = pvKind(name);
if (kind === 'pdf' && !navigator.pdfViewerEnabled) kind = 'none'; // WebView 内嵌不了 PDF:给占位卡,不再自动下载
const desk = pvDesktop();
const my = ++pvSeq;
if (desk) {
pvOpenPane(); pvClearBody(); // 立即开窗 + 转圈,点击零延迟可见
pvHeader(name, sizeText); pvToolbar({ refresh: false, popup: false });
document.getElementById('pv-body').appendChild(pvLoadingBox());
}
const show = (node, tb) => {
if (my !== pvSeq) return;
if (desk) {
pvClearBody(); pvHeader(name, sizeText);
document.getElementById('pv-body').appendChild(node);
if (tb) pvToolbar(tb);
} else pvOverlayShow(node);
};
if (kind === 'none') {
const low = String(name).toLowerCase();
const hint = /\.pdf$/i.test(low)
? '当前浏览器不支持页内预览 PDF,请下载后用系统查看器打开。'
: '该格式暂不支持在线预览,可下载后本地打开。';
show(pvInfoNode(name, sizeText, hint), { refresh: false, popup: false });
return;
}
let r;
try {
r = await fetch('/api/sessions/' + state.sessionId + '/files/download?path=' + encodeURIComponent(name));
if (r.status === 401) { if (my === pvSeq) location.href = '/login?next=' + encodeURIComponent(location.pathname + location.search); return; }
if (!r.ok) { let msg = 'HTTP ' + r.status; try { msg = (await r.json()).error || msg; } catch (_) {} throw new Error(msg); }
} catch (e) {
if (my === pvSeq) { desk ? show(pvInfoNode(name, sizeText, '读取失败:' + e.message), { refresh: false, popup: false }) : (pvCloseOverlayQuiet(), toast('预览失败:' + e.message)); }
return;
}
try {
if (!desk) { await pvRenderLegacy(name, r, my); return; }
let node = null, tb = { refresh: false, popup: false };
if (kind === 'html') {
const fr = document.createElement('iframe');
fr.className = 'pv-frame';
fr.setAttribute('sandbox', 'allow-same-origin allow-scripts');
fr.srcdoc = rewriteHtmlDocSrcs(await r.text(), name); // 相对资源改写,否则 about:srcdoc 基准下全 404
node = fr;
} else if (kind === 'pdf') {
const u = URL.createObjectURL(await r.blob());
pvState.blobUrl = u; pvState.url = u;
const fr = document.createElement('iframe');
fr.className = 'pv-frame'; fr.title = String(name); fr.src = u; // 不加 sandbox:内建查看器插件需要 unrestricted 帧
node = fr; tb = { refresh: false, popup: true };
} else if (kind === 'img') {
const u = URL.createObjectURL(await r.blob());
pvState.blobUrl = u; pvState.url = u;
const im = document.createElement('img');
im.className = 'pv-img'; im.src = u; im.alt = String(name);
im.addEventListener('click', () => openImageViewer(u, String(name).split('/').pop()));
node = im; tb = { refresh: false, popup: true };
} else { // text/md/代码/json/csv
node = await pvTextNode(name, sizeText, r);
if (node.__tb) { tb = node.__tb; delete node.__tb; }
}
show(node, tb);
} catch (e) {
if (my === pvSeq) desk ? show(pvInfoNode(name, sizeText, '预览失败:' + e.message), { refresh: false, popup: false }) : toast('预览失败:' + e.message);
}
}
function pvCloseOverlayQuiet() { const fs = document.getElementById('fs-viewer'); if (!fs.classList.contains('hidden') && fs.querySelector('.pv-loading')) closeFullscreen(); }
// 桌面文本渲染:md 走气泡 markdown;txt/log 原文排版;代码/配置/数据等宽 pre;二进制嗅探回退占位卡
async function pvTextNode(name, sizeText, r) {
const text = await r.text();
if (text.includes('\u0000')) return pvInfoNode(name, sizeText, '该文件不是文本格式,无法在线预览,请下载后本地打开。');
const low = String(name).toLowerCase();
if (PV_MD.test(low)) {
const q = mdHtml(text);
let html = q.html;
let cls = 'bubble-ai' + (q.fmt ? ' md' : '');
html = rewriteMdImageSrcs(html, name);
const wrap = document.createElement('div');
wrap.className = 'msg other';
wrap.innerHTML = '<div class="' + cls + ' pv-doc">' + html + '</div>';
decorateCodePre(wrap);
const n = wrap.firstChild; n.__tb = { refresh: false, popup: false };
return n;
}
if (PV_PLAIN.test(low)) {
const wrap = document.createElement('div');
wrap.className = 'msg other';
wrap.innerHTML = '<div class="bubble-ai pv-doc">' + esc(text) + '</div>';
const n = wrap.firstChild; n.__tb = { refresh: false, popup: false };
return n;
}
const frag = document.createDocumentFragment();
let bodyText = text;
if (text.length > PV_TEXT_MAX) {
bodyText = text.slice(0, PV_TEXT_MAX);
const tip = document.createElement('div');
tip.className = 'pv-trunc';
tip.textContent = '文件较大,仅预览前 ' + Math.round(PV_TEXT_MAX / 1024) + ' KB,完整内容请下载查看。';
frag.appendChild(tip);
}
const pre = document.createElement('pre');
pre.className = 'pv-pre';
pre.textContent = bodyText;
frag.appendChild(pre);
const holder = document.createElement('div');
holder.className = 'pv-plain';
holder.appendChild(frag);
holder.__tb = { refresh: false, popup: false };
return holder;
}
// 移动端非 office:保持原全屏行为(#fs-viewer)
async function pvRenderLegacy(name, r, my) {
if (/\.html?$/i.test(name)) {
const html = await r.text();
const iframe = document.createElement('iframe');
iframe.className = 'fs-html-frame';
iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts');
iframe.srcdoc = rewriteHtmlDocSrcs(html, name);
pvOverlayShow(iframe);
setFsSource(html); // 源码钮可看页面原码
if (my !== pvSeq) return;
} else if (/\.pdf$/i.test(name)) {
const u = URL.createObjectURL(await r.blob());
if (state.lastPdfBlobUrl) { try { URL.revokeObjectURL(state.lastPdfBlobUrl); } catch (_) {} }
state.lastPdfBlobUrl = u;
const frame = document.createElement('iframe');
frame.className = 'fs-html-frame';
frame.title = name;
frame.src = u;
pvOverlayShow(frame);
} else if (PV_IMG.test(name)) {
const u = URL.createObjectURL(await r.blob());
if (state.lastImgBlobUrl) { try { URL.revokeObjectURL(state.lastImgBlobUrl); } catch (_) {} }
state.lastImgBlobUrl = u;
openImageViewer(u, name);
} else {
const text = await r.text();
let cls = 'bubble-ai', html;
if (PV_MD.test(name)) {
const q = mdHtml(text);
html = q.html;
if (q.fmt) cls += ' md';
html = rewriteMdImageSrcs(html, name);
} else {
html = esc(text);
}
const wrap = document.createElement('div');
wrap.className = 'msg other';
wrap.innerHTML = '<div class="' + cls + '">' + html + '</div>';
decorateCodePre(wrap);
openFullscreen(wrap.firstChild, text); // 文件原文供 eye 钮看源码
}
}
// ---------- 组件事件 ----------
document.getElementById('pv-close').addEventListener('click', pvCloseDoc);
document.getElementById('pv-download').addEventListener('click', () => {
if (pvState.name && typeof downloadFile === 'function') downloadFile(pvState.name);
});
document.getElementById('pv-max').addEventListener('click', () => {
const max = document.body.classList.toggle('pv-max');
const btn = document.getElementById('pv-max');
const lbl = max ? '还原' : '放大';
btn.title = lbl;
btn.setAttribute('aria-label', lbl);
});
document.getElementById('pv-refresh').addEventListener('click', () => {
const f = document.getElementById('pv-body').querySelector('iframe');
if (!f) return;
try { f.contentWindow.location.reload(); } catch (_) { const s = f.src; f.src = ''; f.src = s; }
});
document.getElementById('pv-popup').addEventListener('click', () => {
if (pvState.url) window.open(pvState.url, '_blank', 'noopener');
});
// md 代码块复制钮与 fs-viewer 同一委托逻辑
document.getElementById('pv-pane').addEventListener('click', (e) => {
const b = e.target.closest('.act-copy');
if (b && typeof onCopyClick === 'function') onCopyClick(e);
});
// 移动端系统返回键:先收起 office 全屏预览
window.addEventListener('popstate', () => {
pvState.mobilePush = false;
const fs = document.getElementById('fs-viewer');
if (!fs.classList.contains('hidden') && fs.querySelector('.fs-html-frame[src^="/preview/"]')) closeFullscreen();
});
// Esc 关闭右栏(未开全屏查看器时)
window.addEventListener('keydown', (e) => {
if (e.key !== 'Escape') return;
if (!document.getElementById('fs-viewer').classList.contains('hidden')) return;
pvCloseDoc();
});
// 窗口收窄到移动端宽度:右栏收起
window.matchMedia('(min-width: 960px)').addEventListener('change', () => { if (!pvDesktop()) pvCloseDoc(); });
// ---------- 左缘拖拽调宽(预览/会话列边界):双击复位默认宽度,宽度记在 localStorage ----------
(function bindPvResize() {
const pane = document.getElementById('pv-pane');
const saved = Number(localStorage.getItem('pv-w') || 0);
if (saved > 0) document.documentElement.style.setProperty('--pv-w', saved + 'px');
const clamp = (w) => Math.max(360, Math.min(w, Math.max(360, window.innerWidth - 420)));
const h = document.createElement('div');
h.className = 'pv-resizer';
pane.appendChild(h);
let st = null;
h.addEventListener('pointerdown', (e) => {
st = { x: e.clientX, w: pane.offsetWidth || clamp(window.innerWidth * 0.5) };
try { h.setPointerCapture(e.pointerId); } catch (_) {}
document.body.classList.add('pv-resizing');
});
h.addEventListener('pointermove', (e) => {
if (!st) return;
document.documentElement.style.setProperty('--pv-w', clamp(st.w + (st.x - e.clientX)) + 'px');
});
function end() {
if (!st) return;
st = null;
document.body.classList.remove('pv-resizing');
const w = pane.offsetWidth;
if (w) localStorage.setItem('pv-w', String(w));
}
h.addEventListener('pointerup', end);
h.addEventListener('pointercancel', end);
h.addEventListener('dblclick', () => {
document.documentElement.style.removeProperty('--pv-w');
localStorage.removeItem('pv-w');
});
})();
+1
View File
@@ -154,6 +154,7 @@
closeStream();
removeTyping();
setFilesPanel(false); // 会话切换,收起文件面板防旧列表残留
if (typeof pvCloseDoc === 'function') pvCloseDoc(); // 同上:收起文档预览右栏,防旧会话内容残留
state.sessionId = id;
state.status = '';
state.schedule = null; // 防详情返回前残留上一会话的任务状态条
+2 -2
View File
@@ -50,8 +50,8 @@ self.addEventListener('fetch', (event) => {
// 只处理同源
if (url.origin !== self.location.origin) return;
// 跳过 API/SSE,避免缓存动态数据
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/sse')) return;
// 跳过 API/SSE/预览/交付取件,避免缓存动态数据(预览页需实时;/f/ 同链内容会随重新 save 变化)
if (url.pathname.startsWith('/api/') || url.pathname.startsWith('/sse') || url.pathname.startsWith('/preview') || url.pathname.startsWith('/f/')) return;
// HTML/登录页:网络优先
if (request.mode === 'navigate' || request.destination === 'document') {