精修 WebUI 第五轮:交互能力与功能性升级
- 新增 Toast 通知系统:右下角浮出(移动端横铺底部),4 类(success/error/warn/info)+ 关闭按钮 + 自动消失 + hover 暂停消失 - 关键操作接入 Toast:保存配置 / 加载配置 / 启动失败 / 设备操作(连接/断开/WiFi 启用)成功失败提示 - 日志关键词分类着色:行级 span,自动识别 ERROR/WARN/SUCCESS/DEBUG/INFO(含中英文与 emoji 标记);DocumentFragment 批量渲染保持性能 - 配置面板加跨标签搜索:workspaceHeader 内嵌搜索框,输入即时按 label/hint/key 过滤所有 row 与 sectionTitle,搜索时自动展开所有 panel;空结果显示空状态;带清空按钮 - 首屏统计骨架屏:未到数据前 statValue 显示 shimmer 占位;pollStats 成功后自动移除 - 移动端复查:inline2 在小屏取消连体边框;workspaceHeader 改纵向布局,搜索框占满宽;secondaryActions 分隔线隐藏;btnTheme 推到右侧 - cache-bust v7 → v8
This commit is contained in:
1 parent
aa5065590a
commit
96cba09c49
3 files changed
+559
-27
No files matched your search
+229
-24
@@ -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: '<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);
|
||||
|
||||
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(); });
|
||||
|
||||
Reference in new issue
Block a user