// GitLab Webhook Dashboard - 前端逻辑 // 数据源: // GET /api/queue -> { pending: [], current: { task, startedAt, log } | null } // GET /api/history -> { scripts: [], history: { scriptPath: [record, ...] } } const POLL_QUEUE_MS = 1500; // 队列 + 当前执行 轮询周期 const POLL_HISTORY_MS = 4000; // 历史 轮询周期 const LOG_TAIL_CHARS = 12000; // 前端日志渲染尾部最大字符数 const state = { pending: [], current: null, history: {}, // { scriptPath: [record, ...] } scripts: [], // 配置中的全部脚本 autoscroll: true, expandedLogs: new Set(), // 已展开的历史日志 record ID(re-render 后恢复) lastLiveKey: null, // 上次渲染的"当前任务身份"(用于判断是否需要重建 DOM) }; // ============ Helpers ============ const $ = (sel) => document.querySelector(sel); const fmtTime = (iso) => { if (!iso) return "-"; const d = new Date(iso); if (isNaN(d.getTime())) return iso; const pad = (n) => String(n).padStart(2, "0"); return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; }; const fmtFullTime = (iso) => { if (!iso) return "-"; const d = new Date(iso); if (isNaN(d.getTime())) return iso; const pad = (n) => String(n).padStart(2, "0"); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ` + `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; }; const shortCommit = (s) => { if (!s) return "unknown"; return s.length > 7 ? s.slice(0, 7) : s; }; const escapeHtml = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'", }[c])); // ============ Connection status ============ function setConn(ok, text) { const dot = $("#conn-dot"); const txt = $("#conn-text"); dot.classList.remove("dot-green", "dot-red", "dot-grey"); dot.classList.add(ok ? "dot-green" : "dot-red"); txt.textContent = text; } // ============ Fetchers ============ async function fetchJSON(url) { const r = await fetch(url, { cache: "no-store" }); if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); } async function pollQueue() { try { const data = await fetchJSON("/api/queue"); state.pending = data.pending || []; state.current = data.current || null; setConn(true, "已连接"); renderQueue(); renderRunning(); } catch (e) { setConn(false, "连接失败"); console.warn("queue poll failed:", e); } } async function pollHistory() { try { const data = await fetchJSON("/api/history"); state.scripts = data.scripts || []; state.history = data.history || {}; renderHistory(); } catch (e) { console.warn("history poll failed:", e); } } // ============ Renderers ============ function renderQueue() { const list = $("#pending-list"); const badge = $("#pending-count"); badge.textContent = String(state.pending.length); if (state.pending.length === 0) { list.innerHTML = `
暂无等待任务
`; return; } list.innerHTML = state.pending.map((p) => `当前没有任务在执行
`; sizeEl.textContent = ""; state.lastLiveKey = null; return; } const c = state.current; stateBadge.textContent = "执行中"; stateBadge.className = "badge badge-warn"; const liveKey = `${c.task.script}|${c.task.repo}|${c.task.ref}|${c.startedAt}`; // 仅渲染尾部以避免长日志卡顿 const fullLog = c.log || ""; const tail = fullLog.length > LOG_TAIL_CHARS ? fullLog.slice(fullLog.length - LOG_TAIL_CHARS) : fullLog; if (state.lastLiveKey !== liveKey) { // 任务身份变化:重建结构并贴底 body.innerHTML = ` `; state.lastLiveKey = liveKey; const logBox = $("#live-log"); logBox.textContent = tail || "(等待脚本输出…)"; sizeEl.textContent = fullLog.length ? `${(fullLog.length / 1024).toFixed(1)} KB` : ""; requestAnimationFrame(() => { logBox.scrollTop = logBox.scrollHeight; }); return; } // 同一任务:仅更新日志内容,保持 DOM 节点稳定 const logBox = $("#live-log"); const distanceFromBottom = logBox.scrollHeight - logBox.scrollTop - logBox.clientHeight; const atBottom = distanceFromBottom <= 24; logBox.textContent = tail || "(等待脚本输出…)"; sizeEl.textContent = fullLog.length ? `${(fullLog.length / 1024).toFixed(1)} KB` : ""; if (state.autoscroll && atBottom) { requestAnimationFrame(() => { logBox.scrollTop = logBox.scrollHeight; }); } } function statusPill(status) { const map = { success: ["status-success", "成功"], failed: ["status-failed", "失败"], timeout: ["status-timeout", "超时"], skipped: ["status-skipped", "跳过"], running: ["status-running", "运行中"], }; const [cls, text] = map[status] || ["status-skipped", status || "-"]; return `${text}`; } function renderHistory() { const root = $("#history-list"); if (!state.scripts.length) { root.innerHTML = `配置文件中未声明任何脚本
`; return; } // 当前正在执行的任务 ID(用于高亮) const liveKey = state.current ? `${state.current.task.script}|${state.current.task.repo}|${state.current.task.ref}` : null; root.innerHTML = state.scripts.map((script) => { const records = state.history[script] || []; const rows = records.length ? records.slice().reverse().map((r) => { const liveMarker = (liveKey && liveKey === `${r.script}|${r.repo}|${r.ref}` && r.status === "running") ? "row-running" : ""; const logId = `log-${r.id}`; return `${escapeHtml(script)}(${records.length})| 开始时间 | Commit | 仓库/分支 | 状态 | 耗时 | 原因 | 日志 |
|---|