705 lines
27 KiB
JavaScript
705 lines
27 KiB
JavaScript
// UI initialization and chrome helpers shared by WebUI classic scripts.
|
||
function initTheme() {
|
||
const root = document.documentElement;
|
||
const btn = $("btnTheme");
|
||
const mql = window.matchMedia ? window.matchMedia("(prefers-color-scheme: dark)") : null;
|
||
|
||
const apply = (theme) => {
|
||
root.setAttribute("data-theme", theme);
|
||
if (btn) btn.setAttribute("aria-label", theme === "dark" ? "切换到浅色" : "切换到深色");
|
||
};
|
||
|
||
// Initial: respect inline-set attribute (set by head bootstrap), or fall back.
|
||
const initial = root.getAttribute("data-theme")
|
||
|| (mql && mql.matches ? "dark" : "light");
|
||
apply(initial);
|
||
|
||
if (btn) {
|
||
btn.addEventListener("click", () => {
|
||
const next = root.getAttribute("data-theme") === "dark" ? "light" : "dark";
|
||
try { localStorage.setItem("ui-theme", next); } catch (_) {}
|
||
root.classList.add("isThemeSwitching");
|
||
apply(next);
|
||
setTimeout(() => root.classList.remove("isThemeSwitching"), 260);
|
||
});
|
||
}
|
||
|
||
// Follow system changes only when user hasn't picked manually.
|
||
if (mql && typeof mql.addEventListener === "function") {
|
||
mql.addEventListener("change", (ev) => {
|
||
let saved = null;
|
||
try { saved = localStorage.getItem("ui-theme"); } catch (_) {}
|
||
if (saved !== "dark" && saved !== "light") {
|
||
apply(ev.matches ? "dark" : "light");
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
function ensureToastContainer() {
|
||
let c = document.getElementById("toastContainer");
|
||
if (!c) {
|
||
c = document.createElement("div");
|
||
c.id = "toastContainer";
|
||
c.className = "toastContainer";
|
||
c.setAttribute("role", "status");
|
||
c.setAttribute("aria-live", "polite");
|
||
document.body.appendChild(c);
|
||
}
|
||
return c;
|
||
}
|
||
|
||
function toast(message, kind = "info", { duration = 3500 } = {}) {
|
||
if (!message) return;
|
||
const container = ensureToastContainer();
|
||
const t = document.createElement("div");
|
||
t.className = `toast toast-${kind}`;
|
||
const icon = document.createElement("span");
|
||
icon.className = "toastIcon";
|
||
icon.setAttribute("aria-hidden", "true");
|
||
const ICONS = {
|
||
success: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',
|
||
error: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',
|
||
warn: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
|
||
info: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
|
||
};
|
||
icon.innerHTML = ICONS[kind] || ICONS.info;
|
||
const body = document.createElement("div");
|
||
body.className = "toastBody";
|
||
body.textContent = String(message);
|
||
const close = document.createElement("button");
|
||
close.className = "toastClose";
|
||
close.type = "button";
|
||
close.setAttribute("aria-label", "关闭");
|
||
close.innerHTML = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>';
|
||
t.append(icon, body, close);
|
||
container.appendChild(t);
|
||
let timer = setTimeout(remove, duration);
|
||
function remove() {
|
||
if (timer) { clearTimeout(timer); timer = null; }
|
||
t.classList.add("isLeaving");
|
||
setTimeout(() => t.remove(), 220);
|
||
}
|
||
close.addEventListener("click", remove);
|
||
t.addEventListener("mouseenter", () => { if (timer) { clearTimeout(timer); timer = null; } });
|
||
t.addEventListener("mouseleave", () => { if (!timer) timer = setTimeout(remove, 1500); });
|
||
return remove;
|
||
}
|
||
|
||
function initConfigSearch() {
|
||
const input = $("configSearch");
|
||
const clear = $("configSearchClear");
|
||
const empty = $("configSearchEmpty");
|
||
if (!input) return;
|
||
|
||
// Cache: rows = [.row], with their lower-case search text + parent panel
|
||
const rows = Array.from(document.querySelectorAll(".panels .panel .row"));
|
||
const rowMeta = rows.map((row) => {
|
||
const textParts = [];
|
||
row.querySelectorAll(".label, .check span, .hint, span").forEach((el) => {
|
||
const t = (el.textContent || "").trim();
|
||
if (t) textParts.push(t);
|
||
});
|
||
row.querySelectorAll("input[data-key], select[data-key], textarea[data-key]").forEach((el) => {
|
||
if (el.dataset.key) textParts.push(el.dataset.key);
|
||
});
|
||
return { row, panel: row.closest(".panel"), text: textParts.join(" ").toLowerCase() };
|
||
});
|
||
|
||
// Section titles: when filtering, hide sections that have no visible row after them
|
||
const allSectionTitles = Array.from(document.querySelectorAll(".panels .panel .sectionTitle"));
|
||
|
||
const apply = (q) => {
|
||
const query = q.trim().toLowerCase();
|
||
if (clear) clear.toggleAttribute("hidden", !query);
|
||
const countBadge = document.getElementById("configSearchCount");
|
||
|
||
if (!query) {
|
||
// Restore all
|
||
rowMeta.forEach(({ row }) => row.classList.remove("isSearchHidden"));
|
||
allSectionTitles.forEach((s) => s.classList.remove("isSearchHidden"));
|
||
document.querySelectorAll(".panel").forEach((p) => p.classList.remove("isSearchAllHidden"));
|
||
if (empty) empty.hidden = true;
|
||
if (countBadge) countBadge.hidden = true;
|
||
// Re-apply normal tab visibility (panels may have been forced visible)
|
||
const activeTab = document.querySelector(".tabBtn.active[data-target]");
|
||
if (activeTab) {
|
||
const target = activeTab.dataset.target;
|
||
document.querySelectorAll(".panel[data-panel]").forEach((p) => {
|
||
const on = p.dataset.panel === target;
|
||
p.toggleAttribute("hidden", !on);
|
||
p.classList.toggle("active", on);
|
||
});
|
||
}
|
||
return;
|
||
}
|
||
|
||
// While searching: show ALL panels (panels normally hide via [hidden]), then filter rows.
|
||
document.querySelectorAll(".panel[data-panel]").forEach((p) => {
|
||
p.removeAttribute("hidden");
|
||
p.classList.add("active");
|
||
});
|
||
|
||
let totalVisible = 0;
|
||
const visibleByPanel = new Map();
|
||
rowMeta.forEach(({ row, panel, text }) => {
|
||
const match = text.includes(query);
|
||
row.classList.toggle("isSearchHidden", !match);
|
||
if (match) {
|
||
totalVisible++;
|
||
visibleByPanel.set(panel, (visibleByPanel.get(panel) || 0) + 1);
|
||
}
|
||
});
|
||
|
||
// Hide section titles that have no visible row in their following sibling group
|
||
allSectionTitles.forEach((title) => {
|
||
let next = title.nextElementSibling;
|
||
let anyVisible = false;
|
||
while (next && !next.matches(".sectionTitle")) {
|
||
if (next.matches(".row") && !next.classList.contains("isSearchHidden")) { anyVisible = true; break; }
|
||
next = next.nextElementSibling;
|
||
}
|
||
title.classList.toggle("isSearchHidden", !anyVisible);
|
||
});
|
||
|
||
// Hide panels that have zero visible rows
|
||
document.querySelectorAll(".panel[data-panel]").forEach((p) => {
|
||
const visible = visibleByPanel.get(p) || 0;
|
||
p.toggleAttribute("hidden", visible === 0);
|
||
});
|
||
|
||
if (empty) empty.hidden = totalVisible > 0;
|
||
if (countBadge) {
|
||
countBadge.hidden = false;
|
||
countBadge.textContent = `${totalVisible} 项`;
|
||
}
|
||
};
|
||
|
||
let debounceTimer;
|
||
input.addEventListener("input", () => {
|
||
clearTimeout(debounceTimer);
|
||
debounceTimer = setTimeout(() => apply(input.value), 80);
|
||
});
|
||
|
||
if (clear) {
|
||
clear.addEventListener("click", () => {
|
||
input.value = "";
|
||
apply("");
|
||
input.focus();
|
||
});
|
||
}
|
||
|
||
// Platform-aware kbd hint label
|
||
const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || "");
|
||
const kbdMod = $("configSearchKbdMod");
|
||
if (kbdMod) kbdMod.textContent = isMac ? "⌘" : "Ctrl";
|
||
|
||
// ⌘K / Ctrl+K to focus, ESC to clear/blur
|
||
document.addEventListener("keydown", (e) => {
|
||
const mod = isMac ? e.metaKey : e.ctrlKey;
|
||
if (mod && e.key.toLowerCase() === "k") {
|
||
e.preventDefault();
|
||
input.focus();
|
||
input.select();
|
||
return;
|
||
}
|
||
if (e.key === "Escape" && document.activeElement === input) {
|
||
if (input.value) {
|
||
input.value = "";
|
||
apply("");
|
||
} else {
|
||
input.blur();
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
function initFooter() {
|
||
// 版本号尝试从 /api/version 拿;拿不到就用 cache-bust 标识做 fallback
|
||
const verEl = document.getElementById("appFooterVersion");
|
||
const buildEl = document.getElementById("appFooterBuild");
|
||
(async () => {
|
||
try {
|
||
const data = await apiGet("/api/version");
|
||
if (verEl && data?.version) verEl.textContent = "v" + data.version;
|
||
if (buildEl && data?.build) buildEl.textContent = data.build;
|
||
} catch (_) {
|
||
const tag = (document.currentScript?.src || document.querySelector('script[src*="app.js"]')?.src || "")
|
||
.split("v=")[1] || "";
|
||
if (verEl) verEl.textContent = tag ? tag.split("-").pop() : "—";
|
||
if (buildEl) buildEl.textContent = "本地";
|
||
}
|
||
})();
|
||
|
||
// FPS 计数(每秒更新一次)
|
||
const fpsEl = document.getElementById("hudFps");
|
||
if (fpsEl && typeof requestAnimationFrame === "function") {
|
||
let frames = 0, last = performance.now();
|
||
const setFps = (n) => {
|
||
const em = fpsEl.querySelector("em");
|
||
if (em) em.textContent = String(n);
|
||
};
|
||
const tick = (now) => {
|
||
frames++;
|
||
if (now - last >= 1000) {
|
||
setFps(Math.round((frames * 1000) / (now - last)));
|
||
frames = 0;
|
||
last = now;
|
||
}
|
||
requestAnimationFrame(tick);
|
||
};
|
||
requestAnimationFrame(tick);
|
||
}
|
||
|
||
// PING:每 5s 测一次 /api/version 响应时间
|
||
const pingEl = document.getElementById("hudPing");
|
||
if (pingEl) {
|
||
const setPing = (ms) => {
|
||
const em = pingEl.querySelector("em");
|
||
if (em) em.textContent = ms === null ? "—" : String(ms);
|
||
};
|
||
const ping = async () => {
|
||
const t0 = performance.now();
|
||
try {
|
||
await fetch("/api/version", { cache: "no-store" });
|
||
setPing(Math.max(1, Math.round(performance.now() - t0)));
|
||
} catch (_) {
|
||
setPing(null);
|
||
}
|
||
};
|
||
ping();
|
||
setInterval(ping, 5000);
|
||
}
|
||
}
|
||
|
||
function attachCopyButtons() {
|
||
// 给指定 statValue 元素绑定一键复制(hover 显示按钮,点击复制文本)
|
||
const ids = ["statPid", "statTraceId"];
|
||
for (const id of ids) {
|
||
const el = document.getElementById(id);
|
||
if (!el || el.dataset.copyBound === "1") continue;
|
||
el.dataset.copyBound = "1";
|
||
el.classList.add("hasCopy");
|
||
const btn = document.createElement("button");
|
||
btn.type = "button";
|
||
btn.className = "copyBtn";
|
||
btn.setAttribute("aria-label", "复制");
|
||
btn.setAttribute("data-tooltip", "复制");
|
||
btn.setAttribute("data-tooltip-pos", "bottom");
|
||
btn.innerHTML = '<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
|
||
btn.addEventListener("click", async (e) => {
|
||
e.stopPropagation();
|
||
const text = (el.textContent || "").trim();
|
||
if (!text || text === "-") {
|
||
toast("暂无可复制内容", "warn", { duration: 1800 });
|
||
return;
|
||
}
|
||
try {
|
||
await navigator.clipboard.writeText(text);
|
||
toast("已复制:" + (text.length > 24 ? text.slice(0, 24) + "…" : text), "success", { duration: 1800 });
|
||
} catch (err) {
|
||
// fallback for non-secure context
|
||
const ta = document.createElement("textarea");
|
||
ta.value = text;
|
||
ta.style.position = "fixed";
|
||
ta.style.opacity = "0";
|
||
document.body.appendChild(ta);
|
||
ta.select();
|
||
try { document.execCommand("copy"); toast("已复制", "success", { duration: 1800 }); }
|
||
catch (_) { toast("复制失败", "error", { duration: 2400 }); }
|
||
document.body.removeChild(ta);
|
||
}
|
||
});
|
||
el.appendChild(btn);
|
||
}
|
||
}
|
||
|
||
function initKeyboardShortcuts() {
|
||
const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || "");
|
||
document.addEventListener("keydown", (e) => {
|
||
const mod = isMac ? e.metaKey : e.ctrlKey;
|
||
if (!mod) return;
|
||
const key = e.key.toLowerCase();
|
||
// ⌘S / Ctrl+S → 保存配置
|
||
if (key === "s") {
|
||
e.preventDefault();
|
||
const btn = document.getElementById("btnSave");
|
||
if (btn && !btn.disabled) btn.click();
|
||
return;
|
||
}
|
||
// ⌘Enter / Ctrl+Enter → 启动运行
|
||
if (key === "enter") {
|
||
e.preventDefault();
|
||
const btn = document.getElementById("btnStart");
|
||
if (btn && !btn.disabled) btn.click();
|
||
return;
|
||
}
|
||
});
|
||
}
|
||
|
||
function initHeaderScroll() {
|
||
const header = document.querySelector(".header");
|
||
const scrollTop = document.getElementById("btnScrollTop");
|
||
const onScroll = () => {
|
||
if (header) header.classList.toggle("isScrolled", window.scrollY > 8);
|
||
if (scrollTop) scrollTop.toggleAttribute("hidden", window.scrollY < 240);
|
||
};
|
||
window.addEventListener("scroll", onScroll, { passive: true });
|
||
if (scrollTop) {
|
||
scrollTop.addEventListener("click", () => {
|
||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||
});
|
||
}
|
||
onScroll();
|
||
}
|
||
|
||
function initShotFullscreen() {
|
||
const btn = document.getElementById("btnShotFullscreen");
|
||
const img = document.getElementById("liveShot");
|
||
if (!btn || !img) return;
|
||
btn.addEventListener("click", () => {
|
||
const target = img.closest(".preview") || img;
|
||
if (document.fullscreenElement) {
|
||
document.exitFullscreen?.();
|
||
} else if (target.requestFullscreen) {
|
||
target.requestFullscreen().catch(() => {
|
||
// fallback:在新标签打开
|
||
window.open(img.src, "_blank", "noopener");
|
||
});
|
||
} else {
|
||
window.open(img.src, "_blank", "noopener");
|
||
}
|
||
});
|
||
}
|
||
|
||
function applyKbdHints() {
|
||
// 给 [data-kbd-mod="1"] 的按钮自动注入平台对应的修饰键前缀
|
||
const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || "");
|
||
const prefix = isMac ? "⌘ " : "Ctrl ";
|
||
document.querySelectorAll('[data-kbd-mod="1"]').forEach((el) => {
|
||
el.setAttribute("data-kbd-prefix", prefix);
|
||
});
|
||
}
|
||
|
||
function initStickySectionShadow() {
|
||
// 当 .sectionTitle 真正贴住 sticky top 时加 .isStuck 类
|
||
const titles = Array.from(document.querySelectorAll(".sectionTitle"))
|
||
.filter((el) => !el.matches(".cardTitle, summary, summary *"));
|
||
if (!titles.length || !("IntersectionObserver" in window)) return;
|
||
const io = new IntersectionObserver(
|
||
(entries) => {
|
||
for (const e of entries) {
|
||
// intersectionRatio < 1 && top 已到达 sentinel:贴住状态
|
||
e.target.classList.toggle("isStuck", e.intersectionRatio < 1 && e.boundingClientRect.top <= 65);
|
||
}
|
||
},
|
||
{ threshold: [1], rootMargin: "-65px 0px 0px 0px" }
|
||
);
|
||
titles.forEach((t) => io.observe(t));
|
||
}
|
||
|
||
function initShortcutsHelp() {
|
||
const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || "");
|
||
const mod = isMac ? "⌘" : "Ctrl";
|
||
let overlay = null;
|
||
const ITEMS = [
|
||
{ keys: [mod, "K"], desc: "聚焦配置搜索" },
|
||
{ keys: [mod, "S"], desc: "保存配置" },
|
||
{ keys: [mod, "Enter"], desc: "开始运行" },
|
||
{ keys: ["Esc"], desc: "清空搜索 / 关闭弹层" },
|
||
{ keys: ["?"], desc: "显示此帮助" },
|
||
];
|
||
const open = () => {
|
||
if (overlay) return;
|
||
overlay = document.createElement("div");
|
||
overlay.className = "shortcutsOverlay";
|
||
overlay.innerHTML = `
|
||
<div class="shortcutsCard" role="dialog" aria-label="快捷键帮助">
|
||
<div class="shortcutsHeader">
|
||
<span class="shortcutsTitle">键盘快捷键</span>
|
||
<button class="shortcutsClose" type="button" aria-label="关闭">
|
||
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
|
||
</button>
|
||
</div>
|
||
<div class="shortcutsList">
|
||
${ITEMS.map(i => `<div class="shortcutsRow"><span class="shortcutsDesc">${i.desc}</span><span class="shortcutsKeys">${i.keys.map(k => `<kbd>${k}</kbd>`).join("<span class=\"shortcutsPlus\">+</span>")}</span></div>`).join("")}
|
||
</div>
|
||
</div>
|
||
`;
|
||
document.body.appendChild(overlay);
|
||
requestAnimationFrame(() => overlay.classList.add("isVisible"));
|
||
overlay.addEventListener("click", (e) => {
|
||
if (e.target === overlay || e.target.closest(".shortcutsClose")) close();
|
||
});
|
||
};
|
||
const close = () => {
|
||
if (!overlay) return;
|
||
overlay.classList.remove("isVisible");
|
||
const ref = overlay;
|
||
setTimeout(() => { try { ref.remove(); } catch (_) {} }, 160);
|
||
overlay = null;
|
||
};
|
||
document.addEventListener("keydown", (e) => {
|
||
// 输入框聚焦时不拦截 ? 字符
|
||
const inField = /^(INPUT|TEXTAREA|SELECT)$/i.test(document.activeElement?.tagName || "");
|
||
if (e.key === "?" && !inField && !e.metaKey && !e.ctrlKey) {
|
||
e.preventDefault();
|
||
overlay ? close() : open();
|
||
return;
|
||
}
|
||
if (e.key === "Escape" && overlay) {
|
||
e.preventDefault();
|
||
close();
|
||
}
|
||
});
|
||
}
|
||
|
||
function updateTabBadge(target, count) {
|
||
const btn = document.querySelector(`.tabBtn[data-target="${target}"]`);
|
||
if (!btn) return;
|
||
const n = Math.max(0, Number(count) || 0);
|
||
if (n > 0) btn.setAttribute("data-badge", n > 99 ? "99+" : String(n));
|
||
else btn.removeAttribute("data-badge");
|
||
}
|
||
|
||
function startReservationsCountdownTick() {
|
||
if (window.__reservationTickTimer) {
|
||
clearInterval(window.__reservationTickTimer);
|
||
window.__reservationTickTimer = null;
|
||
}
|
||
// 每秒 tick 更新预约卡倒计时与高亮类,无需等待 stats 轮询
|
||
window.__reservationTickTimer = setInterval(() => {
|
||
const items = document.querySelectorAll(".reservationItem[data-future-ts]");
|
||
if (!items.length) return;
|
||
const now = Date.now() / 1000;
|
||
items.forEach((card) => {
|
||
const fut = Number(card.dataset.futureTs) || 0;
|
||
if (!fut) return;
|
||
const remain = Math.max(0, Math.floor(fut - now));
|
||
const remainEl = card.querySelector(".reservationRemain");
|
||
if (remainEl) {
|
||
remainEl.textContent = remain > 0
|
||
? `${Math.floor(remain / 60)}分${remain % 60}秒后`
|
||
: "已到开奖时间";
|
||
}
|
||
card.classList.toggle("isImminent", remain > 0 && remain <= 60);
|
||
card.classList.toggle("isDue", remain === 0);
|
||
});
|
||
}, 1000);
|
||
}
|
||
|
||
function initTabs() {
|
||
const tabButtons = Array.from(document.querySelectorAll(".tabBtn[data-target]"));
|
||
const panels = Array.from(document.querySelectorAll(".panel[data-panel]"));
|
||
const sideNav = document.querySelector(".sideNav");
|
||
if (tabButtons.length === 0 || panels.length === 0) return;
|
||
|
||
const updateIndicator = (btn) => {
|
||
if (!sideNav || !btn || sideNav.offsetParent === null) return;
|
||
// 横向布局(移动端 row)下不绘制竖条
|
||
const isRow = getComputedStyle(sideNav).flexDirection !== "column";
|
||
if (isRow) {
|
||
sideNav.style.setProperty("--tab-indicator-opacity", "0");
|
||
return;
|
||
}
|
||
const navRect = sideNav.getBoundingClientRect();
|
||
const btnRect = btn.getBoundingClientRect();
|
||
const top = (btnRect.top - navRect.top) + (btnRect.height - 16) / 2;
|
||
sideNav.style.setProperty("--tab-indicator-y", `${top}px`);
|
||
sideNav.style.setProperty("--tab-indicator-h", `16px`);
|
||
sideNav.style.setProperty("--tab-indicator-opacity", "1");
|
||
};
|
||
|
||
const setActive = (target) => {
|
||
let activeBtn = null;
|
||
for (const btn of tabButtons) {
|
||
const isActive = btn.dataset.target === target;
|
||
btn.classList.toggle("active", isActive);
|
||
btn.setAttribute("aria-selected", isActive ? "true" : "false");
|
||
if (isActive) activeBtn = btn;
|
||
}
|
||
for (const panel of panels) {
|
||
const isActive = panel.dataset.panel === target;
|
||
panel.toggleAttribute("hidden", !isActive);
|
||
panel.classList.toggle("active", isActive);
|
||
}
|
||
document.body.dataset.activePanel = target || "";
|
||
updateIndicator(activeBtn);
|
||
};
|
||
|
||
for (const btn of tabButtons) {
|
||
btn.addEventListener("click", () => {
|
||
const wasActive = btn.classList.contains("active");
|
||
setActive(btn.dataset.target);
|
||
// Trigger burst pulse on the indicator only when actually switching
|
||
if (!wasActive && sideNav) {
|
||
sideNav.classList.remove("isBurst");
|
||
void sideNav.offsetWidth;
|
||
sideNav.classList.add("isBurst");
|
||
setTimeout(() => sideNav.classList.remove("isBurst"), 380);
|
||
}
|
||
});
|
||
}
|
||
|
||
const defaultTarget = tabButtons.find(b => b.classList.contains("active"))?.dataset.target || tabButtons[0].dataset.target;
|
||
setActive(defaultTarget);
|
||
|
||
// 窗口尺寸变化或字体加载完成时重新计算位置
|
||
let resizeTimer;
|
||
window.addEventListener("resize", () => {
|
||
clearTimeout(resizeTimer);
|
||
resizeTimer = setTimeout(() => {
|
||
const cur = document.querySelector(".tabBtn.active[data-target]");
|
||
if (cur) updateIndicator(cur);
|
||
}, 80);
|
||
});
|
||
if (document.fonts && document.fonts.ready) {
|
||
document.fonts.ready.then(() => {
|
||
const cur = document.querySelector(".tabBtn.active[data-target]");
|
||
if (cur) updateIndicator(cur);
|
||
});
|
||
}
|
||
}
|
||
|
||
function attachNumberSteppers() {
|
||
// 给所有 .input[type=number] 包裹 .numStepperWrap + 添加 +/- 按钮
|
||
const SVG_UP = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 15 12 9 18 15"/></svg>';
|
||
const SVG_DOWN = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>';
|
||
document.querySelectorAll('input.input[type="number"]').forEach((input) => {
|
||
if (input.dataset.stepperBound === "1") return;
|
||
if (input.closest(".inline2")) return; // inline2 内不加,避免连体边框冲突
|
||
input.dataset.stepperBound = "1";
|
||
const wrap = document.createElement("div");
|
||
wrap.className = "numStepperWrap";
|
||
input.parentNode.insertBefore(wrap, input);
|
||
wrap.appendChild(input);
|
||
const btns = document.createElement("span");
|
||
btns.className = "numStepperBtns";
|
||
const up = document.createElement("button");
|
||
up.type = "button";
|
||
up.tabIndex = -1;
|
||
up.className = "numStepperBtn";
|
||
up.setAttribute("aria-label", "增加");
|
||
up.innerHTML = SVG_UP;
|
||
const down = document.createElement("button");
|
||
down.type = "button";
|
||
down.tabIndex = -1;
|
||
down.className = "numStepperBtn";
|
||
down.setAttribute("aria-label", "减少");
|
||
down.innerHTML = SVG_DOWN;
|
||
btns.append(up, down);
|
||
wrap.appendChild(btns);
|
||
const fire = (dir) => {
|
||
try { dir > 0 ? input.stepUp() : input.stepDown(); } catch (_) {}
|
||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||
input.dispatchEvent(new Event("change", { bubbles: true }));
|
||
};
|
||
const bindHold = (btn, dir) => {
|
||
let holdTimer, repeatTimer;
|
||
const cancel = () => {
|
||
if (holdTimer) { clearTimeout(holdTimer); holdTimer = null; }
|
||
if (repeatTimer) { clearInterval(repeatTimer); repeatTimer = null; }
|
||
};
|
||
btn.addEventListener("pointerdown", (e) => {
|
||
if (e.button !== 0) return;
|
||
e.preventDefault();
|
||
fire(dir);
|
||
holdTimer = setTimeout(() => {
|
||
repeatTimer = setInterval(() => fire(dir), 80);
|
||
}, 500);
|
||
});
|
||
btn.addEventListener("pointerup", cancel);
|
||
btn.addEventListener("pointerleave", cancel);
|
||
btn.addEventListener("pointercancel", cancel);
|
||
btn.addEventListener("blur", cancel);
|
||
};
|
||
bindHold(up, 1);
|
||
bindHold(down, -1);
|
||
});
|
||
}
|
||
|
||
function pollShot() {
|
||
const img = $("liveShot");
|
||
if (!img) return;
|
||
const preview = img.closest(".preview");
|
||
|
||
// 性能优化:避免重复加载相同的图片(如果正在加载中)
|
||
if (img.dataset.loading === "true") return;
|
||
|
||
const url = `/pic/screenshot.png?t=${Date.now()}`;
|
||
img.dataset.loading = "true";
|
||
if (preview) preview.classList.remove(UI_CLASS.shotEmpty);
|
||
img.src = url;
|
||
|
||
const status = $("liveShotStatus");
|
||
if (status) status.textContent = `刷新中:${new Date().toLocaleTimeString()}`;
|
||
}
|
||
|
||
function startShotPolling() {
|
||
if (shotTimer) clearInterval(shotTimer);
|
||
|
||
const img = $("liveShot");
|
||
const status = $("liveShotStatus");
|
||
if (img) {
|
||
const preview = img.closest(".preview");
|
||
const syncShotEmpty = () => {
|
||
if (!preview) return;
|
||
preview.classList.toggle(UI_CLASS.shotEmpty, img.complete && img.naturalWidth === 0);
|
||
};
|
||
syncShotEmpty();
|
||
if (!img.dataset.boundLoadHandler) {
|
||
img.dataset.boundLoadHandler = "1";
|
||
img.addEventListener("load", () => {
|
||
img.dataset.loading = "false";
|
||
if (preview) preview.classList.remove(UI_CLASS.shotEmpty);
|
||
const ts = new Date().toLocaleTimeString();
|
||
if (status) status.textContent = `已更新:${ts}`;
|
||
const tsBadge = document.getElementById("liveShotTs");
|
||
if (tsBadge) {
|
||
tsBadge.textContent = ts;
|
||
tsBadge.hidden = false;
|
||
}
|
||
});
|
||
img.addEventListener("error", () => {
|
||
img.dataset.loading = "false";
|
||
if (preview) preview.classList.add(UI_CLASS.shotEmpty);
|
||
if (status) status.textContent = "暂无截图(等待脚本生成 pic/screenshot.png)";
|
||
});
|
||
}
|
||
setTimeout(syncShotEmpty, 0);
|
||
}
|
||
|
||
// 性能优化:截图轮询间隔从 900ms 调整为 1500ms,减少服务器压力
|
||
shotTimer = setInterval(pollShot, UI_LIMITS.screenshotPollMs);
|
||
}
|
||
|
||
function setButtonBusy(id, busy) {
|
||
const btn = $(id);
|
||
if (!btn) return;
|
||
btn.classList.toggle(UI_CLASS.busy, !!busy);
|
||
btn.toggleAttribute("aria-busy", !!busy);
|
||
if (BUSY_DISABLED_BUTTONS.has(id)) btn.disabled = !!busy;
|
||
}
|
||
|
||
function setRunOverview(state, meta, tone) {
|
||
setTextIfExists("topRunState", state || UI_COPY.empty);
|
||
setTextIfExists("topRunMeta", meta || UI_COPY.empty);
|
||
const dot = $("topRunDot");
|
||
if (!dot) return;
|
||
dot.classList.remove(UI_CLASS.statusRunning, UI_CLASS.statusIdle, UI_CLASS.statusError);
|
||
dot.classList.add(tone === RUN_TONE.running ? UI_CLASS.statusRunning : tone === RUN_TONE.error ? UI_CLASS.statusError : UI_CLASS.statusIdle);
|
||
}
|
||
|
||
function updateDeviceOverview() {
|
||
const devices = Array.isArray(deviceOverviewState.devices) ? deviceOverviewState.devices : [];
|
||
const selected = selectedDeviceId();
|
||
if (selected) {
|
||
setTextIfExists("topDeviceState", selected);
|
||
} else if (devices.length > 0) {
|
||
setTextIfExists("topDeviceState", UI_COPY.device.autoOnline(devices.length));
|
||
} else {
|
||
setTextIfExists("topDeviceState", UI_COPY.device.noOnline);
|
||
}
|
||
setTextIfExists("topAdbState", deviceOverviewState.adb ? UI_COPY.device.adbReady : UI_COPY.device.adbMissing);
|
||
}
|