/* 工作区控制台 · 前端逻辑(无依赖) */ const KIND = { site: { label: '网站', cls: 'site' }, repo: { label: '仓库', cls: 'repo' }, plugin: { label: '插件', cls: 'plugin' }, mirror: { label: '镜像', cls: 'mirror' }, dir: { label: '目录', cls: 'dir' }, file: { label: '文件', cls: 'dir' }, } const state = { data: null, q: '', kind: 'all', dirty: false, sort: 'size', desc: true, } const $ = (sel) => document.querySelector(sel) const el = (tag, attrs = {}, ...kids) => { const n = document.createElement(tag) for (const [k, v] of Object.entries(attrs)) { if (k === 'class') n.className = v else if (k === 'html') n.innerHTML = v else if (k === 'text') n.textContent = v else if (k.startsWith('on')) n.addEventListener(k.slice(2), v) else n.setAttribute(k, v) } for (const kid of kids.flat()) if (kid != null) n.append(kid.nodeType ? kid : document.createTextNode(kid)) return n } const ago = (iso) => { const diff = Date.now() - new Date(iso).getTime() if (diff < 60e3) return '刚刚' if (diff < 36e5) return `${Math.floor(diff / 60e3)} 分钟前` if (diff < 864e5) return `${Math.floor(diff / 36e5)} 小时前` if (diff < 30 * 864e5) return `${Math.floor(diff / 864e5)} 天前` return new Date(iso).toLocaleDateString('zh-CN') } async function copy(text) { try { await navigator.clipboard.writeText(text) toast(`已复制:${text.length > 34 ? text.slice(0, 34) + '…' : text}`) } catch { toast('复制失败,手动选一下文本吧', true) } } let toastTimer = null function toast(msg, bad = false) { let t = $('#toast') if (!t) { t = el('div', { id: 'toast', class: 'toast' }) document.body.append(t) } t.textContent = msg t.classList.toggle('bad', bad) t.classList.add('show') clearTimeout(toastTimer) toastTimer = setTimeout(() => t.classList.remove('show'), 2200) } function renderStats() { const t = state.data.totals const box = $('#stats') box.replaceChildren( stat(t.projects, '项目'), stat(t.size, '占用'), stat(String(t.files), '文件'), stat(String(t.dirty), '有改动', t.dirty ? 'warn' : '') ) function stat(value, label, tone = '') { return el('div', { class: `stat ${tone}` }, el('b', { text: String(value) }), el('span', { text: label })) } } function renderServices() { const grid = $('#svcGrid') const list = state.data.services || [] const up = list.filter((s) => s.ok).length const known = list.filter((s) => s.ok !== null).length $('#svcHint').textContent = known ? `${up}/${known} 在线 · 扫描时探测` : '点开直接用' grid.replaceChildren( ...list.map((s) => { const dotCls = s.ok === null ? 'idle' : s.ok ? 'ok' : 'bad' const status = s.ok === null ? '未探测' : s.ok ? `${s.ms} ms` : '连不上' return el( 'a', { class: 'svc', href: s.url, target: '_blank', rel: 'noopener' }, el('div', { class: 'svc-top' }, el('span', { class: `dot ${dotCls}` }), el('b', { text: s.name }), el('em', { text: `:${s.port}` }) ), el('p', { text: s.desc }), el('span', { class: `svc-ms ${dotCls}`, text: status }) ) }) ) } function renderChips() { const counts = { all: state.data.entries.length } for (const e of state.data.entries) counts[e.kind] = (counts[e.kind] || 0) + 1 const chips = $('#chips') const make = (key, label) => el('button', { class: `chip ${state.kind === key ? 'on' : ''}`, type: 'button', onclick: () => { state.kind = key renderChips() renderGrid() }, }, label, el('b', { text: String(counts[key] || 0) })) chips.replaceChildren( make('all', '全部'), ...['site', 'repo', 'plugin', 'mirror', 'dir'].filter((k) => counts[k]).map((k) => make(k, KIND[k].label)), el('button', { class: `chip ${state.dirty ? 'on warn' : ''}`, type: 'button', onclick: () => { state.dirty = !state.dirty renderChips() renderGrid() }, }, '有改动', el('b', { text: String(state.data.totals.dirty) })) ) } function filtered() { const q = state.q.trim().toLowerCase() let list = state.data.entries.filter((e) => { if (state.kind !== 'all' && e.kind !== state.kind) return false if (state.dirty && !e.git?.dirty) return false if (!q) return true return [e.name, e.title, e.desc, e.git?.branch, e.git?.repo].join(' ').toLowerCase().includes(q) }) const dir = state.desc ? -1 : 1 list = list.sort((a, b) => { if (state.sort === 'name') return a.name.localeCompare(b.name) * dir if (state.sort === 'time') return (new Date(a.mtime) - new Date(b.mtime)) * dir return (a.bytes - b.bytes) * dir }) return list } function renderGrid() { const list = filtered() const max = Math.max(1, ...state.data.entries.map((e) => e.bytes)) const grid = $('#grid') $('#empty').hidden = list.length > 0 grid.replaceChildren(...list.map((e) => card(e, max))) } function card(e, max) { const kind = KIND[e.kind] || KIND.dir const pct = Math.max(2, Math.round((e.bytes / max) * 100)) const g = e.git const meta = el('div', { class: 'meta' }, el('span', { text: e.size }), el('span', { text: `${e.files} 个文件` }), el('span', { text: ago(e.mtime) }) ) const gitRow = g ? el('div', { class: 'git' }, el('span', { class: 'branch', text: `⎇ ${g.branch}` }), el('span', { class: 'sha', text: g.sha }), el('span', { class: 'subject', text: g.subject, title: g.subject }), g.dirty ? el('span', { class: 'dirty', text: `有改动 ${g.changes}` }) : null ) : el('div', { class: 'git muted' }, el('span', { text: '未纳入 git' })) const acts = el('div', { class: 'acts' }) if (e.url) acts.append(el('a', { class: 'btn primary', href: e.url, target: '_blank', rel: 'noopener', text: `打开 :${e.port}` })) if (g?.webRepo) acts.append(el('a', { class: 'btn', href: g.webRepo, target: '_blank', rel: 'noopener', text: 'Gitea 仓库' })) acts.append(el('button', { class: 'btn ghost', type: 'button', title: '复制本地路径', text: '路径', onclick: () => copy(`${state.data.root}/${e.name}`) })) if (g) acts.append(el('button', { class: 'btn ghost', type: 'button', title: '复制 git 命令', text: 'git', onclick: () => copy(`cd ${state.data.root}/${e.name} && git status`) })) return el('article', { class: 'card' }, el('div', { class: 'card-head' }, el('h3', { text: e.name }), el('span', { class: `kind ${kind.cls}`, text: kind.label }) ), e.title || e.desc ? el('p', { class: 'desc', text: e.title && e.title !== e.name ? e.title : e.desc || '' }) : null, el('div', { class: 'bar' }, el('i', { style: `width:${pct}%` })), meta, gitRow, e.ext?.length ? el('div', { class: 'ext' }, ...e.ext.map((x) => el('span', { text: x }))) : null, acts ) } function bind() { $('#q').addEventListener('input', (ev) => { state.q = ev.target.value renderGrid() }) $('#sort').addEventListener('change', (ev) => { state.sort = ev.target.value renderGrid() }) $('#dirBtn').addEventListener('click', () => { state.desc = !state.desc $('#dirBtn').textContent = state.desc ? '↓' : '↑' renderGrid() }) const openHelp = () => { $('#help').hidden = false document.body.classList.add('locked') } const closeHelp = () => { $('#help').hidden = true document.body.classList.remove('locked') } $('#helpBtn').addEventListener('click', openHelp) $('#helpLink').addEventListener('click', (ev) => { ev.preventDefault() openHelp() }) $('#help').addEventListener('click', (ev) => { if (ev.target.dataset.close !== undefined) closeHelp() }) $('#themeBtn').addEventListener('click', toggleTheme) document.addEventListener('keydown', (ev) => { if (ev.key === '/' && document.activeElement !== $('#q')) { ev.preventDefault() $('#q').focus() } else if (ev.key === 'Escape') { closeHelp() } else if (ev.key === 't' && document.activeElement !== $('#q')) { toggleTheme() } }) } function toggleTheme() { const root = document.documentElement const next = root.dataset.theme === 'light' ? 'dark' : 'light' root.dataset.theme = next try { localStorage.setItem('console.theme', next) } catch {} $('#themeBtn').textContent = next === 'light' ? '☀' : '☾' } async function main() { $('#themeBtn').textContent = document.documentElement.dataset.theme === 'light' ? '☀' : '☾' try { const res = await fetch('manifest.json', { cache: 'no-store' }) if (!res.ok) throw new Error(res.status) state.data = await res.json() } catch (err) { $('#sub').textContent = '读不到 manifest.json —— 先跑一次 publish.sh' $('#grid').replaceChildren(el('p', { class: 'empty', text: `加载失败:${err.message}` })) return } const d = state.data $('#sub').textContent = `${d.totals.projects} 项 · ${d.totals.size} · ${d.totals.files} 个文件` $('#stamp').textContent = `扫描于 ${new Date(d.scannedAt).toLocaleString('zh-CN')} · 根目录 ${d.root}` renderStats() renderServices() renderChips() renderGrid() bind() startStatus() } main() /* ---------- 服务器状态 ---------- */ const SUB = { 0: '正常', 60: '偏高', 80: '吃紧', 90: '告急' } const humanBytes = (n) => { const u = ['B', 'KB', 'MB', 'GB', 'TB'] let i = 0 let v = n while (v >= 1024 && i < u.length - 1) { v /= 1024 i++ } return `${v < 10 ? v.toFixed(1) : Math.round(v)} ${u[i]}` } const humanUptime = (sec) => { const d = Math.floor(sec / 86400) const h = Math.floor((sec % 86400) / 3600) const m = Math.floor((sec % 3600) / 60) if (d) return `${d} 天 ${h} 小时` if (h) return `${h} 小时 ${m} 分` return `${m} 分钟` } function ring(label, pct, sub) { const r = 40 const c = 2 * Math.PI * r const v = Math.max(0, Math.min(100, Number(pct) || 0)) const off = c * (1 - v / 100) const tone = v >= 90 ? 'bad' : v >= 70 ? 'warn' : 'ok' const svgNS = 'http://www.w3.org/2000/svg' const svg = document.createElementNS(svgNS, 'svg') svg.setAttribute('viewBox', '0 0 100 100') svg.setAttribute('class', `ring ${tone}`) for (const [cls, dash] of [['bg', ''], ['fg', '']]) { const circle = document.createElementNS(svgNS, 'circle') circle.setAttribute('cx', '50') circle.setAttribute('cy', '50') circle.setAttribute('r', String(r)) circle.setAttribute('class', cls) if (cls === 'fg') { circle.setAttribute('stroke-dasharray', String(c)) circle.setAttribute('stroke-dashoffset', String(off)) } svg.append(circle) } const t = document.createElementNS(svgNS, 'text') t.setAttribute('x', '50') t.setAttribute('y', '50') t.setAttribute('text-anchor', 'middle') t.setAttribute('dominant-baseline', 'central') t.setAttribute('class', 'ring-val') t.textContent = `${Math.round(v)}%` svg.append(t) const box = el('div', { class: 'ring-box' }, svg, el('b', { text: label }), el('span', { text: sub || '' })) return box } function renderStatus(st) { const rings = $('#rings') const memSub = `${humanBytes(st.mem.used)} / ${humanBytes(st.mem.total)}` const diskSub = `${humanBytes(st.disk.used)} / ${humanBytes(st.disk.total)}` const loadPct = Math.min(100, Math.round((st.load[0] / (st.cores || 1)) * 100)) rings.replaceChildren( ring('CPU', st.cpu.pct, `${st.cores} 核`), ring('内存', st.mem.pct, memSub), ring('磁盘', st.disk.pct, diskSub), ring('负载', loadPct, st.load.join(' / ')) ) $('#statusMeta').replaceChildren( metaRow('主机', st.host), metaRow('系统', st.os), metaRow('内核', st.kernel), metaRow('已运行', humanUptime(st.uptimeSec)), metaRow('Swap', st.swap.total ? `${humanBytes(st.swap.used)} / ${humanBytes(st.swap.total)}` : '未启用'), metaRow('Gitea', st.gitea || '—') ) const svg = $('#sparkSvg') const MAX = 90 const hist = (st.history || []).slice(-MAX) const w = 100 const h = 34 const xAt = (i, n) => w - ((n - 1 - i) / (MAX - 1)) * w const path = (key) => { if (hist.length < 2) return '' return hist .map((p, i) => { const x = xAt(i, hist.length) const y = h - (Math.max(0, Math.min(100, p[key])) / 100) * (h - 3) - 1 return `${i ? 'L' : 'M'}${x.toFixed(2)},${y.toFixed(2)}` }) .join(' ') } const area = (key) => { if (hist.length < 2) return '' const x0 = xAt(0, hist.length) return `${path(key)} L100,${h - 1} L${x0.toFixed(2)},${h - 1} Z` } svg.innerHTML = ` ` const dots = st.services.filter((s) => s.active === true).length $('#svcDots').replaceChildren( el('span', { class: 'svc-dots-label', text: `服务 ${dots}/${st.services.length} 在跑` }), ...st.services.map((s) => el('span', { class: `svc-pill ${s.active ? 'on' : 'off'}`, title: `${s.name} ${s.active ? '运行中' : '未运行'}` }, el('i', { class: `dot ${s.active ? 'ok' : 'bad'}` }), s.name) ) ) $('#topProcs').replaceChildren( el('span', { class: 'svc-dots-label', text: '吃内存前三' }), ...(st.top || []).map((p) => el('span', { class: 'proc', text: `${p.name} · ${humanBytes(p.mem)}` })) ) const when = new Date(st.ts) const age = Math.round((Date.now() - when.getTime()) / 1000) $('#statusStamp').textContent = `${when.toLocaleTimeString('zh-CN')} 采集 · ${age < 60 ? `${age} 秒前` : `${Math.round(age / 60)} 分钟前`}` } function metaRow(k, v) { return el('div', { class: 'meta-row' }, el('span', { text: k }), el('b', { text: v })) } let statusTimer = null async function loadStatus() { try { const res = await fetch(`status/status.json?t=${Date.now()}`, { cache: 'no-store' }) if (!res.ok) throw new Error(res.status) renderStatus(await res.json()) } catch (err) { $('#statusStamp').textContent = '还没装状态采集器' const grid = document.querySelector('.status-grid') if (!grid.querySelector('.panel-empty')) { grid.replaceChildren( el('div', { class: 'panel-empty' }, el('h3', { text: '服务器上还没跑状态采集器' }), el('p', { text: '控制台页面是静态的,服务器状态由一个小采集器每 20 秒写进 status.json。在服务器上装一次就好:' }), el('pre', {}, el('code', { text: 'cd /opt/sites/console && cp status/console-status.service /etc/systemd/system/\nsystemctl daemon-reload && systemctl enable --now console-status' })), el('p', { class: 'muted', text: '装好后这个区块会自动出现 CPU / 内存 / 磁盘 / 负载和历史曲线。' }) ) ) } } } function startStatus() { loadStatus() $('#statusRefresh').addEventListener('click', loadStatus) clearInterval(statusTimer) statusTimer = setInterval(loadStatus, 30_000) }