Files
douyi_guaji_main/webui/js/dom_utils.js
T

91 lines
2.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// DOM and formatting helpers shared by WebUI classic scripts.
function $(id) { return document.getElementById(id); }
function fmtTime(ts) {
if (!ts) return "-";
try {
return new Date(ts * 1000).toLocaleString();
} catch {
return "-";
}
}
function fmtNum(v) {
if (v === null || typeof v === "undefined") return "-";
const n = Number(v);
if (!Number.isFinite(n)) return String(v);
return n.toLocaleString("en-US");
}
function fmtDuration(seconds) {
const s = Math.max(0, parseInt(seconds || 0, 10));
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
const sec = s % 60;
const pad = (n) => String(n).padStart(2, "0");
// mono 格式:HH:MM:SS(>1h)/ MM:SS(其他),方便 tabular-nums 对齐
if (h > 0) return `${pad(h)}:${pad(m)}:${pad(sec)}`;
return `${pad(m)}:${pad(sec)}`;
}
function setTextIfExists(id, text) {
const el = $(id);
if (!el) return;
const next = String(text ?? "-");
// 仅取文本节点(跳过子元素如 .copyBtn / .statTrend)来比较和读取当前值
const getTextOnly = (node) => {
let s = "";
for (const ch of node.childNodes) if (ch.nodeType === Node.TEXT_NODE) s += ch.textContent;
return s;
};
const prev = getTextOnly(el);
// 仅对 statValue 有效:值变化时短暂高亮 + 趋势箭头
if (el.classList.contains("statValue") && prev !== next && next !== "-") {
el.classList.remove("isFlash");
void el.offsetWidth;
el.classList.add("isFlash");
setTimeout(() => el.classList.remove("isFlash"), 700);
// 数字字段才显示趋势
const prevNum = Number(prev);
const nextNum = Number(next);
if (Number.isFinite(prevNum) && Number.isFinite(nextNum) && prevNum !== nextNum) {
let trend = el.querySelector(".statTrend");
if (!trend) {
trend = document.createElement("span");
trend.className = "statTrend";
el.appendChild(trend);
}
const isUp = nextNum > prevNum;
trend.textContent = isUp ? "▲" : "▼";
trend.classList.toggle("isUp", isUp);
trend.classList.toggle("isDown", !isUp);
trend.classList.remove("isFading");
void trend.offsetWidth;
trend.classList.add("isFading");
// 1s 后自动消失
clearTimeout(trend._fadeTimer);
trend._fadeTimer = setTimeout(() => {
if (trend) trend.remove();
}, 1100);
}
}
// 替换:保留所有非文本子节点(如 .copyBtn / .statTrend),仅更新文本
for (const ch of Array.from(el.childNodes)) {
if (ch.nodeType === Node.TEXT_NODE) ch.remove();
}
el.insertBefore(document.createTextNode(next), el.firstChild || null);
}
function clearEl(el) {
while (el && el.firstChild) el.removeChild(el.firstChild);
}
function escapeHtml(s) {
return String(s ?? "")
.replaceAll("&", "&")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#39;");
}