更新前端页交互模式

This commit is contained in:
2026-01-31 20:27:17 +08:00
parent 5eb13324c2
commit e9644360ce
7 changed files with 1050 additions and 937 deletions

View File

@@ -1,4 +1,5 @@
// DOM Elements
const uploadZone = document.getElementById('uploadZone');
const fileInput = document.getElementById('fileInput');
const fileList = document.getElementById('fileList');
@@ -8,7 +9,7 @@ const statusDot = document.getElementById('statusDot');
const statusText = document.getElementById('statusText');
const logOutput = document.getElementById('logOutput');
const reportContainer = document.getElementById('reportContainer');
const galleryContainer = document.getElementById('galleryContainer');
const downloadScriptBtn = document.getElementById('downloadScriptBtn');
let isRunning = false;
let pollingInterval = null;
@@ -26,9 +27,12 @@ if (uploadZone) {
uploadZone.classList.remove('dragover');
handleFiles(e.dataTransfer.files);
});
uploadZone.addEventListener('click', () => fileInput.click());
}
if (fileInput) {
fileInput.addEventListener('change', (e) => handleFiles(e.target.files));
fileInput.addEventListener('click', (e) => e.stopPropagation()); // Prevent bubbling to uploadZone
}
async function handleFiles(files) {
@@ -40,9 +44,8 @@ async function handleFiles(files) {
for (const file of files) {
formData.append('files', file);
const fileItem = document.createElement('div');
fileItem.innerText = `📄 ${file.name}`;
fileItem.style.fontSize = '0.8rem';
fileItem.style.color = '#fff';
fileItem.className = 'file-item';
fileItem.innerHTML = `<i class="fa-regular fa-file-excel"></i> ${file.name}`;
fileList.appendChild(fileItem);
}
@@ -52,8 +55,7 @@ async function handleFiles(files) {
body: formData
});
if (res.ok) {
const data = await res.json();
console.log('Upload success:', data);
console.log('Upload success');
} else {
alert('Upload failed');
}
@@ -63,63 +65,75 @@ async function handleFiles(files) {
}
}
// --- Start Analysis ---
// --- Analysis Logic ---
if (startBtn) {
startBtn.addEventListener('click', async () => {
if (isRunning) return;
startBtn.addEventListener('click', startAnalysis);
}
const requirement = requirementInput.value.trim();
if (!requirement) {
alert('Please enter analysis requirement');
return;
}
async function startAnalysis() {
if (isRunning) return;
setRunningState(true);
const requirement = requirementInput.value.trim();
if (!requirement) {
alert('Please enter analysis requirement');
return;
}
try {
const res = await fetch('/api/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ requirement })
});
setRunningState(true);
if (res.ok) {
const data = await res.json();
currentSessionId = data.session_id; // Store Session ID
console.log("Started Session:", currentSessionId);
try {
const res = await fetch('/api/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ requirement })
});
startPolling();
switchTab('logs');
} else {
const err = await res.json();
alert('Failed to start: ' + err.detail);
setRunningState(false);
}
} catch (e) {
console.error(e);
alert('Error starting analysis');
if (res.ok) {
const data = await res.json();
currentSessionId = data.session_id;
console.log("Started Session:", currentSessionId);
startPolling();
switchTab('logs');
} else {
const err = await res.json();
alert('Failed to start: ' + err.detail);
setRunningState(false);
}
});
} catch (e) {
console.error(e);
alert('Error starting analysis');
setRunningState(false);
}
}
function setRunningState(running) {
isRunning = running;
startBtn.disabled = running;
startBtn.innerHTML = running ? '<i class="fa-solid fa-spinner fa-spin"></i> Running...' : '<i class="fa-solid fa-play"></i> Start Analysis';
if (running) {
statusDot.className = 'dot running';
statusText.innerText = 'Analysis in Progress';
if (document.getElementById('followUpSection')) document.getElementById('followUpSection').style.display = 'none';
startBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Analysis in Progress...';
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');
} else {
statusDot.className = 'dot done';
startBtn.innerHTML = '<i class="fa-solid fa-play"></i> Start Analysis';
statusDot.className = 'status-dot';
statusText.innerText = 'Completed';
if (currentSessionId && document.getElementById('followUpSection')) document.getElementById('followUpSection').style.display = 'flex';
statusText.style.color = 'var(--text-secondary)';
const followUpSection = document.getElementById('followUpSection');
if (currentSessionId && followUpSection) {
followUpSection.classList.remove('hidden');
}
}
}
// --- Status Polling ---
function startPolling() {
if (pollingInterval) clearInterval(pollingInterval);
if (!currentSessionId) return;
@@ -131,20 +145,31 @@ function startPolling() {
const data = await res.json();
// Update Logs
logOutput.innerText = data.log || "Waiting for logs...";
// Auto scroll to bottom
const term = document.querySelector('.terminal-window');
if (term) term.scrollTop = term.scrollHeight;
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) {
// Just finished
// Finished
setRunningState(false);
clearInterval(pollingInterval);
if (data.has_report) {
loadReport();
loadGallery(); // Load images when done
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';
}
}
}
} catch (e) {
@@ -153,129 +178,122 @@ function startPolling() {
}, 2000);
}
// --- Report Logic ---
async function loadReport() {
if (!currentSessionId) return;
try {
const res = await fetch(`/api/report?session_id=${currentSessionId}`);
const data = await res.json();
// Render Markdown
reportContainer.innerHTML = marked.parse(data.content);
// Fix images relative path for display if needed
// The backend should return a base_path or we handle it here
if (data.base_path) {
// Backend already handled replacement?
// The backend returns content with updated paths.
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);
}
} catch (e) {
reportContainer.innerHTML = '<p class="error">Failed to load report.</p>';
console.error(e);
}
}
// --- Gallery Logic ---
let galleryImages = [];
let currentImageIndex = 0;
async function loadGallery() {
if (!currentSessionId) return;
// Switch to gallery view logic if we were already there
// But this is just data loading
try {
const res = await fetch(`/api/figures?session_id=${currentSessionId}`);
const data = await res.json();
const galleryGrid = document.getElementById('galleryContainer');
if (!data.figures || data.figures.length === 0) {
galleryGrid.innerHTML = `
<div class="empty-state">
<i class="fa-solid fa-images"></i>
<p>No images generated in this session.</p>
</div>
`;
return;
}
let html = '';
data.figures.forEach(fig => {
html += `
<div class="gallery-card">
<div class="img-wrapper">
<img src="${fig.web_url}" alt="${fig.filename}" onclick="window.open('${fig.web_url}', '_blank')">
</div>
<div class="card-content">
<h4>${fig.filename}</h4>
<p class="desc">${fig.description || 'No description'}</p>
${fig.analysis ? `<div class="analysis-box"><i class="fa-solid fa-magnifying-glass"></i> ${fig.analysis}</div>` : ''}
</div>
</div>
`;
});
galleryGrid.innerHTML = html;
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>';
}
}
// --- Export Report ---
function renderGalleryImage() {
const slide = document.getElementById('carouselSlide');
const info = document.getElementById('imageInfo');
if (galleryImages.length === 0) {
slide.innerHTML = '<p class="placeholder-text" style="color:var(--text-secondary);">No images generated in this session.</p>';
info.innerHTML = '';
return;
}
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>
${img.analysis ? `<div style="font-size:0.8rem; margin-top:0.5rem; color:#4B5563; background:#F3F4F6; padding:0.5rem; border-radius:4px;">${img.analysis}</div>` : ''}
`;
}
window.prevImage = function () {
if (galleryImages.length === 0) return;
currentImageIndex = (currentImageIndex - 1 + galleryImages.length) % galleryImages.length;
renderGalleryImage();
}
window.nextImage = function () {
if (galleryImages.length === 0) return;
currentImageIndex = (currentImageIndex + 1) % galleryImages.length;
renderGalleryImage();
}
// --- Download Script ---
window.downloadScript = async function () {
if (!currentSessionId) return;
const link = document.createElement('a');
link.href = `/api/download_script?session_id=${currentSessionId}`;
link.download = '';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// --- Export Report ---
window.triggerExport = async function () {
if (!currentSessionId) {
alert("No active session to export.");
return;
}
const btn = document.getElementById('exportBtn');
const originalText = btn.innerHTML;
const originalContent = btn.innerHTML;
btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Zipping...';
btn.disabled = true;
try {
const url = `/api/export?session_id=${currentSessionId}`;
const res = await fetch(url); // Default GET
window.open(url, '_blank');
if (res.ok) {
const blob = await res.blob();
const downloadUrl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = downloadUrl;
a.download = `analysis_export_${currentSessionId}.zip`;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(downloadUrl);
} else {
// Try to parse error
let errMsg = "Unknown error";
try {
const err = await res.json();
errMsg = err.detail || errMsg;
} catch (jsonErr) {
errMsg = res.statusText;
}
alert("Export failed: " + errMsg);
}
} catch (e) {
alert("Export failed: " + e.message);
} finally {
btn.innerHTML = originalText;
btn.disabled = false;
setTimeout(() => {
btn.innerHTML = originalContent;
btn.disabled = false;
}, 2000);
}
}
// --- Follow-up Chat ---
window.sendFollowUp = async function () {
if (!currentSessionId || isRunning) return;
const input = document.getElementById('followUpInput');
const message = input.value.trim();
if (!message) return;
// UI Loading state
const btn = document.getElementById('sendFollowUpBtn');
btn.disabled = true;
input.disabled = true;
try {
const res = await fetch('/api/chat', {
method: 'POST',
@@ -289,128 +307,128 @@ window.sendFollowUp = async function () {
startPolling();
switchTab('logs');
} else {
const err = await res.json();
alert('Error: ' + err.detail);
alert('Failed to send request');
}
} catch (e) {
console.error(e);
alert('Failed to send request');
} finally {
btn.disabled = false;
input.disabled = false;
}
}
// --- History Logic ---
async function loadHistory() {
const list = document.getElementById('historyList');
if (!list) return;
try {
const res = await fetch('/api/history');
const data = await res.json();
// --- Tabs (Inner) ---
window.switchTab = function (tabName) {
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
if (data.history.length === 0) {
list.innerHTML = '<div style="padding:0.5rem; font-size:0.8rem; color:#9CA3AF;">No history yet</div>';
return;
}
const btn = document.querySelector(`button[onclick="switchTab('${tabName}')"]`);
if (btn) btn.classList.add('active');
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>
<span>${item.id}</span>
</div>
`;
});
list.innerHTML = html;
const tab = document.getElementById(`${tabName}Tab`);
if (tab) tab.classList.add('active');
} catch (e) {
console.error("Failed to load history", e);
}
}
// --- View Navigation (Outer Sidebar) ---
window.switchView = function (viewName) {
// 1. Update Sidebar Buttons
document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'));
const navBtn = document.querySelector(`button[onclick="switchView('${viewName}')"]`);
if (navBtn) navBtn.classList.add('active');
window.loadSession = async function (sessionId) {
if (isRunning) {
alert("Analysis in progress, please wait.");
return;
}
// 2. Switch Main Content Sections
const viewId = 'view' + viewName.charAt(0).toUpperCase() + viewName.slice(1);
currentSessionId = sessionId;
document.querySelectorAll('.view-section').forEach(v => {
// Hide all
v.style.display = 'none';
v.classList.remove('active');
});
// 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');
const activeView = document.getElementById(viewId);
if (activeView) {
// Analysis view uses flex for layout (logs scrolling), others use block
if (viewName === 'analysis') {
activeView.style.display = 'flex';
activeView.style.flexDirection = 'column';
} else {
activeView.style.display = 'block';
// If switching to gallery, reload it if session exists
if (viewName === 'gallery' && currentSessionId) {
loadGallery();
// 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';
}
switchTab('report');
} else {
switchTab('logs');
}
}
activeView.classList.add('active');
}
// 3. Toggle Sidebar Controls (only show Analysis Controls in analysis view)
const analysisControls = document.getElementById('analysisControls');
if (analysisControls) {
analysisControls.style.display = (viewName === 'analysis') ? 'block' : 'none';
} catch (e) {
logOutput.innerText = "Error loading session.";
}
}
// --- Tool Functions ---
window.triggerMerge = async function () {
const sourceDir = document.getElementById('mergeSource').value;
const resultDiv = document.getElementById('mergeResult');
// Initialize
document.addEventListener('DOMContentLoaded', () => {
loadHistory();
});
resultDiv.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Merging...';
// --- Navigation ---
// No-op for switchView as sidebar is simplified
window.switchView = function (viewName) {
console.log("View switch requested:", viewName);
}
try {
const res = await fetch('/api/tools/merge', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ source_dir: sourceDir, output_filename: 'merged_output.csv' })
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');
}
});
const data = await res.json();
if (data.status === 'success') {
resultDiv.innerHTML = `<span style="color:var(--success)"><i class="fa-solid fa-check"></i> ${data.message}</span>`;
} else {
resultDiv.innerHTML = `<span style="color:var(--warning)">${data.message}</span>`;
}
} catch (e) {
resultDiv.innerHTML = `<span style="color:red">Error: ${e.message}</span>`;
}
}
window.triggerSort = async function () {
const targetFile = document.getElementById('sortTarget').value;
const resultDiv = document.getElementById('sortResult');
resultDiv.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Sorting...';
try {
const res = await fetch('/api/tools/sort', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ target_file: targetFile })
});
const data = await res.json();
if (data.status === 'success') {
resultDiv.innerHTML = `<span style="color:var(--success)"><i class="fa-solid fa-check"></i> ${data.message}</span>`;
} else {
resultDiv.innerHTML = `<span style="color:var(--warning)">${data.message}</span>`;
}
} catch (e) {
resultDiv.innerHTML = `<span style="color:red">Error: ${e.message}</span>`;
}
}
// --- Help Functions ---
window.fetchHelp = async function () {
const container = document.getElementById('helpContainer');
container.innerHTML = 'Loading...';
try {
const res = await fetch('/api/help/troubleshooting');
const data = await res.json();
container.innerHTML = marked.parse(data.content);
} catch (e) {
container.innerHTML = 'Failed to load guide.';
});
// Valid tabs logic
if (tabName === 'logs') {
document.getElementById('logsTab').classList.remove('hidden');
} else if (tabName === 'report') {
document.getElementById('reportTab').classList.remove('hidden');
} else if (tabName === 'gallery') {
document.getElementById('galleryTab').classList.remove('hidden');
if (currentSessionId) loadGallery();
}
}