900 lines
31 KiB
JavaScript
900 lines
31 KiB
JavaScript
// DOM Elements
|
|
const uploadZone = document.getElementById('uploadZone');
|
|
const fileInput = document.getElementById('fileInput');
|
|
const fileList = document.getElementById('fileList');
|
|
const startBtn = document.getElementById('startBtn');
|
|
const requirementInput = document.getElementById('requirementInput');
|
|
const statusDot = document.getElementById('statusDot');
|
|
const statusText = document.getElementById('statusText');
|
|
const reportContainer = document.getElementById('reportContainer');
|
|
const downloadScriptBtn = document.getElementById('downloadScriptBtn');
|
|
|
|
let isRunning = false;
|
|
let pollingInterval = null;
|
|
let currentSessionId = null;
|
|
let selectedTemplate = '';
|
|
|
|
// 报告段落数据(用于润色功能)
|
|
let reportParagraphs = [];
|
|
|
|
// Supporting data from report API
|
|
let supportingData = {};
|
|
|
|
// Execution Process state
|
|
let lastRenderedRound = 0;
|
|
|
|
// --- Progress Bar ---
|
|
function updateProgressBar(percentage, message, currentRound, maxRounds) {
|
|
const container = document.getElementById('progressBarContainer');
|
|
const fill = document.getElementById('progressBarFill');
|
|
const label = document.getElementById('progressLabel');
|
|
const percent = document.getElementById('progressPercent');
|
|
const msg = document.getElementById('progressMessage');
|
|
if (!container || !fill) return;
|
|
|
|
container.classList.remove('hidden');
|
|
fill.style.width = percentage + '%';
|
|
if (label) label.textContent = `Round ${currentRound || 0}/${maxRounds || 0}`;
|
|
if (percent) percent.textContent = Math.round(percentage) + '%';
|
|
if (msg) msg.textContent = message || '';
|
|
}
|
|
|
|
function hideProgressBar() {
|
|
const container = document.getElementById('progressBarContainer');
|
|
if (container) container.classList.add('hidden');
|
|
}
|
|
|
|
// --- Upload Logic ---
|
|
if (uploadZone) {
|
|
uploadZone.addEventListener('dragover', (e) => {
|
|
e.preventDefault();
|
|
uploadZone.classList.add('dragover');
|
|
});
|
|
uploadZone.addEventListener('dragleave', () => uploadZone.classList.remove('dragover'));
|
|
uploadZone.addEventListener('drop', (e) => {
|
|
e.preventDefault();
|
|
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());
|
|
}
|
|
|
|
// Track all uploaded file paths for this session
|
|
let uploadedFilePaths = [];
|
|
|
|
async function handleFiles(files) {
|
|
if (files.length === 0) return;
|
|
|
|
const formData = new FormData();
|
|
for (const file of files) {
|
|
formData.append('files', file);
|
|
}
|
|
|
|
try {
|
|
const res = await fetch('/api/upload', { method: 'POST', body: formData });
|
|
if (!res.ok) { alert('Upload failed'); return; }
|
|
const data = await res.json();
|
|
// Accumulate uploaded paths
|
|
if (data.paths) {
|
|
uploadedFilePaths = uploadedFilePaths.concat(data.paths);
|
|
}
|
|
renderFileList();
|
|
} catch (e) {
|
|
console.error(e);
|
|
alert('Upload failed');
|
|
}
|
|
}
|
|
|
|
function renderFileList() {
|
|
fileList.innerHTML = '';
|
|
for (let i = 0; i < uploadedFilePaths.length; i++) {
|
|
const fname = uploadedFilePaths[i].split('/').pop().split('\\').pop();
|
|
const fileItem = document.createElement('div');
|
|
fileItem.className = 'file-item';
|
|
fileItem.innerHTML = `<i class="fa-regular fa-file-excel"></i> ${fname}
|
|
<span class="file-remove" onclick="removeUploadedFile(${i})" title="移除">×</span>`;
|
|
fileList.appendChild(fileItem);
|
|
}
|
|
}
|
|
|
|
window.removeUploadedFile = function(index) {
|
|
uploadedFilePaths.splice(index, 1);
|
|
renderFileList();
|
|
}
|
|
|
|
// --- Template Logic ---
|
|
async function loadTemplates() {
|
|
try {
|
|
const res = await fetch('/api/templates');
|
|
if (!res.ok) return;
|
|
const data = await res.json();
|
|
const selector = document.getElementById('templateSelector');
|
|
if (!selector || !data.templates) return;
|
|
|
|
for (const tpl of data.templates) {
|
|
const card = document.createElement('div');
|
|
card.className = 'template-card';
|
|
card.setAttribute('data-template', tpl.name);
|
|
card.onclick = function() { selectTemplate(this, tpl.name); };
|
|
card.innerHTML = `<div class="template-card-title">${tpl.display_name}</div><div class="template-card-desc">${tpl.description}</div>`;
|
|
selector.appendChild(card);
|
|
}
|
|
} catch (e) {
|
|
console.error('Failed to load templates', e);
|
|
}
|
|
}
|
|
|
|
window.selectTemplate = function(el, name) {
|
|
document.querySelectorAll('.template-card').forEach(c => c.classList.remove('selected'));
|
|
el.classList.add('selected');
|
|
selectedTemplate = name;
|
|
}
|
|
|
|
// --- Analysis Logic ---
|
|
if (startBtn) {
|
|
startBtn.addEventListener('click', startAnalysis);
|
|
}
|
|
|
|
async function startAnalysis() {
|
|
if (isRunning) return;
|
|
|
|
const requirement = requirementInput.value.trim();
|
|
if (!requirement) {
|
|
alert('Please enter analysis requirement');
|
|
return;
|
|
}
|
|
|
|
setRunningState(true);
|
|
// Reset execution state for new analysis
|
|
lastRenderedRound = 0;
|
|
const wrapper = document.getElementById('roundCardsWrapper');
|
|
if (wrapper) wrapper.innerHTML = '';
|
|
const emptyState = document.getElementById('executionEmptyState');
|
|
if (emptyState) emptyState.remove();
|
|
|
|
try {
|
|
const body = { requirement };
|
|
if (selectedTemplate) {
|
|
body.template = selectedTemplate;
|
|
}
|
|
if (uploadedFilePaths.length > 0) {
|
|
body.files = uploadedFilePaths;
|
|
}
|
|
|
|
const res = await fetch('/api/start', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(body)
|
|
});
|
|
|
|
if (res.ok) {
|
|
const data = await res.json();
|
|
currentSessionId = data.session_id;
|
|
startPolling();
|
|
switchTab('execution');
|
|
} 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;
|
|
|
|
if (running) {
|
|
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)';
|
|
const followUpSection = document.getElementById('followUpSection');
|
|
if (followUpSection) followUpSection.classList.add('hidden');
|
|
if (downloadScriptBtn) downloadScriptBtn.classList.add('hidden');
|
|
const tplGroup = document.getElementById('templateSelectorGroup');
|
|
if (tplGroup) tplGroup.classList.add('hidden');
|
|
} else {
|
|
startBtn.innerHTML = '<i class="fa-solid fa-play"></i> Start Analysis';
|
|
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');
|
|
}
|
|
}
|
|
|
|
// --- Polling ---
|
|
function startPolling() {
|
|
if (pollingInterval) clearInterval(pollingInterval);
|
|
if (!currentSessionId) return;
|
|
|
|
pollingInterval = setInterval(async () => {
|
|
try {
|
|
const res = await fetch(`/api/status?session_id=${currentSessionId}`);
|
|
if (!res.ok) return;
|
|
const data = await res.json();
|
|
|
|
// Render round cards incrementally
|
|
const rounds = data.rounds || [];
|
|
renderRoundCards(rounds);
|
|
|
|
// Load data files during polling
|
|
loadDataFiles();
|
|
|
|
// Update progress bar during analysis
|
|
// Use rounds.length (actual completed analysis rounds) for display
|
|
// instead of current_round (which includes non-code rounds like collect_figures)
|
|
if (data.is_running && data.progress_percentage !== undefined) {
|
|
const displayRound = rounds.length || data.current_round || 0;
|
|
updateProgressBar(data.progress_percentage, data.status_message, displayRound, data.max_rounds);
|
|
}
|
|
|
|
if (!data.is_running && isRunning) {
|
|
const displayRound = rounds.length || data.current_round || data.max_rounds;
|
|
updateProgressBar(100, 'Analysis complete', displayRound, data.max_rounds);
|
|
setTimeout(hideProgressBar, 3000);
|
|
|
|
setRunningState(false);
|
|
clearInterval(pollingInterval);
|
|
|
|
// Final render of rounds
|
|
renderRoundCards(data.rounds || []);
|
|
loadDataFiles();
|
|
|
|
if (data.has_report) {
|
|
await loadReport();
|
|
switchTab('report');
|
|
}
|
|
if (data.script_path && downloadScriptBtn) {
|
|
downloadScriptBtn.classList.remove('hidden');
|
|
downloadScriptBtn.style.display = 'inline-flex';
|
|
}
|
|
}
|
|
} catch (e) {
|
|
console.error('Polling error', e);
|
|
}
|
|
}, 2000);
|
|
}
|
|
|
|
// --- Execution Process Tab (Task 11) ---
|
|
|
|
function renderRoundCards(rounds) {
|
|
if (!rounds || rounds.length === 0) return;
|
|
|
|
const wrapper = document.getElementById('roundCardsWrapper');
|
|
if (!wrapper) return;
|
|
|
|
// Handle server restart: if rounds shrunk, re-render all
|
|
if (rounds.length < lastRenderedRound) {
|
|
lastRenderedRound = 0;
|
|
wrapper.innerHTML = '';
|
|
}
|
|
|
|
// Remove empty state if present
|
|
const emptyState = document.getElementById('executionEmptyState');
|
|
if (emptyState) emptyState.remove();
|
|
|
|
// Only render new rounds
|
|
for (let i = lastRenderedRound; i < rounds.length; i++) {
|
|
const rd = rounds[i];
|
|
const card = createRoundCard(rd);
|
|
wrapper.appendChild(card);
|
|
}
|
|
|
|
lastRenderedRound = rounds.length;
|
|
|
|
// Auto-scroll when running
|
|
if (isRunning) {
|
|
const executionTab = document.getElementById('executionTab');
|
|
if (executionTab) {
|
|
executionTab.scrollTop = executionTab.scrollHeight;
|
|
}
|
|
}
|
|
}
|
|
|
|
function createRoundCard(rd) {
|
|
const roundNum = rd.round || 0;
|
|
const summary = escapeHtml(rd.result_summary || '');
|
|
const reasoning = escapeHtml(rd.reasoning || '');
|
|
const code = escapeHtml(rd.code || '');
|
|
const rawLog = escapeHtml(rd.raw_log || '');
|
|
|
|
const card = document.createElement('div');
|
|
card.className = 'round-card';
|
|
card.setAttribute('data-round', roundNum);
|
|
|
|
// Build evidence table HTML
|
|
let evidenceHtml = '';
|
|
const evidenceRows = rd.evidence_rows || [];
|
|
if (evidenceRows.length > 0) {
|
|
const cols = Object.keys(evidenceRows[0]);
|
|
evidenceHtml = `
|
|
<div class="round-section">
|
|
<div class="round-section-title">本轮数据案例</div>
|
|
<table class="evidence-table">
|
|
<thead><tr>${cols.map(c => `<th>${escapeHtml(c)}</th>`).join('')}</tr></thead>
|
|
<tbody>${evidenceRows.map(row =>
|
|
`<tr>${cols.map(c => `<td>${escapeHtml(String(row[c] ?? ''))}</td>`).join('')}</tr>`
|
|
).join('')}</tbody>
|
|
</table>
|
|
</div>`;
|
|
}
|
|
|
|
card.innerHTML = `
|
|
<div class="round-card-header" onclick="toggleRoundCard(${roundNum})">
|
|
<span class="round-number">Round ${roundNum}</span>
|
|
<span class="round-summary">${summary}</span>
|
|
<i class="fa-solid fa-chevron-down round-toggle-icon"></i>
|
|
</div>
|
|
<div class="round-card-body hidden">
|
|
<div class="round-section">
|
|
<div class="round-section-title">AI 推理</div>
|
|
<div class="round-reasoning">${reasoning}</div>
|
|
</div>
|
|
<details class="round-details">
|
|
<summary>代码</summary>
|
|
<pre class="round-code">${code}</pre>
|
|
</details>
|
|
<div class="round-section">
|
|
<div class="round-section-title">执行结果</div>
|
|
<div class="round-result">${summary}</div>
|
|
</div>
|
|
${evidenceHtml}
|
|
<details class="round-details">
|
|
<summary>原始日志</summary>
|
|
<pre class="round-raw-log">${rawLog}</pre>
|
|
</details>
|
|
</div>
|
|
`;
|
|
|
|
return card;
|
|
}
|
|
|
|
window.toggleRoundCard = function(roundNum) {
|
|
const card = document.querySelector(`.round-card[data-round="${roundNum}"]`);
|
|
if (!card) return;
|
|
const body = card.querySelector('.round-card-body');
|
|
const icon = card.querySelector('.round-toggle-icon');
|
|
if (!body) return;
|
|
|
|
body.classList.toggle('hidden');
|
|
if (icon) {
|
|
icon.classList.toggle('fa-chevron-down');
|
|
icon.classList.toggle('fa-chevron-up');
|
|
}
|
|
card.classList.toggle('expanded');
|
|
}
|
|
|
|
function escapeHtml(text) {
|
|
const div = document.createElement('div');
|
|
div.textContent = text;
|
|
return div.innerHTML;
|
|
}
|
|
|
|
// --- Data Files Tab (Task 12) ---
|
|
|
|
async function loadDataFiles() {
|
|
if (!currentSessionId) return;
|
|
try {
|
|
const res = await fetch(`/api/data-files?session_id=${currentSessionId}`);
|
|
if (!res.ok) return;
|
|
const data = await res.json();
|
|
const files = data.files || [];
|
|
|
|
const grid = document.getElementById('fileCardsGrid');
|
|
const emptyState = document.getElementById('datafilesEmptyState');
|
|
if (!grid) return;
|
|
|
|
if (files.length === 0) {
|
|
grid.innerHTML = '';
|
|
if (emptyState) emptyState.classList.remove('hidden');
|
|
return;
|
|
}
|
|
|
|
if (emptyState) emptyState.classList.add('hidden');
|
|
|
|
grid.innerHTML = files.map(f => {
|
|
const desc = escapeHtml(f.description || '');
|
|
const name = escapeHtml(f.filename || '');
|
|
const rows = f.rows || 0;
|
|
const iconClass = name.endsWith('.xlsx') ? 'fa-file-excel' : 'fa-file-csv';
|
|
return `
|
|
<div class="data-file-card" onclick="previewDataFile('${escapeHtml(f.filename)}')">
|
|
<div class="data-file-icon"><i class="fa-regular ${iconClass}"></i></div>
|
|
<div class="data-file-info">
|
|
<div class="data-file-name">${name}</div>
|
|
<div class="data-file-desc">${desc} · ${rows}行</div>
|
|
</div>
|
|
<button class="btn btn-sm btn-secondary" onclick="event.stopPropagation(); downloadDataFile('${escapeHtml(f.filename)}')">
|
|
<i class="fa-solid fa-download"></i>
|
|
</button>
|
|
</div>`;
|
|
}).join('');
|
|
} catch (e) {
|
|
console.error('Failed to load data files', e);
|
|
}
|
|
}
|
|
|
|
window.previewDataFile = async function(filename) {
|
|
if (!currentSessionId) return;
|
|
try {
|
|
const res = await fetch(`/api/data-files/preview?session_id=${currentSessionId}&filename=${encodeURIComponent(filename)}`);
|
|
if (!res.ok) {
|
|
alert('Failed to load preview');
|
|
return;
|
|
}
|
|
const data = await res.json();
|
|
const columns = data.columns || [];
|
|
const rows = data.rows || [];
|
|
|
|
const panel = document.getElementById('dataPreviewPanel');
|
|
const nameEl = document.getElementById('previewFileName');
|
|
const container = document.getElementById('previewTableContainer');
|
|
if (!panel || !container) return;
|
|
|
|
nameEl.textContent = filename;
|
|
|
|
let tableHtml = '<table class="data-preview-table">';
|
|
tableHtml += '<thead><tr>' + columns.map(c => `<th>${escapeHtml(c)}</th>`).join('') + '</tr></thead>';
|
|
tableHtml += '<tbody>';
|
|
for (const row of rows) {
|
|
tableHtml += '<tr>' + columns.map(c => `<td>${escapeHtml(String(row[c] ?? ''))}</td>`).join('') + '</tr>';
|
|
}
|
|
tableHtml += '</tbody></table>';
|
|
|
|
container.innerHTML = tableHtml;
|
|
panel.classList.remove('hidden');
|
|
} catch (e) {
|
|
console.error('Preview failed', e);
|
|
}
|
|
}
|
|
|
|
window.downloadDataFile = function(filename) {
|
|
if (!currentSessionId) return;
|
|
const link = document.createElement('a');
|
|
link.href = `/api/data-files/download?session_id=${currentSessionId}&filename=${encodeURIComponent(filename)}`;
|
|
link.download = '';
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
document.body.removeChild(link);
|
|
}
|
|
|
|
window.closePreview = function() {
|
|
const panel = document.getElementById('dataPreviewPanel');
|
|
if (panel) panel.classList.add('hidden');
|
|
}
|
|
|
|
// --- Report Logic with Supporting Data (Task 14) ---
|
|
|
|
async function loadReport() {
|
|
if (!currentSessionId) return;
|
|
try {
|
|
const res = await fetch(`/api/report?session_id=${currentSessionId}`);
|
|
const data = await res.json();
|
|
|
|
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>';
|
|
reportParagraphs = [];
|
|
supportingData = {};
|
|
return;
|
|
}
|
|
|
|
reportParagraphs = data.paragraphs || [];
|
|
supportingData = data.supporting_data || {};
|
|
|
|
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}`;
|
|
const hasSupportingData = supportingData[p.id] && supportingData[p.id].length > 0;
|
|
const supportingBtn = hasSupportingData
|
|
? `<button class="supporting-data-btn" onclick="event.stopPropagation(); showSupportingData('${p.id}')"><i class="fa-solid fa-table"></i> 查看支撑数据</button>`
|
|
: '';
|
|
html += `
|
|
<div class="report-paragraph ${typeClass}" data-para-id="${p.id}" onclick="selectParagraph('${p.id}')">
|
|
<div class="para-content">${renderedContent}</div>
|
|
${supportingBtn}
|
|
<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.showSupportingData = function(paraId) {
|
|
const rows = supportingData[paraId];
|
|
if (!rows || rows.length === 0) return;
|
|
|
|
const modal = document.getElementById('supportingDataModal');
|
|
const body = document.getElementById('supportingDataBody');
|
|
if (!modal || !body) return;
|
|
|
|
const cols = Object.keys(rows[0]);
|
|
let tableHtml = '<table class="evidence-table">';
|
|
tableHtml += '<thead><tr>' + cols.map(c => `<th>${escapeHtml(c)}</th>`).join('') + '</tr></thead>';
|
|
tableHtml += '<tbody>';
|
|
for (const row of rows) {
|
|
tableHtml += '<tr>' + cols.map(c => `<td>${escapeHtml(String(row[c] ?? ''))}</td>`).join('') + '</tr>';
|
|
}
|
|
tableHtml += '</tbody></table>';
|
|
|
|
body.innerHTML = tableHtml;
|
|
modal.classList.remove('hidden');
|
|
}
|
|
|
|
window.closeSupportingData = function() {
|
|
const modal = document.getElementById('supportingDataModal');
|
|
if (modal) modal.classList.add('hidden');
|
|
}
|
|
|
|
// --- Paragraph Selection & Polishing (preserved from original) ---
|
|
|
|
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>
|
|
`;
|
|
|
|
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);
|
|
}
|
|
|
|
// --- Download / Export ---
|
|
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);
|
|
}
|
|
|
|
window.triggerExport = async function () {
|
|
if (!currentSessionId) {
|
|
alert("No active session to export.");
|
|
return;
|
|
}
|
|
const btn = document.getElementById('exportBtn');
|
|
const originalContent = btn.innerHTML;
|
|
btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Zipping...';
|
|
btn.disabled = true;
|
|
|
|
try {
|
|
window.open(`/api/export?session_id=${currentSessionId}`, '_blank');
|
|
} catch (e) {
|
|
alert("Export failed: " + e.message);
|
|
} finally {
|
|
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;
|
|
|
|
input.disabled = true;
|
|
try {
|
|
const res = await fetch('/api/chat', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ session_id: currentSessionId, message: message })
|
|
});
|
|
|
|
if (res.ok) {
|
|
input.value = '';
|
|
setRunningState(true);
|
|
// Reset round rendering for follow-up
|
|
lastRenderedRound = 0;
|
|
const wrapper = document.getElementById('roundCardsWrapper');
|
|
if (wrapper) wrapper.innerHTML = '';
|
|
startPolling();
|
|
switchTab('execution');
|
|
} else {
|
|
alert('Failed to send request');
|
|
}
|
|
} catch (e) {
|
|
console.error(e);
|
|
} finally {
|
|
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();
|
|
|
|
if (data.history.length === 0) {
|
|
list.innerHTML = '<div style="padding:0.5rem; font-size:0.8rem; color:#9CA3AF;">No history yet</div>';
|
|
return;
|
|
}
|
|
|
|
let html = '';
|
|
data.history.forEach(item => {
|
|
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;
|
|
} catch (e) {
|
|
console.error("Failed to load history", e);
|
|
}
|
|
}
|
|
|
|
window.loadSession = async function (sessionId) {
|
|
if (isRunning) {
|
|
alert("Analysis in progress, please wait.");
|
|
return;
|
|
}
|
|
|
|
currentSessionId = sessionId;
|
|
|
|
document.querySelectorAll('.history-item').forEach(el => el.classList.remove('active'));
|
|
const activeItem = document.getElementById(`hist-${sessionId}`);
|
|
if (activeItem) activeItem.classList.add('active');
|
|
|
|
reportContainer.innerHTML = "";
|
|
if (downloadScriptBtn) downloadScriptBtn.classList.add('hidden');
|
|
const tplGroup = document.getElementById('templateSelectorGroup');
|
|
if (tplGroup) tplGroup.classList.add('hidden');
|
|
|
|
// Reset execution state for loaded session
|
|
lastRenderedRound = 0;
|
|
const wrapper = document.getElementById('roundCardsWrapper');
|
|
if (wrapper) wrapper.innerHTML = '';
|
|
|
|
try {
|
|
const res = await fetch(`/api/status?session_id=${sessionId}`);
|
|
if (res.ok) {
|
|
const data = await res.json();
|
|
|
|
// Render rounds for historical session
|
|
renderRoundCards(data.rounds || []);
|
|
|
|
// Load data files for historical session
|
|
loadDataFiles();
|
|
|
|
if (data.has_report) {
|
|
await loadReport();
|
|
if (data.script_path && downloadScriptBtn) {
|
|
downloadScriptBtn.classList.remove('hidden');
|
|
downloadScriptBtn.style.display = 'inline-flex';
|
|
}
|
|
switchTab('report');
|
|
} else {
|
|
switchTab('execution');
|
|
}
|
|
}
|
|
} catch (e) {
|
|
console.error("Error loading session", e);
|
|
}
|
|
}
|
|
|
|
// --- Init & Navigation (Task 13) ---
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
loadTemplates();
|
|
loadHistory();
|
|
});
|
|
|
|
window.switchView = function (viewName) {
|
|
console.log("View switch requested:", viewName);
|
|
}
|
|
|
|
window.switchTab = function (tabName) {
|
|
// Deactivate all tabs
|
|
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
|
|
|
|
// Hide all tab content
|
|
['execution', 'datafiles', 'report'].forEach(name => {
|
|
const content = document.getElementById(`${name}Tab`);
|
|
if (content) content.classList.add('hidden');
|
|
});
|
|
|
|
// Activate the clicked tab button
|
|
document.querySelectorAll('.tab').forEach(btn => {
|
|
if (btn.getAttribute('onclick') && btn.getAttribute('onclick').includes(`'${tabName}'`)) {
|
|
btn.classList.add('active');
|
|
}
|
|
});
|
|
|
|
// Show the selected tab content
|
|
if (tabName === 'execution') {
|
|
document.getElementById('executionTab').classList.remove('hidden');
|
|
} else if (tabName === 'datafiles') {
|
|
document.getElementById('datafilesTab').classList.remove('hidden');
|
|
if (currentSessionId) loadDataFiles();
|
|
} else if (tabName === 'report') {
|
|
document.getElementById('reportTab').classList.remove('hidden');
|
|
}
|
|
}
|