/**
* LLM 论文图书馆 — 前端 JS
* 打开时 ping 所有论文源 → 底部状态条 → 点击论文直用缓存结果
*/
const API = '/api';
let modules = {};
let moduleData = {};
let currentPdf = null;
let pdfTimeout = null;
let networkStatus = {}; // { arxiv: bool, huggingface: bool, hk: bool }
const $ = (sel) => document.querySelector(sel);
const $$ = (sel) => document.querySelectorAll(sel);
const TAG_CLASS = { '起点':'tag-start','关键节点':'tag-milestone','前沿':'tag-frontier','前瞻':'tag-forward','支线':'tag-branch' };
// ═══════════════ INIT ═══════════════════════════════════
async function init() {
// Build network status bar
buildStatusBar();
// Load modules
try {
const resp = await fetch(`${API}/modules`);
const mods = await resp.json();
modules = {};
for (const m of mods) modules[m.id] = m;
renderCards(mods);
attachGlowTracking();
} catch (e) { console.error(e); }
// Ping sources
checkSources();
document.addEventListener('keydown', e => {
if (e.key === 'Escape') {
if ($('#pdfOverlay')?.classList.contains('open')) closePdf();
else if ($('#overlay').classList.contains('open')) closeModal();
}
});
}
// ═══════════════ STATUS BAR ════════════════════════════
function buildStatusBar() {
const bar = document.createElement('div');
bar.id = 'statusBar';
bar.className = 'status-bar';
bar.innerHTML = `
连通性检测 arXiv — HuggingFace —spdis.space由 DeepSeek-V4-Pro 每周维护
`;
document.body.appendChild(bar);
}
function setStatus(id, ok, ms, aborted) {
networkStatus[id.replace('status-','')] = ok;
const el = document.getElementById(id);
if (!el) return;
const dot = el.querySelector('.status-dot');
dot.className = 'status-dot ' + (ok ? 'status-ok' : 'status-fail');
const msEl = document.getElementById('ms-' + id.replace('status-',''));
if (msEl) {
if (aborted) msEl.textContent = '超时 (4s)';
else if (ok) msEl.textContent = ms + 'ms';
else msEl.textContent = '—';
}
}
async function checkSource(name, url, statusId) {
const start = performance.now();
let aborted = false;
// Add cache-buster and force no-store to avoid browser caching
const probeUrl = url + '?_=' + Date.now();
try {
const ctrl = new AbortController();
setTimeout(() => { aborted = true; ctrl.abort(); }, 4000);
await fetch(probeUrl, { mode: 'no-cors', signal: ctrl.signal, cache: 'no-store' });
const ms = Math.round(performance.now() - start);
setStatus(statusId, true, ms, false);
} catch {
const ms = Math.round(performance.now() - start);
setStatus(statusId, false, ms, aborted);
}
}
async function checkSources() {
checkSource('arxiv', 'https://arxiv.org/favicon.ico', 'status-arxiv');
checkSource('hf', 'https://huggingface.co/favicon.ico', 'status-hf');
}
// ═══════════════ GLOW ══════════════════════════════════
function attachGlowTracking() {
$$('.card').forEach(card => {
card.addEventListener('mousemove', e => {
const rect = card.getBoundingClientRect();
card.style.setProperty('--mx', ((e.clientX - rect.left) / rect.width * 100) + '%');
card.style.setProperty('--my', ((e.clientY - rect.top) / rect.height * 100) + '%');
});
});
}
// ═══════════════ CARDS -> MODAL -> PAPERS ═══════════════
function renderCards(mods) {
$('#moduleGrid').innerHTML = mods.map(m => `
${m.icon} ${m.name}
${m.desc}
${m.area_count} 子领域 · ${m.paper_count} 篇
`).join('');
}
async function openModule(modId) {
let data = moduleData[modId];
if (!data) {
try { data = await (await fetch(`${API}/modules/${modId}`)).json(); moduleData[modId] = data; }
catch (e) { return; }
}
const mod = modules[modId];
$('#modalTitle').innerHTML = `${mod?.icon||''} ${data.name}`;
$('#modalSubtitle').textContent = data.desc || '';
const areas = data.areas || [];
$('#modalTabs').innerHTML = areas.map((a,i) =>
``).join('');
if (areas.length > 0) { $('#modalTabs').dataset.areaIdx = '0'; renderPapers(areas[0]); }
$('#overlay').classList.add('open');
}
function switchArea(idx) {
const data = Object.values(moduleData).find(d => d.areas && d.areas[idx]);
if (!data) return;
$$('#modalTabs .tab').forEach((t,i) => t.classList.toggle('active', i===idx));
renderPapers(data.areas[idx]);
}
function closeModal() { $('#overlay').classList.remove('open'); }
function renderPapers(area) {
let h = '';
function s(l, ps, c) { return ps.length ? `
${l}
`+ps.map(renderPaper).join('') : ''; }
h += s('📌 主线论文', area.mainline||[], 'mainline');
h += s('🌿 支线论文', area.branches||[], 'branch');
h += s('🔮 前瞻探索', area.forward||[], 'forward');
$('#modalContent').innerHTML = h || '
暂无论文数据
';
}
function renderPaper(p) {
const pdfUrl = getPdfLink(p);
const id = 'p'+Math.random().toString(36).slice(2,8);
const tags = (p.tags||[]).map(t => `${t}`).join(' ');
const links = [];
if (pdfUrl) links.push(``);
else if (p.arxiv) links.push(`📋 arXiv`);
// Show translation button for ALL papers with arxiv or pdf
const paperId = p.arxiv || (p.pdf ? p.pdf.split('/').pop().replace('.pdf','') : null);
if (paperId) {
links.push('');
}
return `
${p.year||'—'}
${p.title}
${p.authors||''}${p.venue?`${p.venue}`:''}${tags}
${links.join('')}
`;
}
function getPdfLink(p) {
if (p.pdf) return p.pdf;
if (p.arxiv) return `https://arxiv.org/pdf/${p.arxiv}.pdf`;
return null;
}
function openPdfBtn(btn) { openPdf(btn.dataset.pdf, btn.dataset.title); }
function openTrans(btn) {
const url = btn.dataset.pdf;
const title = btn.dataset.title;
openPdf(url, title);
// If translation doesn't exist, the iframe will show error - user can see it
}
// ═══════════════ PDF VIEWER (状态条驱动) ═══════════════
function getLocalPdfUrl(extUrl) {
const am = extUrl.match(/arxiv\.org\/pdf\/(\d+\.\d+)/);
if (am) return `/papers/arxiv/${am[1]}.pdf`;
if (extUrl.includes('huggingface.co')) return `/papers/hf/${extUrl.split('/').pop().replace('.pdf','')}.pdf`;
return null;
}
async function openPdf(url, title) {
const decodedUrl = decodeURIComponent(url);
const decodedTitle = decodeURIComponent(title);
currentPdf = decodedUrl;
const hkFallback = getLocalPdfUrl(decodedUrl);
if (!$('#pdfOverlay')) {
const div = document.createElement('div'); div.id='pdfOverlay'; div.className='pdf-overlay';
div.innerHTML = `