diff --git a/webui/app.js b/webui/app.js index 9d2e2e3..f083d0f 100644 --- a/webui/app.js +++ b/webui/app.js @@ -256,6 +256,154 @@ function initTheme() { } } +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); + + 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; + // 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; + }; + + let debounceTimer; + input.addEventListener("input", () => { + clearTimeout(debounceTimer); + debounceTimer = setTimeout(() => apply(input.value), 80); + }); + + if (clear) { + clear.addEventListener("click", () => { + input.value = ""; + apply(""); + input.focus(); + }); + } +} + function initTabs() { const tabButtons = Array.from(document.querySelectorAll(".tabBtn[data-target]")); const panels = Array.from(document.querySelectorAll(".panel[data-panel]")); @@ -283,43 +431,74 @@ function initTabs() { setActive(defaultTarget); } +function classifyLogLine(line) { + const s = String(line || ""); + if (!s) return ""; + // 错误优先 + if (/\b(ERROR|FATAL|CRITICAL|TRACEBACK|EXCEPTION|FAILED|FAIL\b)\b/i.test(s)) return "logError"; + if (/(失败|错误|异常|未知错误|超时|崩溃)/.test(s)) return "logError"; + if (/❌/.test(s)) return "logError"; + // 警告 + if (/\b(WARN(ING)?)\b/i.test(s)) return "logWarn"; + if (/(警告|注意)/.test(s)) return "logWarn"; + if (/⚠️/.test(s)) return "logWarn"; + // 成功 + if (/\b(SUCCESS|OK|DONE|COMPLETED?)\b/i.test(s)) return "logSuccess"; + if (/(成功|已保存|完成|启动成功)/.test(s)) return "logSuccess"; + if (/(✅|✓)/.test(s)) return "logSuccess"; + // Debug + if (/\b(DEBUG|TRACE)\b/i.test(s)) return "logDebug"; + // INFO 默认 + if (/\b(INFO)\b/i.test(s)) return "logInfo"; + return ""; +} + +function renderLogLineNode(line) { + const cls = classifyLogLine(line); + if (!cls) { + // 普通行:直接文本节点(性能最佳) + return document.createTextNode(String(line ?? "") + "\n"); + } + const span = document.createElement("span"); + span.className = "logLine " + cls; + span.textContent = String(line ?? "") + "\n"; + return span; +} + function appendLog(lines) { const log = $("runLog"); if (!lines || lines.length === 0) return; - + // 记录更新前与底部的距离,用于在非底部时保持视图位置 const distanceFromBottom = log.scrollHeight - log.scrollTop - log.clientHeight; // 是否严格位于底部(仅在几像素内视为底部),避免每次刷新都跳到底部 const wasAtBottom = distanceFromBottom < UI_LIMITS.scrollBottomThresholdPx; - // 性能优化:批量追加文本,减少重排次数 - const newText = lines.join("\n") + "\n"; // 直接追加到 DOM,同时维护 runLogBuffer 以便支持搜索 - const toAppend = lines; - for (const ln of toAppend) runLogBuffer.push(ln); + for (const ln of lines) runLogBuffer.push(ln); // 限制缓冲 if (runLogBuffer.length > runLogMaxLines) runLogBuffer = runLogBuffer.slice(-runLogMaxLines); // 如果当前处于 run search 结果显示状态,则不改变显示(保持搜索结果不被实时追加打断) if (runSearchActive && runLogMode === 'search') { // 仍保持缓冲更新,但不修改 DOM + } else if (runLogFilter) { + // 有过滤器时重渲染整个视图 + renderRunLog(); } else { - // 如果没有过滤器,直接将文本拼接(性能优先) - if (!runLogFilter) { - log.textContent += newText; - } else { - // 有过滤器时重渲染整个视图 - renderRunLog(); - } + // 批量追加:用 fragment + 行级 span 着色 + const frag = document.createDocumentFragment(); + for (const ln of lines) frag.appendChild(renderLogLineNode(ln)); + log.appendChild(frag); } - + // 性能优化:限制日志长度,避免内存溢出(保留最近较多字符以便桌面端查看) const maxLength = UI_LIMITS.runLogMaxChars; if (log.textContent.length > maxLength) { - // 在截断文本时,保留用户原来的距离(除非用户确实在底部) - log.textContent = log.textContent.slice(-maxLength); + // 直接基于缓冲重渲染(截断到最新行) + runLogBuffer = runLogBuffer.slice(-Math.ceil(runLogMaxLines * 0.6)); + renderRunLog(); if (!wasAtBottom) { - // 调整 scrollTop 保持原先距离 const newScrollTop = log.scrollHeight - log.clientHeight - distanceFromBottom; log.scrollTop = Math.max(0, newScrollTop); } @@ -334,12 +513,21 @@ function appendLog(lines) { function renderRunLog() { const el = $("runLog"); if (!el) return; + const renderInto = (lines) => { + el.textContent = ""; + if (!lines.length) return; + const frag = document.createDocumentFragment(); + for (const ln of lines) frag.appendChild(renderLogLineNode(ln)); + el.appendChild(frag); + }; + // 如果处于搜索结果显示状态,优先显示 search 返回的结果 if (runSearchActive && runLogMode === 'search') { const lines = runSearchResultsBuffer || []; const prevScrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight; - el.textContent = lines.join("\n") + (lines.length ? "\n" : ""); - if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); + renderInto(lines); + if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; + else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); return; } @@ -349,9 +537,9 @@ function renderRunLog() { lines = runLogBuffer.filter(l => String(l || "").toLowerCase().includes(filter)); } const prevScrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight; - el.textContent = lines.join("\n") + (lines.length ? "\n" : ""); - // 尽量保持原来滚动位置;若位于底部则滚到底部 - if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); + renderInto(lines); + if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; + else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); } function appendRunLogLines(lines) { @@ -902,8 +1090,9 @@ async function loadConfig() { try { const cfg = await apiGet("/api/config"); applyConfigToUI(cfg); - appendLog(["[WEB] 配置已加载"]); + toast("配置已加载", "success"); } catch (e) { + toast("配置加载失败:" + e.message, "error", { duration: 5000 }); appendLog(["[WEB] 配置加载失败: " + e.message]); } } @@ -913,7 +1102,10 @@ async function saveConfig() { try { const cfgUpdate = collectConfigFromUI(); await apiPost("/api/config", cfgUpdate); - appendLog(["[WEB] 配置已保存到 config.json"]); + toast("配置已保存", "success"); + } catch (e) { + toast("保存失败:" + (e?.message || e), "error", { duration: 5000 }); + throw e; } finally { setButtonBusy("btnSave", false); } @@ -929,10 +1121,13 @@ async function postDeviceAction(path, body, successPrefix) { const result = await apiPost(path, body || {}); const msg = result.message || result.output || result.error || "完成"; appendLog([`${successPrefix}: ${msg}`]); + if (!result.error) toast(`${successPrefix}: ${msg}`, "success"); + else toast(`${successPrefix}: ${msg}`, "warn"); if (result.devices) await refreshDevices(); return result; } catch (e) { appendLog([`${successPrefix}失败: ${e?.message || e}`]); + toast(`${successPrefix}失败:${e?.message || e}`, "error", { duration: 5000 }); throw e; } } @@ -1029,13 +1224,15 @@ async function startRun() { if (result && result.ok === false) { const errorMsg = result.error || "未知错误"; appendLog([`[WEB] 启动失败: ${errorMsg}`]); + toast("启动失败:" + (errorMsg === "running" ? "已有进程在运行" : errorMsg), "error", { duration: 5000 }); if (errorMsg === "running") { appendLog([`[WEB] 提示:已有进程在运行中,请先点击"停止"按钮`]); } return; } - + appendLog([`[WEB] 已开始运行:device=${deviceId || UI_COPY.device.autoLabel}`]); + toast(`已开始运行 · ${deviceId || "自动"}`, "success"); // 启动时自动截图 if (deviceId) { @@ -1071,6 +1268,7 @@ async function startRun() { console.error("[WEB] startRun error:", e); const errorMsg = e.message || String(e); appendLog([`[WEB] 启动失败: ${errorMsg}`]); + toast("启动失败:" + errorMsg, "error", { duration: 5000 }); setRunOverview(UI_COPY.runOverview.failed, errorMsg, RUN_TONE.error); // 如果是"running"错误,显示友好提示 if (errorMsg === "running" || (e.status === 409)) { @@ -1392,6 +1590,8 @@ async function pollHighValueRooms() { async function pollStats() { try { const s = await apiGet(`/api/stats?t=${Date.now()}`); + // 数据到位,去掉骨架 + document.querySelectorAll(".stat .statValue.skeleton, .stat .statHint.skeleton").forEach((el) => el.classList.remove("skeleton")); const running = s.running ? "运行中" : "未运行"; setTextIfExists("statRunning", running); setTextIfExists("statPid", s.pid ?? "-"); @@ -1532,6 +1732,11 @@ function startStatsPolling() { window.addEventListener("DOMContentLoaded", async () => { initTheme(); initTabs(); + initConfigSearch(); + // 首屏统计数字加骨架,待第一次 pollStats 成功后移除 + document.querySelectorAll(".stat .statValue").forEach((el) => { + if ((el.textContent || "").trim() === "-") el.classList.add("skeleton"); + }); $("btnRefresh").addEventListener("click", refreshDevices); $("btnLoad").addEventListener("click", async () => { await loadConfig(); }); $("btnSave").addEventListener("click", async () => { await saveConfig(); }); diff --git a/webui/index.html b/webui/index.html index 3b9a4db..7a9e24a 100644 --- a/webui/index.html +++ b/webui/index.html @@ -15,7 +15,7 @@ } catch (e) {} })(); - +
@@ -186,8 +186,17 @@
Configuration

