Publish reviewed history-free open-source snapshot (2026-10-12)
This commit is contained in:
@@ -0,0 +1,214 @@
|
||||
(() => {
|
||||
"use strict";
|
||||
|
||||
const root = document.querySelector(".traffic-monitor");
|
||||
if (!root) return;
|
||||
|
||||
const endpoint = root.dataset.endpoint;
|
||||
const nodeStrip = document.getElementById("traffic-nodes");
|
||||
const canvas = document.getElementById("traffic-chart");
|
||||
const empty = document.getElementById("traffic-empty");
|
||||
const tooltip = document.getElementById("traffic-tooltip");
|
||||
const ctx = canvas.getContext("2d");
|
||||
const state = { minutes: 60, nodes: [], selectedId: null, points: [] };
|
||||
let loading = false;
|
||||
|
||||
const formatRate = (bytesPerSecond) => {
|
||||
const bits = Number(bytesPerSecond || 0) * 8;
|
||||
if (bits >= 1e9) return `${(bits / 1e9).toFixed(2)} Gbps`;
|
||||
if (bits >= 1e6) return `${(bits / 1e6).toFixed(2)} Mbps`;
|
||||
if (bits >= 1e3) return `${(bits / 1e3).toFixed(1)} Kbps`;
|
||||
return `${Math.round(bits)} bps`;
|
||||
};
|
||||
|
||||
const formatBytes = (bytes) => {
|
||||
let value = Number(bytes || 0);
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
let unit = 0;
|
||||
while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit += 1; }
|
||||
return `${value.toFixed(unit === 0 ? 0 : value >= 100 ? 0 : value >= 10 ? 1 : 2)} ${units[unit]}`;
|
||||
};
|
||||
|
||||
const formatTime = (value, includeDate = false) => {
|
||||
if (!value) return "尚未上报";
|
||||
return new Intl.DateTimeFormat("zh-CN", {
|
||||
month: includeDate ? "2-digit" : undefined,
|
||||
day: includeDate ? "2-digit" : undefined,
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: includeDate ? undefined : "2-digit",
|
||||
hour12: false,
|
||||
}).format(new Date(value));
|
||||
};
|
||||
|
||||
const selectedNode = () => state.nodes.find((node) => node.id === state.selectedId) || state.nodes[0];
|
||||
|
||||
function renderNodes() {
|
||||
if (!state.nodes.length) {
|
||||
nodeStrip.innerHTML = '<div class="traffic-loading">尚未配置可用节点</div>';
|
||||
return;
|
||||
}
|
||||
nodeStrip.innerHTML = state.nodes.map((node) => `
|
||||
<button type="button" class="traffic-node ${node.online ? "" : "is-offline"} ${node.id === state.selectedId ? "is-active" : ""}" data-node-id="${node.id}">
|
||||
<span class="traffic-node-head">
|
||||
<span class="traffic-node-name"><i class="node-online-dot"></i>${escapeHtml(node.name)}</span>
|
||||
<small>${node.online ? "在线" : "离线"}</small>
|
||||
</span>
|
||||
<span class="traffic-node-region">${escapeHtml(node.slug)} · ${escapeHtml(node.region)}</span>
|
||||
<span class="traffic-node-speed">
|
||||
<span>下载<b>${formatRate(node.current_download_bytes_per_second)}</b></span>
|
||||
<span>上传<b>${formatRate(node.current_upload_bytes_per_second)}</b></span>
|
||||
</span>
|
||||
</button>
|
||||
`).join("");
|
||||
nodeStrip.querySelectorAll("[data-node-id]").forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
state.selectedId = Number(button.dataset.nodeId);
|
||||
render();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderSummary(node) {
|
||||
const set = (id, value) => { document.getElementById(id).textContent = value; };
|
||||
if (!node) {
|
||||
["current-download", "current-upload", "total-traffic", "active-subscriptions"].forEach((id) => set(id, "--"));
|
||||
set("chart-title", "请选择节点");
|
||||
return;
|
||||
}
|
||||
set("current-download", formatRate(node.current_download_bytes_per_second));
|
||||
set("current-upload", formatRate(node.current_upload_bytes_per_second));
|
||||
set("total-traffic", formatBytes(node.total_upload_bytes + node.total_download_bytes));
|
||||
set("total-breakdown", `上传 ${formatBytes(node.total_upload_bytes)} · 下载 ${formatBytes(node.total_download_bytes)}`);
|
||||
set("active-subscriptions", `${node.active_subscriptions} 个`);
|
||||
set("last-seen", node.last_seen_at ? `最后上报 ${formatTime(node.last_seen_at)}` : "等待节点上报");
|
||||
set("chart-title", `${node.name} · ${node.region}`);
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value ?? "").replace(/[&<>'"]/g, (char) => ({
|
||||
"&": "&", "<": "<", ">": ">", "'": "'", '"': """,
|
||||
})[char]);
|
||||
}
|
||||
|
||||
function drawChart(node) {
|
||||
const samples = node?.samples || [];
|
||||
empty.hidden = samples.length > 0;
|
||||
tooltip.hidden = true;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const dpr = Math.max(1, window.devicePixelRatio || 1);
|
||||
canvas.width = Math.round(rect.width * dpr);
|
||||
canvas.height = Math.round(rect.height * dpr);
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ctx.clearRect(0, 0, rect.width, rect.height);
|
||||
state.points = [];
|
||||
if (!samples.length || rect.width < 120 || rect.height < 100) return;
|
||||
|
||||
const pad = { top: 18, right: 18, bottom: 30, left: 67 };
|
||||
const width = rect.width - pad.left - pad.right;
|
||||
const height = rect.height - pad.top - pad.bottom;
|
||||
const start = Date.now() - state.minutes * 60 * 1000;
|
||||
const end = Date.now();
|
||||
const maxBps = Math.max(1, ...samples.flatMap((sample) => [sample.upload_bytes_per_second, sample.download_bytes_per_second]));
|
||||
const topBps = maxBps * 1.15;
|
||||
const xFor = (at) => pad.left + Math.max(0, Math.min(1, (new Date(at).getTime() - start) / (end - start))) * width;
|
||||
const yFor = (value) => pad.top + height - (Number(value || 0) / topBps) * height;
|
||||
|
||||
ctx.font = "12px system-ui, sans-serif";
|
||||
ctx.lineWidth = 1;
|
||||
for (let row = 0; row <= 4; row += 1) {
|
||||
const y = pad.top + (height * row / 4);
|
||||
ctx.strokeStyle = "#e6eef5";
|
||||
ctx.beginPath(); ctx.moveTo(pad.left, y); ctx.lineTo(rect.width - pad.right, y); ctx.stroke();
|
||||
ctx.fillStyle = "#8294a7";
|
||||
ctx.textAlign = "right";
|
||||
ctx.fillText(formatRate(topBps * (1 - row / 4)), pad.left - 10, y + 4);
|
||||
}
|
||||
for (let col = 0; col <= 4; col += 1) {
|
||||
const x = pad.left + width * col / 4;
|
||||
ctx.fillStyle = "#8294a7";
|
||||
ctx.textAlign = col === 0 ? "left" : col === 4 ? "right" : "center";
|
||||
ctx.fillText(formatTime(start + (end - start) * col / 4, state.minutes >= 1440), x, rect.height - 7);
|
||||
}
|
||||
|
||||
const drawSeries = (field, color, fillColor) => {
|
||||
const gradient = ctx.createLinearGradient(0, pad.top, 0, pad.top + height);
|
||||
gradient.addColorStop(0, fillColor);
|
||||
gradient.addColorStop(1, "rgba(255,255,255,0)");
|
||||
ctx.beginPath();
|
||||
samples.forEach((sample, index) => {
|
||||
const x = xFor(sample.at); const y = yFor(sample[field]);
|
||||
index ? ctx.lineTo(x, y) : ctx.moveTo(x, y);
|
||||
});
|
||||
const last = samples[samples.length - 1]; const first = samples[0];
|
||||
ctx.lineTo(xFor(last.at), pad.top + height);
|
||||
ctx.lineTo(xFor(first.at), pad.top + height);
|
||||
ctx.closePath(); ctx.fillStyle = gradient; ctx.fill();
|
||||
ctx.beginPath();
|
||||
samples.forEach((sample, index) => {
|
||||
const x = xFor(sample.at); const y = yFor(sample[field]);
|
||||
index ? ctx.lineTo(x, y) : ctx.moveTo(x, y);
|
||||
});
|
||||
ctx.strokeStyle = color; ctx.lineWidth = 2.5; ctx.lineJoin = "round"; ctx.lineCap = "round"; ctx.stroke();
|
||||
};
|
||||
drawSeries("download_bytes_per_second", "#1478e6", "rgba(20,120,230,.16)");
|
||||
drawSeries("upload_bytes_per_second", "#09b7dc", "rgba(9,183,220,.09)");
|
||||
state.points = samples.map((sample) => ({ x: xFor(sample.at), sample }));
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (!state.selectedId && state.nodes.length) state.selectedId = state.nodes[0].id;
|
||||
if (state.selectedId && !state.nodes.some((node) => node.id === state.selectedId)) state.selectedId = state.nodes[0]?.id || null;
|
||||
renderNodes();
|
||||
const node = selectedNode();
|
||||
renderSummary(node);
|
||||
drawChart(node);
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
if (loading) return;
|
||||
loading = true;
|
||||
const live = document.getElementById("traffic-live");
|
||||
try {
|
||||
const response = await fetch(`${endpoint}?minutes=${state.minutes}`, { credentials: "same-origin", cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const data = await response.json();
|
||||
state.nodes = data.nodes || [];
|
||||
live.classList.remove("is-error");
|
||||
live.querySelector("span").textContent = "监控数据连接正常";
|
||||
document.getElementById("traffic-updated").textContent = `刷新于 ${formatTime(data.generated_at)}`;
|
||||
render();
|
||||
} catch (error) {
|
||||
live.classList.add("is-error");
|
||||
live.querySelector("span").textContent = "监控数据暂时中断";
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
document.querySelectorAll("[data-minutes]").forEach((button) => {
|
||||
button.addEventListener("click", () => {
|
||||
document.querySelectorAll("[data-minutes]").forEach((item) => item.classList.remove("is-active"));
|
||||
button.classList.add("is-active");
|
||||
state.minutes = Number(button.dataset.minutes);
|
||||
refresh();
|
||||
});
|
||||
});
|
||||
|
||||
canvas.addEventListener("mousemove", (event) => {
|
||||
if (!state.points.length) return;
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
const mouseX = event.clientX - rect.left;
|
||||
const point = state.points.reduce((best, candidate) => Math.abs(candidate.x - mouseX) < Math.abs(best.x - mouseX) ? candidate : best);
|
||||
if (Math.abs(point.x - mouseX) > 36) { tooltip.hidden = true; return; }
|
||||
tooltip.innerHTML = `<b>${formatTime(point.sample.at, true)}</b><span>下载 ${formatRate(point.sample.download_bytes_per_second)}</span><span>上传 ${formatRate(point.sample.upload_bytes_per_second)}</span>`;
|
||||
tooltip.hidden = false;
|
||||
tooltip.style.left = `${Math.min(rect.width - 175, Math.max(4, point.x + 10))}px`;
|
||||
tooltip.style.top = "18px";
|
||||
});
|
||||
canvas.addEventListener("mouseleave", () => { tooltip.hidden = true; });
|
||||
window.addEventListener("resize", () => drawChart(selectedNode()));
|
||||
|
||||
refresh();
|
||||
window.setInterval(refresh, 5000);
|
||||
})();
|
||||
@@ -0,0 +1,16 @@
|
||||
/* Subscription URLs are credentials: no logging, analytics or network calls. */
|
||||
document.querySelectorAll('[data-copy-target]').forEach(function (button) {
|
||||
button.addEventListener('click', async function () {
|
||||
const input = document.getElementById(button.dataset.copyTarget);
|
||||
const feedback = document.getElementById('copy-feedback');
|
||||
if (!input) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(input.value);
|
||||
if (feedback) feedback.textContent = '已复制订阅地址,请勿转发给他人。';
|
||||
} catch (_) {
|
||||
input.focus();
|
||||
input.select();
|
||||
if (feedback) feedback.textContent = '浏览器未允许自动复制,已选中地址,请手动复制。';
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
const tabs = Array.from(document.querySelectorAll("[data-workflow-tab]"));
|
||||
if (!tabs.length) return;
|
||||
|
||||
const panels = new Map(
|
||||
tabs.map((tab) => [tab.dataset.workflowTab, document.getElementById(tab.dataset.workflowTab)])
|
||||
);
|
||||
|
||||
function activate(tab, moveFocus) {
|
||||
tabs.forEach((item) => {
|
||||
const selected = item === tab;
|
||||
item.classList.toggle("is-active", selected);
|
||||
item.setAttribute("aria-selected", String(selected));
|
||||
item.tabIndex = selected ? 0 : -1;
|
||||
const panel = panels.get(item.dataset.workflowTab);
|
||||
if (panel) {
|
||||
panel.hidden = !selected;
|
||||
panel.classList.toggle("is-active", selected);
|
||||
}
|
||||
});
|
||||
if (moveFocus) tab.focus();
|
||||
if (history.replaceState) history.replaceState(null, "", `#${tab.dataset.workflowTab}`);
|
||||
}
|
||||
|
||||
tabs.forEach((tab, index) => {
|
||||
tab.addEventListener("click", () => activate(tab, false));
|
||||
tab.addEventListener("keydown", (event) => {
|
||||
let target = null;
|
||||
if (event.key === "ArrowRight") target = tabs[(index + 1) % tabs.length];
|
||||
if (event.key === "ArrowLeft") target = tabs[(index - 1 + tabs.length) % tabs.length];
|
||||
if (event.key === "Home") target = tabs[0];
|
||||
if (event.key === "End") target = tabs[tabs.length - 1];
|
||||
if (!target) return;
|
||||
event.preventDefault();
|
||||
activate(target, true);
|
||||
});
|
||||
});
|
||||
|
||||
const initial = tabs.find((tab) => `#${tab.dataset.workflowTab}` === window.location.hash);
|
||||
if (initial) activate(initial, false);
|
||||
})();
|
||||
Reference in New Issue
Block a user