This commit is contained in:
2026-04-19 16:29:59 +08:00
22 changed files with 2060 additions and 916 deletions

View File

@@ -1,4 +1,3 @@
// DOM Elements
const uploadZone = document.getElementById('uploadZone');
const fileInput = document.getElementById('fileInput');
@@ -15,6 +14,9 @@ let isRunning = false;
let pollingInterval = null;
let currentSessionId = null;
// 报告段落数据(用于润色功能)
let reportParagraphs = [];
// --- Upload Logic ---
if (uploadZone) {
uploadZone.addEventListener('dragover', (e) => {
@@ -32,7 +34,7 @@ if (uploadZone) {
if (fileInput) {
fileInput.addEventListener('change', (e) => handleFiles(e.target.files));
fileInput.addEventListener('click', (e) => e.stopPropagation()); // Prevent bubbling to uploadZone
fileInput.addEventListener('click', (e) => e.stopPropagation());
}
async function handleFiles(files) {
@@ -50,15 +52,8 @@ async function handleFiles(files) {
}
try {
const res = await fetch('/api/upload', {
method: 'POST',
body: formData
});
if (res.ok) {
console.log('Upload success');
} else {
alert('Upload failed');
}
const res = await fetch('/api/upload', { method: 'POST', body: formData });
if (!res.ok) alert('Upload failed');
} catch (e) {
console.error(e);
alert('Upload failed');
@@ -91,8 +86,6 @@ async function startAnalysis() {
if (res.ok) {
const data = await res.json();
currentSessionId = data.session_id;
console.log("Started Session:", currentSessionId);
startPolling();
switchTab('logs');
} else {
@@ -116,8 +109,6 @@ function setRunningState(running) {
statusDot.className = 'status-dot running';
statusText.innerText = 'Analyzing';
statusText.style.color = 'var(--primary-color)';
// Hide follow-up and download during run
const followUpSection = document.getElementById('followUpSection');
if (followUpSection) followUpSection.classList.add('hidden');
if (downloadScriptBtn) downloadScriptBtn.classList.add('hidden');
@@ -126,11 +117,8 @@ function setRunningState(running) {
statusDot.className = 'status-dot';
statusText.innerText = 'Completed';
statusText.style.color = 'var(--text-secondary)';
const followUpSection = document.getElementById('followUpSection');
if (currentSessionId && followUpSection) {
followUpSection.classList.remove('hidden');
}
if (currentSessionId && followUpSection) followUpSection.classList.remove('hidden');
}
}
@@ -144,32 +132,21 @@ function startPolling() {
if (!res.ok) return;
const data = await res.json();
// Update Logs
logOutput.innerText = data.log || "Waiting for output...";
// Auto scroll
const logTab = document.getElementById('logsTab');
if (logTab) logTab.scrollTop = logTab.scrollHeight;
if (!data.is_running && isRunning) {
// Finished
setRunningState(false);
clearInterval(pollingInterval);
if (data.has_report) {
await loadReport();
// 强制跳转到 Report Tab
switchTab('report');
console.log("Analysis done, switched to report tab");
}
// Check for script
if (data.script_path) {
if (downloadScriptBtn) {
downloadScriptBtn.classList.remove('hidden');
downloadScriptBtn.style.display = 'inline-flex';
}
if (data.script_path && downloadScriptBtn) {
downloadScriptBtn.classList.remove('hidden');
downloadScriptBtn.style.display = 'inline-flex';
}
}
} catch (e) {
@@ -178,7 +155,8 @@ function startPolling() {
}, 2000);
}
// --- Report Logic ---
// --- Report Logic (with paragraph-level polishing) ---
async function loadReport() {
if (!currentSessionId) return;
try {
@@ -187,14 +165,212 @@ async function loadReport() {
if (!data.content || data.content === "Report not ready.") {
reportContainer.innerHTML = '<div class="empty-state"><p>Analysis in progress or no report generated yet.</p></div>';
} else {
reportContainer.innerHTML = marked.parse(data.content);
reportParagraphs = [];
return;
}
// 保存段落数据
reportParagraphs = data.paragraphs || [];
// 渲染段落化的报告(支持点击润色)
renderParagraphReport(reportParagraphs);
} catch (e) {
reportContainer.innerHTML = '<p class="error">Failed to load report.</p>';
}
}
function renderParagraphReport(paragraphs) {
if (!paragraphs || paragraphs.length === 0) {
reportContainer.innerHTML = '<div class="empty-state"><p>No report content.</p></div>';
return;
}
let html = '';
for (const p of paragraphs) {
const renderedContent = marked.parse(p.content);
const typeClass = `para-${p.type}`;
html += `
<div class="report-paragraph ${typeClass}" data-para-id="${p.id}" onclick="selectParagraph('${p.id}')">
<div class="para-content">${renderedContent}</div>
<div class="para-actions hidden">
<button class="polish-btn" onclick="event.stopPropagation(); polishParagraph('${p.id}', 'context')" title="根据上下文润色">
<i class="fa-solid fa-wand-magic-sparkles"></i> 上下文润色
</button>
<button class="polish-btn" onclick="event.stopPropagation(); polishParagraph('${p.id}', 'data')" title="结合分析数据润色">
<i class="fa-solid fa-database"></i> 数据润色
</button>
<button class="polish-btn" onclick="event.stopPropagation(); showCustomPolish('${p.id}')" title="自定义润色指令">
<i class="fa-solid fa-pen"></i> 自定义
</button>
</div>
</div>
`;
}
reportContainer.innerHTML = html;
}
window.selectParagraph = function(paraId) {
// 取消所有选中
document.querySelectorAll('.report-paragraph').forEach(el => {
el.classList.remove('selected');
el.querySelector('.para-actions')?.classList.add('hidden');
});
// 选中当前段落
const target = document.querySelector(`[data-para-id="${paraId}"]`);
if (target) {
target.classList.add('selected');
target.querySelector('.para-actions')?.classList.remove('hidden');
}
}
window.polishParagraph = async function(paraId, mode, customInstruction = '') {
if (!currentSessionId) return;
const target = document.querySelector(`[data-para-id="${paraId}"]`);
if (!target) return;
// 显示加载状态
const actionsEl = target.querySelector('.para-actions');
const originalActions = actionsEl.innerHTML;
actionsEl.innerHTML = '<span class="polish-loading"><i class="fa-solid fa-spinner fa-spin"></i> AI 润色中...</span>';
try {
const res = await fetch('/api/report/polish', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
session_id: currentSessionId,
paragraph_id: paraId,
mode: mode,
custom_instruction: customInstruction,
})
});
if (!res.ok) {
const err = await res.json();
alert('润色失败: ' + (err.detail || 'Unknown error'));
actionsEl.innerHTML = originalActions;
return;
}
const data = await res.json();
// 显示对比视图
showPolishDiff(target, paraId, data.original, data.polished);
} catch (e) {
console.error(e);
alert('润色请求失败');
actionsEl.innerHTML = originalActions;
}
}
function showPolishDiff(targetEl, paraId, original, polished) {
const polishedHtml = marked.parse(polished);
targetEl.innerHTML = `
<div class="polish-diff">
<div class="diff-header">
<span class="diff-title"><i class="fa-solid fa-wand-magic-sparkles"></i> 润色结果预览</span>
</div>
<div class="diff-panels">
<div class="diff-panel diff-original">
<div class="diff-label">原文</div>
<div class="diff-body">${marked.parse(original)}</div>
</div>
<div class="diff-panel diff-polished">
<div class="diff-label">润色后</div>
<div class="diff-body">${polishedHtml}</div>
</div>
</div>
<div class="diff-actions">
<button class="btn btn-primary btn-sm" id="acceptBtn-${paraId}">
<i class="fa-solid fa-check"></i> 采纳
</button>
<button class="btn btn-secondary btn-sm" id="rejectBtn-${paraId}">
<i class="fa-solid fa-xmark"></i> 放弃
</button>
</div>
</div>
`;
// 用 addEventListener 绑定,避免内联 onclick 中特殊字符破坏 HTML
document.getElementById(`acceptBtn-${paraId}`).addEventListener('click', (e) => {
e.stopPropagation();
applyPolish(paraId, polished);
});
document.getElementById(`rejectBtn-${paraId}`).addEventListener('click', (e) => {
e.stopPropagation();
rejectPolish(paraId);
});
}
window.applyPolish = async function(paraId, newContent) {
if (!currentSessionId) return;
try {
const res = await fetch('/api/report/apply', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
session_id: currentSessionId,
paragraph_id: paraId,
new_content: newContent,
})
});
if (res.ok) {
// 重新加载报告
await loadReport();
} else {
alert('应用失败');
}
} catch (e) {
console.error(e);
alert('应用失败');
}
}
window.rejectPolish = function(paraId) {
// 重新加载报告恢复原状
loadReport();
}
window.showCustomPolish = function(paraId) {
const target = document.querySelector(`[data-para-id="${paraId}"]`);
if (!target) return;
const actionsEl = target.querySelector('.para-actions');
if (!actionsEl) return;
actionsEl.innerHTML = `
<div class="custom-polish-input">
<input type="text" class="form-input" id="customInput-${paraId}" placeholder="输入润色指令,如:增加数据对比、语气更正式..." style="flex:1;">
<button class="btn btn-primary btn-sm" onclick="event.stopPropagation(); submitCustomPolish('${paraId}')">
<i class="fa-solid fa-paper-plane"></i>
</button>
<button class="btn btn-secondary btn-sm" onclick="event.stopPropagation(); loadReport()">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
`;
document.getElementById(`customInput-${paraId}`)?.focus();
}
window.submitCustomPolish = function(paraId) {
const input = document.getElementById(`customInput-${paraId}`);
if (!input) return;
const instruction = input.value.trim();
if (!instruction) {
alert('请输入润色指令');
return;
}
polishParagraph(paraId, 'custom', instruction);
}
// --- Gallery Logic ---
let galleryImages = [];
let currentImageIndex = 0;
@@ -204,11 +380,9 @@ async function loadGallery() {
try {
const res = await fetch(`/api/figures?session_id=${currentSessionId}`);
const data = await res.json();
galleryImages = data.figures || [];
currentImageIndex = 0;
renderGalleryImage();
} catch (e) {
console.error("Gallery load failed", e);
document.getElementById('carouselSlide').innerHTML = '<p class="error">Failed to load images.</p>';
@@ -226,11 +400,7 @@ function renderGalleryImage() {
}
const img = galleryImages[currentImageIndex];
// Image
slide.innerHTML = `<img src="${img.web_url}" alt="${img.filename}" onclick="window.open('${img.web_url}', '_blank')">`;
// Info
info.innerHTML = `
<div class="image-title">${img.filename} (${currentImageIndex + 1}/${galleryImages.length})</div>
<div class="image-desc">${img.description || 'No description available.'}</div>
@@ -250,7 +420,7 @@ window.nextImage = function () {
renderGalleryImage();
}
// --- Download Script ---
// --- Download / Export ---
window.downloadScript = async function () {
if (!currentSessionId) return;
const link = document.createElement('a');
@@ -261,7 +431,6 @@ window.downloadScript = async function () {
document.body.removeChild(link);
}
// --- Export Report ---
window.triggerExport = async function () {
if (!currentSessionId) {
alert("No active session to export.");
@@ -273,9 +442,7 @@ window.triggerExport = async function () {
btn.disabled = true;
try {
const url = `/api/export?session_id=${currentSessionId}`;
window.open(url, '_blank');
window.open(`/api/export?session_id=${currentSessionId}`, '_blank');
} catch (e) {
alert("Export failed: " + e.message);
} finally {
@@ -332,8 +499,6 @@ async function loadHistory() {
let html = '';
data.history.forEach(item => {
// item: {id, timestamp, name}
const timeStr = item.timestamp.split(' ')[0]; // Just date for compactness
html += `
<div class="history-item" onclick="loadSession('${item.id}')" id="hist-${item.id}">
<i class="fa-regular fa-clock"></i>
@@ -342,7 +507,6 @@ async function loadHistory() {
`;
});
list.innerHTML = html;
} catch (e) {
console.error("Failed to load history", e);
}
@@ -356,30 +520,25 @@ window.loadSession = async function (sessionId) {
currentSessionId = sessionId;
// Update active class
document.querySelectorAll('.history-item').forEach(el => el.classList.remove('active'));
const activeItem = document.getElementById(`hist-${sessionId}`);
if (activeItem) activeItem.classList.add('active');
// Reset UI
logOutput.innerText = "Loading session data...";
reportContainer.innerHTML = "";
if (downloadScriptBtn) downloadScriptBtn.classList.add('hidden');
// Fetch Status to get logs and check report
try {
const res = await fetch(`/api/status?session_id=${sessionId}`);
if (res.ok) {
const data = await res.json();
logOutput.innerText = data.log || "No logs available.";
// Auto scroll log
const logTab = document.getElementById('logsTab');
if (logTab) logTab.scrollTop = logTab.scrollHeight;
if (data.has_report) {
await loadReport();
// Check if script exists
if (data.script_path && downloadScriptBtn) {
downloadScriptBtn.classList.remove('hidden');
downloadScriptBtn.style.display = 'inline-flex';
@@ -394,35 +553,29 @@ window.loadSession = async function (sessionId) {
}
}
// Initialize
// --- Init & Navigation ---
document.addEventListener('DOMContentLoaded', () => {
loadHistory();
});
// --- Navigation ---
// No-op for switchView as sidebar is simplified
window.switchView = function (viewName) {
console.log("View switch requested:", viewName);
}
window.switchTab = function (tabName) {
// Buttons
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
// Content
['logs', 'report', 'gallery'].forEach(name => {
const content = document.getElementById(`${name}Tab`);
if (content) content.classList.add('hidden');
// 找到对应的 Tab 按钮并激活
// 这里假设 Tab 按钮的 onclick 包含 tabName
document.querySelectorAll('.tab').forEach(btn => {
if (btn.getAttribute('onclick') && btn.getAttribute('onclick').includes(`'${tabName}'`)) {
btn.classList.add('active');
}
});
});
// Valid tabs logic
document.querySelectorAll('.tab').forEach(btn => {
if (btn.getAttribute('onclick') && btn.getAttribute('onclick').includes(`'${tabName}'`)) {
btn.classList.add('active');
}
});
if (tabName === 'logs') {
document.getElementById('logsTab').classList.remove('hidden');
} else if (tabName === 'report') {