diff --git a/webui/app.js b/webui/app.js index 96afe60..6c04ce7 100644 --- a/webui/app.js +++ b/webui/app.js @@ -21,703 +21,6 @@ let actionsLogFilter = ""; const actionsLogMaxLines = UI_LIMITS.actionsLogMaxLines; let deviceOverviewState = { devices: [], adb: "" }; -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: '', - error: '', - warn: '', - info: '', - }; - 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 = ''; - 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 = ''; - 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 = ` -