运行策略工作区

-
配置项按当前标签自然铺排,短页不再继承长页高度。
+
+ + + +
+
@@ -1222,6 +1231,6 @@
- + diff --git a/webui/styles.css b/webui/styles.css index abbb39f..5b964e2 100644 --- a/webui/styles.css +++ b/webui/styles.css @@ -798,6 +798,89 @@ svg { text-align: right; } +.workspaceSearch { + position: relative; + display: flex; + align-items: center; + width: clamp(220px, 32vw, 360px); +} + +.workspaceSearch input { + width: 100%; + min-height: 32px; + padding: 0 30px 0 30px; + border: 1px solid var(--border-strong); + border-radius: var(--radius-md); + color: var(--text); + background: var(--surface-soft); + font-size: var(--text-sm); + outline: none; + transition: border-color var(--motion-fast), box-shadow var(--motion-fast), background var(--motion-fast); +} + +.workspaceSearch input::-webkit-search-cancel-button { + display: none; +} + +.workspaceSearch input:hover { + border-color: var(--hover-border); +} + +.workspaceSearch input:focus-visible { + border-color: var(--primary); + background: var(--surface); + box-shadow: 0 0 0 1px var(--primary), var(--focus-ring); +} + +.workspaceSearchIcon { + position: absolute; + left: 9px; + top: 50%; + width: 14px; + height: 14px; + margin-top: -7px; + color: var(--muted-soft); + pointer-events: none; +} + +.workspaceSearchClear { + position: absolute; + right: 6px; + top: 50%; + display: inline-flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + margin-top: -10px; + padding: 0; + border: 0; + border-radius: var(--radius-sm); + color: var(--muted-soft); + background: transparent; + cursor: pointer; + transition: color var(--motion-fast), background var(--motion-fast); +} + +.workspaceSearchClear:hover { + color: var(--text); + background: var(--surface-muted); +} + +.row.isSearchHidden, +.sectionTitle.isSearchHidden { + display: none !important; +} + +.configSearchEmpty { + margin: 12px 0; + padding: 24px; + border: 1px dashed var(--border); + border-radius: var(--radius-md); + text-align: center; + color: var(--muted); +} + .sideNav { position: static; display: flex; @@ -1742,6 +1825,71 @@ details[open] > summary.sectionTitle::before { background: color-mix(in oklab, var(--primary) 25%, transparent); } +/* Log line classification colors */ +.logLine { + display: inline; +} + +.logError { + color: var(--danger); +} + +.logWarn { + color: var(--warning); +} + +.logSuccess { + color: var(--success); +} + +.logInfo { + color: var(--text); +} + +.logDebug { + color: var(--muted-soft); +} + +/* ==================== Skeleton placeholders ==================== */ +@keyframes skeletonShimmer { + 0% { background-position: -200% 0; } + 100% { background-position: 200% 0; } +} + +.skeleton { + position: relative; + overflow: hidden; + background: + linear-gradient(90deg, + transparent 0, + color-mix(in oklab, var(--text) 6%, transparent) 50%, + transparent 100%) var(--surface-muted); + background-size: 200% 100%; + background-repeat: no-repeat; + animation: skeletonShimmer 1.6s linear infinite; + border-radius: var(--radius-sm); + color: transparent !important; + user-select: none; + pointer-events: none; +} + +.skeleton * { + visibility: hidden; +} + +.skeletonText { + display: inline-block; + width: var(--skeleton-w, 60%); + height: 0.85em; + vertical-align: middle; +} + +@media (prefers-reduced-motion: reduce) { + .skeleton { + animation: none; + } +} + /* Global thin scrollbars */ * { scrollbar-width: thin; @@ -1769,6 +1917,143 @@ details[open] > summary.sectionTitle::before { background-clip: padding-box; } +/* ==================== Toast ==================== */ +.toastContainer { + position: fixed; + right: 20px; + bottom: 20px; + z-index: 100; + display: flex; + flex-direction: column; + gap: 8px; + max-width: min(420px, calc(100vw - 40px)); + pointer-events: none; +} + +.toast { + display: grid; + grid-template-columns: 18px 1fr auto; + align-items: start; + gap: 10px; + padding: 12px 12px 12px 14px; + border: 1px solid var(--border); + border-radius: var(--radius-md); + background: var(--surface); + color: var(--text); + font-size: var(--text-sm); + line-height: var(--leading-snug); + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12), 0 2px 6px rgba(0, 0, 0, 0.08); + pointer-events: auto; + animation: toastIn 200ms cubic-bezier(0.2, 0.7, 0.2, 1); + position: relative; + overflow: hidden; +} + +:root[data-theme="dark"] .toast { + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5), 0 2px 6px rgba(0, 0, 0, 0.4); +} + +.toast::before { + position: absolute; + left: 0; + top: 0; + bottom: 0; + width: 3px; + content: ""; + background: var(--muted-soft); +} + +.toast-success { + border-color: color-mix(in oklab, var(--success) 30%, var(--border)); +} +.toast-success::before { background: var(--success); } +.toast-success .toastIcon { color: var(--success); } + +.toast-error { + border-color: color-mix(in oklab, var(--danger) 30%, var(--border)); +} +.toast-error::before { background: var(--danger); } +.toast-error .toastIcon { color: var(--danger); } + +.toast-warn { + border-color: color-mix(in oklab, var(--warning) 30%, var(--border)); +} +.toast-warn::before { background: var(--warning); } +.toast-warn .toastIcon { color: var(--warning); } + +.toast-info::before { background: var(--primary); } +.toast-info .toastIcon { color: var(--primary); } + +.toastIcon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 18px; + height: 18px; + margin-top: 1px; +} + +.toastIcon svg { + width: 18px; + height: 18px; +} + +.toastBody { + min-width: 0; + color: var(--text); + overflow-wrap: anywhere; +} + +.toastClose { + display: inline-flex; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + margin: -2px -2px 0 4px; + padding: 0; + border: 0; + border-radius: var(--radius-sm); + color: var(--muted-soft); + background: transparent; + cursor: pointer; + transition: background var(--motion-fast), color var(--motion-fast); +} + +.toastClose:hover { + color: var(--text); + background: var(--surface-muted); +} + +.toast.isLeaving { + animation: toastOut 220ms ease forwards; +} + +@keyframes toastIn { + from { opacity: 0; transform: translateY(8px); } + to { opacity: 1; transform: translateY(0); } +} + +@keyframes toastOut { + to { opacity: 0; transform: translateY(-4px); } +} + +@media (prefers-reduced-motion: reduce) { + .toast, + .toast.isLeaving { + animation: none; + } +} + +@media (max-width: 640px) { + .toastContainer { + right: 12px; + bottom: 12px; + left: 12px; + max-width: none; + } +} + @media (max-width: 900px) { :root { --page-pad: 14px; @@ -1793,6 +2078,24 @@ details[open] > summary.sectionTitle::before { justify-content: flex-start; } + .secondaryActions::before { + display: none; + } + + #btnTheme { + margin-left: auto; + } + + .workspaceHeader { + align-items: stretch; + flex-direction: column; + gap: var(--space-3); + } + + .workspaceSearch { + width: 100%; + } + .overview { grid-template-columns: repeat(2, minmax(0, 1fr)); } @@ -1929,6 +2232,21 @@ details[open] > summary.sectionTitle::before { grid-template-columns: 1fr; } + .inline2 > .input, + .inline2 > input { + border-radius: var(--radius-md); + margin-left: 0; + } + + .workspaceHeader { + align-items: stretch; + flex-direction: column; + } + + .workspaceSearch { + width: 100%; + } + .statsGrid { grid-template-columns: repeat(2, minmax(0, 1fr)); }