'use strict'; /* ---------------- 基础 ---------------- */ const $ = (s, r = document) => r.querySelector(s); const $$ = (s, r = document) => [...r.querySelectorAll(s)]; let serverBuild = null; const state = { view: 'apps', filter: 'all', sort: 'severity', order: 'desc', q: '', timer: null, current: null, currentApp: null, tab: 'stat', appTab: 'containers', insightOpen: false, traffic: { range: 'today', date: '' }, sel: new Set() }; const REFRESH_KEY = 'dc.refreshMs'; state.refreshMs = Math.min(30000, Math.max(1000, Number(localStorage.getItem(REFRESH_KEY)) || 3000)); const ICONS = { grid: '', box: '', pause: '', disc: '', repo: '', globe: '', bell: '', search: '', refresh: '', plus: '', power: '', restart: '', link: '', more: '', trash: '', back: '', }; const icon = (n) => `${ICONS[n] || ''}`; function paintIcons(root = document) { $$('i[data-ico]', root).forEach(el => { el.outerHTML = icon(el.dataset.ico); }); } const fmtBytes = (b) => { if (b === undefined || b === null) return '-'; const u = ['B', 'KB', 'MB', 'GB', 'TB']; let i = 0, n = Math.abs(b); while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; } return `${n < 10 && i > 0 ? n.toFixed(2) : Math.round(n * 10) / 10} ${u[i]}`; }; const fmtRateShort = (b) => { if (!b) return '0'; const u = ['B/s', 'K/s', 'M/s', 'G/s']; let i = 0, v = b; while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; } const s = v >= 100 ? String(Math.round(v)) : (Math.round(v * 10) / 10).toString(); return s.replace(/\.0$/, '') + u[i]; }; const fmtRate = (b) => (b > 0 ? fmtBytes(b) + '/s' : '0 B/s'); const fmtPct = (n) => (n >= 10 ? n.toFixed(1) : (n || 0).toFixed(2)) + '%'; const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const fmtDur = (ms) => { if (ms === null || ms === undefined || !isFinite(ms) || ms < 0) return '—'; const s = Math.floor(ms / 1000); const d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60); if (d > 0) return `${d} 天${h ? ' ' + h + ' 小时' : ''}`; if (h > 0) return `${h} 小时${m ? ' ' + m + ' 分' : ''}`; if (m > 0) return `${m} 分钟`; return '不到 1 分钟'; }; const shortImg = (img) => { const s = String(img || ''); if (/^sha256:/.test(s)) return s.slice(7, 19); const last = s.split('/').pop(); return last.length > 22 ? last.slice(0, 22) + '…' : last; }; const fmtDurCompact = (ms) => { if (ms === null || ms === undefined || !isFinite(ms) || ms < 0) return '—'; const s = Math.floor(ms / 1000), d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60); if (d > 0) return `${d}天${h ? h + '小时' : ''}`; if (h > 0) return `${h}小时${m ? m + '分' : ''}`; if (m > 0) return `${m}分钟`; return '1分钟内'; }; const ago = (iso) => { if (!iso) return '-'; const d = (Date.now() - new Date(iso).getTime()) / 1000; if (!isFinite(d) || d < 0) return '-'; if (d < 60) return `${Math.round(d)} 秒`; if (d < 3600) return `${Math.round(d / 60)} 分钟`; if (d < 86400) return `${(d / 3600).toFixed(1)} 小时`; return `${Math.floor(d / 86400)} 天`; }; const timeStr = (t) => new Date(t).toLocaleString('zh-CN', { hour12: false, month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }); async function api(url, opts) { const r = await fetch(url, opts); const j = await r.json().catch(() => ({})); if (!r.ok) throw new Error(j.error || r.statusText); return j; } function toast(msg, err) { const t = $('#toast'); t.textContent = msg; t.className = 'toast' + (err ? ' err' : ''); clearTimeout(t._h); t._h = setTimeout(() => t.classList.add('hidden'), 2600); } /* ---------------- 路由 ---------------- */ const TITLES = { apps: '概览', 'apps-all': '全部应用', containers: '运行的容器', stopped: '停止的容器', images: '本地镜像', registry: '镜像仓库', networks: '网络', settings: '告警设置' }; const SORTS = { apps: [['severity', '异常优先'], ['cpu', 'CPU 占用'], ['mem', '内存占用'], ['containers', '容器数'], ['name', '名称']], containers: [['cpu', 'CPU 占用'], ['mem', '内存占用'], ['net', '网络速率'], ['io', '磁盘 IO'], ['pids', '进程数'], ['name', '名称']], stopped: [['name', '名称'], ['mem', '内存占用']], }; function go(view) { if (state.view !== view && state.sel) state.sel.clear(); state.view = view; state.currentApp = null; const navView = view === 'apps-all' ? 'apps' : view; $$('#nav a').forEach(a => a.classList.toggle('active', a.dataset.view === navView)); $('#pageTitle').textContent = TITLES[view] || view; const isList = ['apps', 'apps-all', 'containers', 'stopped'].includes(view); $('#search').style.display = isList || view === 'images' ? '' : 'none'; $('#sortbox').style.display = isList ? '' : 'none'; const opts = SORTS[view] || SORTS[navView] || SORTS.containers; if (state.sort && !opts.some(o => o[0] === state.sort)) state.sort = opts[0][0]; $('#sort').innerHTML = opts.map(([v, t]) => ``).join(''); $('#sort').value = state.sort; $('#addBtn').textContent = view === 'registry' ? '拉取镜像' : view === 'images' ? '清理悬空镜像' : '添加容器'; clearInterval(state.timer); if ($('#refreshSel')) $('#refreshSel').value = String(state.refreshMs); render(); state.timer = setInterval(() => { if (!document.hidden && (state.view === view || state.view === 'app-detail')) render(true); }, state.refreshMs); } async function render(silent) { try { if (state.view === 'app-detail') { if (state.appTab === 'containers' && state.currentApp) return openApp(state.currentApp); return; } if (state.view === 'apps' || state.view === 'apps-all') return renderApps(silent); if (state.view === 'containers') return renderContainers(silent, 'running'); if (state.view === 'stopped') return renderContainers(silent, 'stopped'); if (state.view === 'images') return renderImages(); if (state.view === 'registry') return renderRegistry(); if (state.view === 'networks') return renderNetworks(); if (state.view === 'settings') return renderSettings(); } catch (e) { if (!silent) $('#view').innerHTML = `
加载失败:${esc(e.message)}
`; } } /* ---------------- 主机信息 ---------------- */ async function refreshHost() { const h = await api('/api/host'); if (h.build) { if (serverBuild && serverBuild !== h.build) { location.reload(); return h; } serverBuild = h.build; } const navCl = $('#navContainersLabel'); if (navCl && navCl.textContent !== '运行的容器') navCl.textContent = '运行的容器'; const stamp = $('#buildStamp'); if (stamp && h.build) { const d = new Date(Number(h.build)); const txt = `构建 ${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; if (stamp.textContent !== txt) stamp.textContent = txt; } $('#hostMini').innerHTML = `${esc(h.hostname)}
${h.cpus} 核 · 内存 ${fmtBytes(h.memTotal)}
运行 ${h.running} / 共 ${h.containers} 容器`; $('#navRunning').textContent = h.running; $('#navStopped').textContent = (h.stopped || 0) + (h.pending || 0); $('#navStopped').title = `已停止容器 ${h.stopped || 0} 个 · 有镜像未启动的应用 ${h.pending || 0} 个`; return h; } /* ---------------- 应用看板 ---------------- */ const AVATAR_COLORS = ['#1a73e8', '#7a5af8', '#12b76a', '#f79009', '#e5484d', '#0ba5ec', '#9e77ed', '#099250']; function avatar(name) { const s = String(name || '?'); const code = [...s].reduce((a, c) => a + c.codePointAt(0), 0); const color = AVATAR_COLORS[code % AVATAR_COLORS.length]; const label = /^[a-zA-Z]/.test(s) ? s.slice(0, 2).toUpperCase() : [...s].slice(0, 1).join(''); return `${esc(label)}`; } /* ---------------- 趋势图表 ---------------- */ const CHART_META = new Map(); let chartSeq = 0; function lineChart(points, series, unit, opts) { opts = opts || {}; const W = 360, H = 118, PL = 4, PR = 4, PT = 12, PB = 17; const iw = W - PL - PR, ih = H - PT - PB; const n = Math.max(points.length, 2); const vals = points.flatMap(p => series.map(sr => p[sr.key] || 0)); const max = opts.max || Math.max(...vals, 1) || 1; const xAt = (i) => PL + (iw * i) / (n - 1); const yAt = (v) => PT + ih - (Math.min(v, max) / max) * ih; const gap = unit === 'hour' ? 4 : unit === 'day' ? 5 : 3; const ticks = points.map((p, i) => ({ i, l: p.label })).filter(({ i }) => i % gap === 0); const gridY = [0, 0.5, 1].map(f => PT + ih * f); const fmtMax = opts.fmt || ((v) => String(Math.round(v))); const cid = 'cv' + (++chartSeq); CHART_META.set(cid, { points, series, unit }); return ` ${series.map((sr, si) => ` `).join('')} ${gridY.map(y => ``).join('')} ${series.map((sr, si) => { const pts = points.map((p, i) => `${xAt(i).toFixed(1)},${yAt(p[sr.key] || 0).toFixed(1)}`).join(' '); const area = sr.area ? `` : ''; return `${area}`; }).join('')} ${ticks.map(({ i, l }) => `${esc(l)}`).join('')} 峰值 ${fmtMax(max)} `; } function bindChartTips() { let tip = document.getElementById('chartTip'); if (!tip) { tip = document.createElement('div'); tip.id = 'chartTip'; tip.className = 'chart-tip'; document.body.appendChild(tip); } const hide = () => { tip.style.display = 'none'; document.querySelectorAll('.ch-guide').forEach(g => g.setAttribute('opacity', '0')); }; $$('#view .tf-chart').forEach(svg => { const meta = CHART_META.get(svg.dataset.cid); if (!meta) return; svg.addEventListener('mousemove', (e) => { const r = svg.getBoundingClientRect(); const n = meta.points.length; if (!n) return; const ratio = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)); const idx = Math.round(ratio * (n - 1)); const pt = meta.points[idx]; if (!pt) return; const vbW = 360, PL = 4, PR = 4, PT = 12, PB = 17; const xv = PL + ((vbW - PL - PR) * idx) / Math.max(1, n - 1); const guide = svg.querySelector('.ch-guide'); if (guide) { guide.setAttribute('x1', xv); guide.setAttribute('x2', xv); guide.setAttribute('opacity', '1'); } tip.innerHTML = `
${esc(pt.label)}
${meta.series.map(sr => `
${esc(sr.name || sr.key)}${sr.fmt ? sr.fmt(pt[sr.key] || 0) : fmtBytes(pt[sr.key] || 0)}
`).join('')}`; tip.style.display = 'block'; const tw = tip.offsetWidth, th = tip.offsetHeight; let left = e.clientX + 12, top = e.clientY - th - 10; if (left + tw > window.innerWidth - 8) left = e.clientX - tw - 12; if (top < 8) top = e.clientY + 14; tip.style.left = left + 'px'; tip.style.top = top + 'px'; }); svg.addEventListener('mouseleave', hide); }); } async function renderApps(silent) { const q = state.q ? `&q=${encodeURIComponent(state.q)}` : ''; const [data, h, ev, ins, full, tf] = await Promise.all([ api(`/api/apps?filter=${state.filter}&sort=${state.sort}&order=${state.order}${q}`), refreshHost(), api('/api/events?limit=8'), api('/api/insights').catch(() => null), api('/api/apps?sort=cpu&order=desc').catch(() => null), (state.view === 'apps' ? api(`/api/traffic?range=${state.traffic.range}${state.traffic.date && state.traffic.range === 'day' ? `&date=${state.traffic.date}` : ''}`).catch(() => null) : Promise.resolve(null)), ]); const s = data.summary; const disk = h.disk; const pill = (a) => `${a.statusText}`; const chips = [['all', '全部', s.total], ['issues', '有问题', s.critical + s.warning], ['stopped', '已停止', s.stopped], ['high', '高占用', '']]; const cardOf = (a) => `
${avatar(a.name)}
${esc(a.name)}
${a.type === 'compose' ? `Compose · ${a.total} 个容器` : '单容器'} · ${a.running}/${a.total} 运行
${pill(a)}
CPU
${fmtPct(a.cpuPctOfMachine)}
内存
${fmtBytes(a.mem)}
网络
↑${fmtRate(a.txBps)}
↓${fmtRate(a.rxBps)}
${a.issues.length ? `
${a.issues.slice(0, 2).map(i => `
${esc(i.text)}
`).join('')}${a.issues.length > 2 ? `
还有 ${a.issues.length - 2} 条
` : ''}
` : ''}
${a.ports.slice(0, 3).map(p => `:${p.public}`).join('') || '无对外端口'}
${a.runMs === null ? '未运行' : a.runMs < 60000 ? '刚刚启动' : `已运行 ${fmtDur(a.runMs)}`} · ${a.uptime !== null ? `可用率 ${a.uptime}%` : '采样中'}${a.restarts ? ` · 重启 ${a.restarts}` : ''}
`; const cards = data.items.map(cardOf).join(''); const allApps = (full && full.items) || data.items || []; const topCpu = [...allApps].sort((x, y) => (y.cpuPctOfMachine || 0) - (x.cpuPctOfMachine || 0)).slice(0, 5); const topMem = [...allApps].sort((x, y) => (y.mem || 0) - (x.mem || 0)).slice(0, 5); const netOf = (a) => (a.rxBps || 0) + (a.txBps || 0); const topNet = [...allApps].sort((x, y) => netOf(y) - netOf(x)).slice(0, 5); const topRun = [...allApps].filter(a => a.runMs !== null && a.runMs !== undefined).sort((x, y) => y.runMs - x.runMs).slice(0, 5); const memTotal = h.memTotal || 1; const topRow = (a, i, val, pct, kind) => `
${i + 1}
${esc(a.name)} ${val}
`; const maxCpu = Math.max(1, ...topCpu.map(a => a.cpuPctOfMachine || 0)); const maxMem = Math.max(1, ...topMem.map(a => a.mem || 0)); const maxNet = Math.max(1, ...topNet.map(netOf)); const maxRun = Math.max(1, ...topRun.map(a => a.runMs)); const topHtml = `
CPU 占用 Top 5占整机 · ${h.cpus} 核
${topCpu.map((a, i) => topRow(a, i, fmtPct(a.cpuPctOfMachine || 0), ((a.cpuPctOfMachine || 0) / maxCpu) * 100, 'cpu')).join('') || '
暂无数据
'}
内存占用 Top 5占整机 ${fmtBytes(memTotal)}
${topMem.map((a, i) => topRow(a, i, `${fmtBytes(a.mem || 0)} ${((a.mem || 0) / memTotal * 100).toFixed(1)}%`, ((a.mem || 0) / maxMem) * 100, 'mem')).join('') || '
暂无数据
'}
网络占用 Top 5上下行合计
${topNet.map((a, i) => topRow(a, i, `↓${fmtRateShort(a.rxBps || 0)} ↑${fmtRateShort(a.txBps || 0)}`, (netOf(a) / maxNet) * 100, 'net')).join('') || '
暂无数据
'}
运行时长 Top 5连续运行
${topRun.map((a, i) => topRow(a, i, `${fmtDurCompact(a.runMs)} ${a.running}/${a.total}`, (a.runMs / maxRun) * 100, 'run')).join('') || '
暂无数据
'}
进度条长度按各榜第一名的值等比缩放,不是占整机比例
`; const insItems = (ins && ins.items) || []; const shownIns = state.insightOpen ? insItems : insItems.slice(0, 4); const insHtml = insItems.length ? `
优化建议根据当前运行状态自动分析
${ins.counts.high ? `高 ${ins.counts.high}` : ''} ${ins.counts.mid ? `中 ${ins.counts.mid}` : ''} ${ins.counts.low ? `低 ${ins.counts.low}` : ''}
${shownIns.map(i => `
${esc(i.title)}${esc(i.appName || '系统')}
${esc(i.detail)}
${i.action ? `` : (i.appKey ? `` : '')}
`).join('')}
${insItems.length > 4 ? `` : ''}
` : `
优化建议当前没有需要优化的项,配置状态良好
`; const isAll = state.view === 'apps-all'; const attn = allApps.filter(a => a.severity > 0).slice(0, 6); const totalApps = s.total; if (isAll) { $('#view').innerHTML = `
全部应用共 ${totalApps} 个 · 点击卡片查看详情
${chips.map(([k, t2, n]) => ``).join('')} 按状态异常优先、其次资源占用排序
${cards || '
没有匹配的应用
'}
`; $('#backOverview').onclick = () => go('apps'); } else { CHART_META.clear(); chartSeq = 0; const tfPts = (tf && tf.points) || []; const tfTotal = (tf && tf.total) || { rx: 0, tx: 0 }; const tfNow = (tf && tf.now) || { rx: 0, tx: 0, cpu: 0, mem: 0 }; const tfPeak = (tf && tf.peak) || { mem: 0, cpu: 0 }; const tfAvg = (tf && tf.avg) || { cpu: 0, mem: 0 }; const tfTabs = [['today', '今天'], ['yesterday', '昨天'], ['month', '近 30 天'], ['year', '近 12 个月']]; const noData = '
暂无数据
'; const tfHtml = `
性能趋势 3 秒采样 · 按小时汇总${tf && tf.coverage && tf.coverage.from ? ` · 自 ${esc(tf.coverage.from)} 起` : ''}
${tfTabs.map(([k, l]) => ``).join('')}
流量↓ ${fmtRate(tfNow.rx)} · ↑ ${fmtRate(tfNow.tx)}
${tfPts.length ? lineChart(tfPts, [{ key: 'rx', name: '下行', color: '#1a73e8', area: true, fmt: fmtBytes }, { key: 'tx', name: '上行', color: '#f79009', dash: true, fmt: fmtBytes }], tf.unit, { fmt: fmtBytes }) : noData}
总 ${fmtBytes(tfTotal.rx + tfTotal.tx)} · 下 ${fmtBytes(tfTotal.rx)} · 上 ${fmtBytes(tfTotal.tx)}
CPU${fmtPct(tfNow.cpu)}
${tfPts.length ? lineChart(tfPts, [{ key: 'cpu', name: 'CPU', color: '#12b76a', area: true, fmt: (v) => v.toFixed(2) + '%' }], tf.unit, { max: Math.min(100, Math.max(2, (tfPeak.cpu || 0) * 1.25)), fmt: (v) => v.toFixed(1) + '%' }) : noData}
均值 ${(tfAvg.cpu || 0).toFixed(1)}% · 峰值 ${(tfPeak.cpu || 0).toFixed(1)}% · ${tf && tf.cores ? tf.cores + ' 核' : ''}
内存${fmtBytes(tfNow.mem)}
${tfPts.length ? lineChart(tfPts, [{ key: 'mem', name: '内存', color: '#7a5af8', area: true, fmt: fmtBytes }], tf.unit, { fmt: fmtBytes }) : noData}
均值 ${fmtBytes(tfAvg.mem || 0)} · 峰值 ${fmtBytes(tfPeak.mem || 0)}
`; $('#view').innerHTML = `
应用总数
${s.total}
${s.containers} 个容器
异常
${s.critical}
需要立即处理
注意
${s.warning}
建议关注
资源占用
${fmtBytes(s.mem)}
CPU ${fmtPct(s.cpu / h.cpus)} · 磁盘可用 ${disk ? fmtBytes(disk.free) : '-'}
运行容器
${h.running}/${h.containers}
镜像 ${h.images} 个
${tfHtml} ${topHtml} ${insHtml}
需要关注的应用${attn.length ? `${attn.length} 个异常或需要注意` : '全部正常'}
${attn.length ? `
${attn.map(cardOf).join('')}
` : '
所有应用运行正常,无需处理
'}

最近事件

状态变化与重启记录
${ev.items.length ? ev.items.map(e => `
${timeStr(e.t)}
${esc(e.title)}
${esc(e.detail || '')}
`).join('') : '
暂无事件
'}
`; $('#openAllApps').onclick = () => go('apps-all'); } $$('#view .chip').forEach(b => b.onclick = () => { state.filter = b.dataset.filter; render(); }); $$('#view .tf-tab').forEach(b => b.onclick = () => { state.traffic.range = b.dataset.tr; state.traffic.date = ''; render(); }); const tfDate = $('#tfDate'); if (tfDate) tfDate.onchange = () => { if (!tfDate.value) return; state.traffic.range = 'day'; state.traffic.date = tfDate.value; render(); }; bindChartTips(); $$('#view .top-row').forEach(r => r.onclick = () => openApp(r.dataset.top)); const moreBtn = $('#insightMore'); if (moreBtn) moreBtn.onclick = () => { state.insightOpen = !state.insightOpen; render(); }; $$('#view [data-insight]').forEach(b => b.onclick = async (e) => { e.stopPropagation(); const type = b.dataset.insight, key = b.dataset.key; if (type === 'openApp') return openApp(key); b.disabled = true; try { if (type === 'startApp') { const r = await api(`/api/apps/${encodeURIComponent(key)}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'start' }) }); toast(`启动完成(${r.results.filter(x => x.ok).length}/${r.results.length})`); } else if (type === 'pruneImages') { const r = await api('/api/maintenance/prune', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ what: 'images' }) }); toast(`清理完成,释放 ${fmtBytes(r.reclaimed)}(${r.deleted} 个镜像)`); } else if (type === 'pruneBuildCache') { const r = await api('/api/maintenance/prune', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ what: 'buildCache' }) }); toast(`构建缓存已清理,释放 ${fmtBytes(r.reclaimed)}`); } setTimeout(render, 900); } catch (err) { toast(err.message, true); } b.disabled = false; }); $$('#view .app-card').forEach(card => { card.addEventListener('click', async (e) => { const port = e.target.closest('.port'); if (port) { e.stopPropagation(); window.open(`http://${location.hostname}:${port.dataset.port}`, '_blank'); return; } const b = e.target.closest('[data-app-act]'); if (!b) return openApp(card.dataset.app); e.stopPropagation(); const act = b.dataset.appAct; if (act === 'detail') return openApp(card.dataset.app); if (act === 'stop' && !confirm('确定停止该应用的全部容器?')) return; b.disabled = true; try { const r = await api(`/api/apps/${encodeURIComponent(card.dataset.app)}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act }) }); const ok = r.results.filter(x => x.ok).length; toast(`${act === 'start' ? '启动' : act === 'restart' ? '重启' : '停止'}完成(${ok}/${r.results.length})`); setTimeout(render, 900); } catch (err) { toast(err.message, true); } b.disabled = false; }); }); } /* ---------------- 应用详情 ---------------- */ async function openApp(key) { if (state.currentApp !== key) state.appTab = 'containers'; state.currentApp = key; state.view = 'app-detail'; $$('#nav a').forEach(a => a.classList.remove('active')); const a = await api(`/api/apps/${encodeURIComponent(key)}`); $('#pageTitle').textContent = '应用详情'; const disk = null; const conts = a.containers.map(c => ` ${esc(c.name)}
${esc(c.service || c.image)}
${c.state === 'running' ? (c.health === 'unhealthy' ? '异常' : '运行中') : '已停止'} ${fmtPct(c.stats.cpu)} ${fmtBytes(c.stats.mem)} ↑${fmtRate(c.stats.txBps)} ↓${fmtRate(c.stats.rxBps)} ${c.restarts || 0} ${c.state === 'running' ? fmtDur(c.runMs !== null && c.runMs !== undefined ? c.runMs : Date.now() - Date.parse(c.startedAt)) : '—'} `).join(''); $('#view').innerHTML = `
${avatar(a.name)}

${esc(a.name)}

${a.type === 'compose' ? 'Compose 应用' : '单容器'} · ${a.running}/${a.total} 运行 · ${a.key}
${a.statusText}
${a.issues.length ? `
${a.issues.map(i => `
${esc(i.text)}
`).join('')}
` : ''}
CPU 占整机
${fmtPct(a.cpuPctOfMachine)}
内存合计
${fmtBytes(a.mem)}
网络
↑${fmtRate(a.txBps)} ↓${fmtRate(a.rxBps)}
重启总数
${a.restarts}
运行时长
${a.runMs === null ? '已停止' : a.runMs < 60000 ? '1 分钟内' : fmtDur(a.runMs)}
可用率
${a.uptime !== null ? a.uptime + '%' : '采样中'}
端口
${a.ports.map(p => `:${p.public}`).join(' ') || '无'}
`; $('#backBtn').onclick = () => { $('#pageTitle').textContent = '概览'; go('apps'); }; $$('#view [data-app-act]').forEach(b => b.onclick = async () => { const act = b.dataset.appAct; if (act === 'stop' && !confirm('确定停止该应用的全部容器?')) return; b.disabled = true; try { const r = await api(`/api/apps/${encodeURIComponent(key)}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act }) }); toast(`完成(${r.results.filter(x => x.ok).length}/${r.results.length})`); setTimeout(() => openApp(key), 1000); } catch (e) { toast(e.message, true); b.disabled = false; } }); $$('#view .port').forEach(p => p.onclick = () => window.open(`http://${location.hostname}:${p.dataset.port}`, '_blank')); const body = $('#appTabBody'); const drawTab = async () => { $$('#appTabs button').forEach(b => b.classList.toggle('active', b.dataset.atab === state.appTab)); if (state.appTab === 'containers') { body.innerHTML = `${conts}
容器状态CPU内存网络重启运行时长操作
`; $$('#appTabBody [data-c-act]').forEach(b => b.onclick = async () => { const act = b.dataset.cAct, id = b.dataset.id; if (act === 'detail') return openDrawer(id); const running = b.textContent.includes('停止'); try { await api(`/api/containers/${id}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act === 'restart' ? 'restart' : (running ? 'stop' : 'start') }) }); toast('已执行'); setTimeout(() => openApp(key), 900); } catch (e) { toast(e.message, true); } }); } else if (state.appTab === 'logs') { body.innerHTML = `
按容器名加前缀合并显示
加载中…
`; const load = async () => { const r = await api(`/api/apps/${encodeURIComponent(key)}/logs?tail=${$('#appLogTail').value || 60}`); $('#appLogBox').textContent = r.logs || '(无日志)'; }; $('#appLogReload').onclick = load; await load(); } else { body.innerHTML = `
${a.events.length ? a.events.map(e => `
${timeStr(e.t)}
${esc(e.title)}
${esc(e.detail || '')}
`).join('') : '
该应用暂无事件
'}
`; } }; $$('#appTabs button').forEach(b => b.onclick = () => { state.appTab = b.dataset.atab; drawTab(); }); await drawTab(); } /* ---------------- 容器列表 ---------------- */ async function renderContainers(silent, mode = 'running') { const q = state.q ? `&q=${encodeURIComponent(state.q)}` : ''; const filter = mode === 'stopped' ? '&all=1&state=stopped' : '&all=0'; const [data, h, pend] = await Promise.all([ api(`/api/containers?sort=${state.sort}&order=${state.order}${filter}${q}`), refreshHost(), mode === 'stopped' ? api('/api/pending-apps').catch(() => null) : Promise.resolve(null), ]); const html = data.items.map(c => { const s = c.stats; const cpuCls = s.cpu > 80 ? 'hot' : s.cpu > 40 ? 'warn' : ''; const memCls = s.memPct > 80 ? 'hot' : s.memPct > 50 ? 'warn' : ''; const ports = c.ports.filter(p => p.public).slice(0, 2); const linkBtn = ports.length ? `${icon('link')}` : ''; return `
${mode === 'stopped' ? `` : ''}
${icon('box')}
${esc(c.name)}
${c.project ? '项目: ' + esc(c.project) : esc(shortImg(c.image))} · ${c.state === 'running' ? (c.runMs === null || c.runMs === undefined ? '运行中' : c.runMs < 60000 ? '刚刚启动' : '已运行 ' + fmtDurCompact(c.runMs)) : '已停止'}${c.restarts ? ` · 重启${c.restarts}` : ''}
CPU
${fmtPct(s.cpu)}
内存
${fmtBytes(s.mem)} ${s.memPct ? s.memPct.toFixed(1) + '%' : ''}
网络
↑${fmtRate(s.txBps)} ↓${fmtRate(s.rxBps)}
磁盘 IO
R ${fmtRate(s.rdBps)} / W ${fmtRate(s.wrBps)}
${linkBtn} ${icon('power')} ${c.state === 'running' ? `${icon('restart')}` : ''} ${icon('trash')} ${icon('more')}
`; }).join(''); const pendHtml = (mode === 'stopped' && pend && pend.items.length) ? `
有镜像但未启动的应用${pend.items.length} 个 · 扫描 ${esc((pend.root || '').replace(/^.*\/docker$/, '.../docker'))}
${pend.items.map(p => `
${esc(p.name)}${p.services} 个服务
${esc(p.file.replace((pend.root || '') + '/', ''))}
${p.images.missing.length ? `缺 ${p.images.missing.length} 个镜像 · 自动拉取` : `镜像就绪 ${p.images.present}/${p.images.total}`}
`).join('')}
已停止的容器${data.total} 个
` : ''; const label = mode === 'stopped' ? '已停止' : '运行中'; const batchHtml = (mode === 'stopped' && data.items.length) ? `
已选 ${[...state.sel].filter(id => data.items.some(c => c.id === id)).length} / ${data.items.length} 只删容器,不删数据卷
` : ''; $('#view').innerHTML = `${pendHtml}${batchHtml}${html || `
${mode === 'stopped' ? '没有已停止的容器' : '没有正在运行的容器'}
`}
共 ${data.total} 个${label}容器 · 排序:${({ cpu: 'CPU', mem: '内存', net: '网络', io: '磁盘IO', pids: '进程数', name: '名称' })[state.sort] || state.sort} ${state.order === 'desc' ? '降序' : '升序'} · 每 ${state.refreshMs / 1000} 秒刷新${h.disk ? ` · /vol1 可用 ${fmtBytes(h.disk.free)}` : ''}
`; $$('#view [data-pend-cmd]').forEach(b => b.onclick = () => { alert(`在宿主机执行:\n\ndocker compose -f ${b.dataset.pendCmd} up -d`); }); $$('#view [data-pend]').forEach(b => b.onclick = async () => { const name = b.dataset.pend; if (!confirm(`启动应用「${name}」?\n\n将执行 docker compose up -d,会创建并运行该项目下的容器。`)) return; b.disabled = true; b.textContent = '启动中…'; try { const r = await api('/api/pending-apps/start', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) }); if (r.ok) { toast(`「${name}」已启动`); setTimeout(() => render(), 1500); } else { alert(`启动失败:\n\n${r.output || '未知错误'}`); b.disabled = false; b.textContent = '启动'; } } catch (e) { toast(e.message, true); b.disabled = false; b.textContent = '启动'; } }); if (mode === 'stopped') { const ids = data.items.map(c => c.id); [...state.sel].forEach(id => { if (!ids.includes(id)) state.sel.delete(id); }); const syncSel = () => { const n = $('#selCount'); if (n) n.textContent = state.sel.size; const b = $('#batchDel'); if (b) { b.disabled = state.sel.size === 0; b.textContent = state.sel.size ? `删除选中 ${state.sel.size} 个` : '删除选中'; } const all = $('#selAll'); if (all) all.checked = state.sel.size > 0 && state.sel.size === ids.length; }; $$('#view .rowsel').forEach(cb => { cb.onclick = (e) => { e.stopPropagation(); if (cb.checked) state.sel.add(cb.dataset.id); else state.sel.delete(cb.dataset.id); syncSel(); }; cb.parentElement.onclick = (e) => e.stopPropagation(); }); const selAll = $('#selAll'); if (selAll) selAll.onclick = () => { if (selAll.checked) ids.forEach(i => state.sel.add(i)); else state.sel.clear(); $$('#view .rowsel').forEach(cb => { cb.checked = selAll.checked; }); syncSel(); }; const bd = $('#batchDel'); if (bd) bd.onclick = async () => { const list = [...state.sel]; if (!list.length) return; if (!confirm(`确定删除选中的 ${list.length} 个容器?\n\n只删除容器,不删除数据卷。`)) return; bd.disabled = true; bd.textContent = '删除中…'; try { const r = await api('/api/containers/batch-delete', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ids: list }) }); const fail = r.results.filter(x => !x.ok); toast(fail.length ? `已删除 ${r.deleted} 个,失败 ${fail.length} 个` : `已删除 ${r.deleted} 个容器`); state.sel.clear(); setTimeout(render, 600); } catch (e) { toast(e.message, true); bd.disabled = false; bd.textContent = '删除选中'; } }; syncSel(); } $$('#view .row').forEach(row => { row.addEventListener('click', async (e) => { if (e.target.closest('.chk')) return; const btn = e.target.closest('[data-act]'); const id = row.dataset.id; if (!btn) return openDrawer(id); e.stopPropagation(); const act = btn.dataset.act; if (act === 'detail') return openDrawer(id); if (act === 'open') { window.open(`http://${location.hostname}:${btn.dataset.ports.split(',')[0]}`, '_blank'); return; } if (act === 'rm') { if (!confirm('确定删除这个容器?(不会删除数据卷)')) return; try { await api(`/api/containers/${id}?force=1`, { method: 'DELETE' }); toast('已删除'); render(); } catch (err) { toast(err.message, true); } return; } const running = row.querySelector('.dot').classList.contains('up'); try { await api(`/api/containers/${id}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: act === 'restart' ? 'restart' : (running ? 'stop' : 'start') }) }); toast('已执行'); setTimeout(render, 700); } catch (err) { toast(err.message, true); } }); }); } /* ---------------- 容器详情抽屉 ---------------- */ async function openDrawer(id) { state.current = id; state.tab = 'stat'; $('#drawer').classList.remove('hidden'); $('#drawerBody').innerHTML = '
加载中…
'; const d = await api(`/api/containers/${id}`); $('#drawerName').textContent = d.info.Name.replace(/^\//, ''); $('#drawerSub').innerHTML = `${esc(d.info.Config.Image)} · ${esc(d.info.State.Status)} · ${esc(d.info.Id.slice(0, 12))}`; const running = d.info.State.Running; $('#drawerActions').innerHTML = ` `; $$('#drawerActions [data-d]').forEach(b => b.onclick = async () => { const a = b.dataset.d; try { if (a === 'rm') { if (!confirm('确定删除该容器?')) return; await api(`/api/containers/${id}?force=1`, { method: 'DELETE' }); closeDrawer(); render(); toast('已删除'); return; } await api(`/api/containers/${id}/action`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: a === 'toggle' ? (running ? 'stop' : 'start') : a }) }); toast('操作成功'); openDrawer(id); render(); } catch (e) { toast(e.message, true); } }); drawTab(d); } async function drawTab(d) { const tab = state.tab; $$('#drawerTabs button').forEach(b => b.classList.toggle('active', b.dataset.tab === tab)); const body = $('#drawerBody'); const s = d.stats || {}; if (tab === 'stat') { body.innerHTML = `
CPU
${fmtPct(s.cpu || 0)}
内存
${fmtBytes(s.mem || 0)}
上限 ${fmtBytes(s.memLimit || 0)} · ${(s.memPct || 0).toFixed(1)}%
网络
↑ ${fmtRate(s.txBps || 0)}
↓ ${fmtRate(s.rxBps || 0)}
累计 ↑${fmtBytes(s.tx || 0)} ↓${fmtBytes(s.rx || 0)}
磁盘 IO
读 ${fmtRate(s.rdBps || 0)}
写 ${fmtRate(s.wrBps || 0)}
累计读 ${fmtBytes(s.rd || 0)} / 写 ${fmtBytes(s.wr || 0)}
进程数
${s.pids || 0}
重启策略
${esc(d.restartPolicy)}
退出码 ${d.exitCode ?? 0}${d.health ? ' · ' + esc(d.health) : ''}

CPU 曲线(约 12 分钟)

当前 ${fmtPct(s.cpu || 0)}

内存曲线

当前 ${fmtBytes(s.mem || 0)}

网络速率

基本信息

启动时间
${esc(d.startedAt || '-')}
镜像
${esc(d.info.Config.Image)}
命令
${esc([].concat(d.entrypoint || [], d.cmd || []).join(' ') || '-')}
端口
${Object.entries(d.ports || {}).map(([p, b]) => `${p} → ${(b || []).map(x => x.HostPort).join(',') || '-'}`).join('
') || '-'}
容器 ID
${esc(d.info.Id)}
`; const hist = d.history || []; drawChart(body, 'cpu', hist.map(x => x.c), v => v.toFixed(1) + '%', '#1a73e8'); drawChart(body, 'mem', hist.map(x => x.m / 1048576), v => v.toFixed(0) + ' MB', '#7a5af8'); drawChart(body, 'net', hist.map(x => (x.rx || 0) + (x.tx || 0)), v => fmtRate(v), '#12b76a'); } else if (tab === 'logs') { body.innerHTML = `
加载中…
`; let es = null; const startStream = () => { if (es) es.close(); es = new EventSource(`/api/containers/${state.current}/logs/stream?tail=${$('#logTail').value || 200}`); es.onmessage = (ev) => { const box = $('#logBox'); if (!box) return; try { box.textContent += JSON.parse(ev.data); } catch (e) {} box.scrollTop = box.scrollHeight; }; }; $('#logReload').onclick = async () => { if (es) { es.close(); es = null; } const r = await api(`/api/containers/${state.current}/logs?tail=${$('#logTail').value || 200}`); $('#logBox').textContent = r.logs || '(无日志)'; if ($('#logLive').checked) startStream(); }; $('#logLive').onchange = (e) => { if (e.target.checked) startStream(); else if (es) { es.close(); es = null; } }; const r = await api(`/api/containers/${state.current}/logs?tail=${$('#logTail').value || 200}`); $('#logBox').textContent = r.logs || '(无日志)'; if ($('#logLive').checked) startStream(); } else if (tab === 'env') { body.innerHTML = `
环境变量
${(d.env || []).map(e => `
${esc(e.split('=')[0])}
${esc(e.split('=').slice(1).join('='))}
`).join('') || '
-
-
'}
`; } else { body.innerHTML = `

挂载

${(d.mounts || []).map(m => ``).join('') || ''}
宿主机路径 / 卷容器路径模式
${esc(m.Source || m.Name || '')}${esc(m.Destination)}${m.RW ? '读写' : '只读'}
无挂载

网络

${Object.entries(d.networks || {}).map(([n, v]) => ``).join('') || ''}
网络IP网关
${esc(n)}${esc(v.IPAddress || '-')}${esc(v.Gateway || '-')}
无网络
`; } } function drawChart(root, which, values, fmt, color) { const cv = root.querySelector(`canvas[data-chart="${which}"]`); if (!cv) return; const dpr = window.devicePixelRatio || 1; const w = cv.clientWidth || 600, hgt = cv.clientHeight || 90; cv.width = w * dpr; cv.height = hgt * dpr; const ctx = cv.getContext('2d'); ctx.scale(dpr, dpr); ctx.clearRect(0, 0, w, hgt); if (!values || values.length < 2) { ctx.fillStyle = '#98a2b3'; ctx.font = '12px sans-serif'; ctx.fillText('采集中…', 12, hgt / 2); return; } const max = Math.max(...values, 1) * 1.15, pad = 8; const x = i => pad + (w - pad * 2) * i / (values.length - 1); const y = v => hgt - pad - (hgt - pad * 2) * (v / max); ctx.beginPath(); ctx.moveTo(x(0), y(values[0])); values.forEach((v, i) => ctx.lineTo(x(i), y(v))); ctx.strokeStyle = color; ctx.lineWidth = 1.8; ctx.lineJoin = 'round'; ctx.stroke(); ctx.lineTo(x(values.length - 1), hgt - pad); ctx.lineTo(x(0), hgt - pad); ctx.closePath(); const g = ctx.createLinearGradient(0, 0, 0, hgt); g.addColorStop(0, color + '33'); g.addColorStop(1, color + '05'); ctx.fillStyle = g; ctx.fill(); ctx.fillStyle = '#98a2b3'; ctx.font = '11px sans-serif'; ctx.fillText(fmt(max / 1.15), 10, 14); ctx.fillText(fmt(values[values.length - 1]), Math.max(10, w - 70), hgt - 10); } /* ---------------- 镜像 / 仓库 / 网络 / 设置 ---------------- */ async function renderImages() { const data = await api('/api/images'); const imgs = data.items || []; const s = data.summary || { total: imgs.length, totalSize: 0, inUse: 0, deletable: 0, deletableSize: 0 }; const useCell = (i) => { if (i.running && i.running.length) { return `运行中 ${i.running.length} 个容器`; } if (i.stopped && i.stopped.length) { return `已停止容器引用 ${i.stopped.length}`; } return '未使用'; }; $('#view').innerHTML = ` ${imgs.map(i => ``).join('')}
镜像ID大小使用情况创建
${(i.tags.length ? i.tags : [':']).map(t => `${esc(t)}`).join(' ')} ${esc(i.shortId)} ${fmtBytes(i.size)} ${useCell(i)} ${new Date(i.created * 1000).toLocaleDateString('zh-CN')} ${i.canDelete ? `` : '使用中,不可删除'}
共 ${s.total} 个镜像 · 合计 ${fmtBytes(s.totalSize)} · 使用中 ${s.inUse} 个 · 可删除 ${s.deletable} 个(可释放 ${fmtBytes(s.deletableSize)})
`; $$('#view [data-img]').forEach(b => b.onclick = async () => { if (!confirm('确定删除该镜像?')) return; try { await api(`/api/images/${encodeURIComponent(b.dataset.img)}?force=1`, { method: 'DELETE' }); toast('已删除'); render(); } catch (e) { toast(e.message, true); } }); } async function renderRegistry() { $('#view').innerHTML = `

拉取镜像

国内建议用加速前缀:docker.1ms.run/library/nginx:latest
等待操作…

常用镜像

${['nginx:latest', 'redis:7-alpine', 'postgres:17', 'mysql:8', 'mongo:8', 'louislam/uptime-kuma:2', 'jellyfin/jellyfin:latest'].map(t => ``).join('')}
`; const doPull = (name) => { const box = $('#pullLog'); box.textContent = ''; fetch('/api/images/pull', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ image: name }) }) .then(async (resp) => { const reader = resp.body.getReader(); const dec = new TextDecoder(); let buf = ''; while (true) { const { done, value } = await reader.read(); if (done) break; buf += dec.decode(value, { stream: true }); const parts = buf.split('\n\n'); buf = parts.pop(); for (const p of parts) { const line = p.replace(/^data: /, ''); if (!line) continue; try { const j = JSON.parse(line); if (j.error) box.textContent += `\n❌ ${j.error}`; else if (j.status) box.textContent += `\n${j.status}${j.progress ? ' ' + j.progress : ''}`; if (j.done) box.textContent += '\n✅ 完成'; } catch (e) {} } box.scrollTop = box.scrollHeight; } }).catch(e => box.textContent += `\n❌ ${e.message}`); }; $('#pullBtn').onclick = () => { const n = $('#pullName').value.trim(); if (n) doPull(n); }; $$('#view [data-pull]').forEach(b => b.onclick = () => { $('#pullName').value = b.dataset.pull; doPull(b.dataset.pull); }); } async function renderNetworks() { const nets = await api('/api/networks'); $('#view').innerHTML = ` ${nets.map(n => ``).join('')}
网络名驱动子网网关容器数范围
${esc(n.name)}${n.internal ? ' 内部' : ''}${esc(n.driver)} ${n.subnet.map(esc).join('
') || '-'}
${n.gateway.map(esc).join('
') || '-'}
${n.containers}${esc(n.scope)}
共 ${nets.length} 个网络
`; } async function renderSettings() { const s = await api('/api/settings'); $('#view').innerHTML = `

告警规则

%
%
分钟
容器未运行、健康检查失败、重启次数增加、超过资源阈值时产生事件;「异常」级事件按上面的间隔去重后推送到 webhook(POST JSON:title / level / app / detail / time / host)。
—
`; $('#saveBtn').onclick = async () => { try { await api('/api/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ thresholds: { cpu: Number($('#th_cpu').value), mem: Number($('#th_mem').value) }, debounceMinutes: Number($('#th_debounce').value), webhook: $('#th_webhook').value, notify: $('#th_notify').checked, }), }); toast('已保存'); } catch (e) { toast(e.message, true); } }; $('#testBtn').onclick = async () => { try { await api('/api/settings/test', { method: 'POST' }); $('#setLog').textContent = '测试推送已发送'; toast('已发送'); } catch (e) { $('#setLog').textContent = '推送失败:' + e.message; toast(e.message, true); } }; $('#eventBtn').onclick = async () => { const ev = await api('/api/events?limit=50'); $('#setLog').textContent = ev.items.length ? ev.items.map(e => `${timeStr(e.t)} [${e.level}] ${e.title} — ${e.detail}`).join('\n') : '暂无事件'; }; } /* ---------------- 添加容器 ---------------- */ function openAddModal() { if (state.view === 'registry') { go('registry'); return; } if (state.view === 'images') return pruneImages(); $('#modalTitle').textContent = '添加容器'; $('#modalBody').innerHTML = ` `; $('#modal').classList.remove('hidden'); $('#modalOk').onclick = async () => { const image = $('#f_image').value.trim(); if (!image) return toast('请填写镜像', true); const ports = $('#f_ports').value.split('\n').map(l => l.trim()).filter(Boolean).map(l => { const [host, cont] = l.split(':'); return { host: Number(host), container: Number(cont || host) }; }); const body = { image, name: $('#f_name').value.trim() || undefined, ports, env: $('#f_env').value.split('\n').map(s => s.trim()).filter(Boolean), volumes: $('#f_vol').value.split('\n').map(s => s.trim()).filter(Boolean), restart: $('#f_restart').value.trim() || 'always', }; $('#modalOk').disabled = true; $('#modalOk').textContent = '创建中…'; try { await api('/api/containers', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); toast('创建成功'); $('#modal').classList.add('hidden'); render(); } catch (e) { toast(e.message, true); } $('#modalOk').disabled = false; $('#modalOk').textContent = '确定'; }; } async function pruneImages() { if (!confirm('清理未被使用的悬空镜像?')) return; try { const r = await api('/api/images/prune', { method: 'POST' }); toast(`已清理,释放 ${fmtBytes(r.SpaceReclaimed || 0)}`); render(); } catch (e) { toast(e.message, true); } } /* ---------------- 事件绑定 ---------------- */ $('#nav').addEventListener('click', e => { const a = e.target.closest('a'); if (a) go(a.dataset.view); }); let qTimer = null; $('#search').addEventListener('input', e => { state.q = e.target.value; clearTimeout(qTimer); qTimer = setTimeout(() => { if (state.currentApp) return; render(); }, 250); }); $('#sort').addEventListener('change', e => { state.sort = e.target.value; render(); }); $('#orderBtn').addEventListener('click', () => { state.order = state.order === 'desc' ? 'asc' : 'desc'; $('#orderBtn').textContent = state.order === 'desc' ? '降序 ↓' : '升序 ↑'; render(); }); $('#refreshBtn').addEventListener('click', () => render()); $('#refreshSel').addEventListener('change', (e) => { state.refreshMs = Math.min(30000, Math.max(1000, Number(e.target.value) || 3000)); localStorage.setItem(REFRESH_KEY, state.refreshMs); clearInterval(state.timer); const view = state.view; state.timer = setInterval(() => { if (!document.hidden && (state.view === view || state.view === 'app-detail')) render(true); }, state.refreshMs); toast(`刷新间隔已设为 ${state.refreshMs / 1000} 秒`); }); $('#addBtn').addEventListener('click', openAddModal); $('#drawerClose').onclick = () => $('#drawer').classList.add('hidden'); $('#drawerMask').onclick = () => $('#drawer').classList.add('hidden'); $('#drawerTabs').addEventListener('click', async e => { const b = e.target.closest('button'); if (!b) return; state.tab = b.dataset.tab; if (state.current) drawTab(await api(`/api/containers/${state.current}`)); }); $('#modalCancel').onclick = () => $('#modal').classList.add('hidden'); $('#modalMask').onclick = () => $('#modal').classList.add('hidden'); document.addEventListener('keydown', e => { if (e.key === 'Escape') { $('#modal').classList.add('hidden'); $('#drawer').classList.add('hidden'); } }); paintIcons(); go('apps');