2026-10-17 10:46:29 +08:00

201 lines
7.0 KiB
JavaScript

const form = document.querySelector("#run-form");
const instancesInput = document.querySelector("#instance-count");
const errorBox = document.querySelector("#form-error");
const runStatus = document.querySelector("#run-status");
const stopButton = document.querySelector("#stop-button");
const emptyState = document.querySelector("#empty-state");
const instanceGrid = document.querySelector("#instance-results");
const submitButton = form.querySelector("button[type=submit]");
let currentRunId = null;
let eventSource = null;
const imageModal = document.querySelector("#image-modal");
const modalImage = document.querySelector("#modal-image");
const modalCaption = document.querySelector("#modal-caption");
const interactionLayer = document.querySelector("#interaction-layer");
let controlSocket = null;
let activeInstance = null;
const VIEWPORT_WIDTH = 1365;
const VIEWPORT_HEIGHT = 860;
document.querySelectorAll("[data-step]").forEach((button) => {
button.addEventListener("click", () => {
const next = Math.max(1, Math.min(12, Number(instancesInput.value) + Number(button.dataset.step)));
instancesInput.value = next;
});
});
function setBusy(busy) {
submitButton.disabled = busy;
submitButton.querySelector("span").textContent = busy ? "运行中..." : "启动任务";
stopButton.disabled = !busy;
}
function closeLiveUpdates() {
if (eventSource) {
eventSource.close();
eventSource = null;
}
}
function connectLiveUpdates() {
closeLiveUpdates();
eventSource = new EventSource(`/api/runs/${currentRunId}/events`);
eventSource.onmessage = (event) => {
const run = JSON.parse(event.data);
renderRun(run);
if (!["运行中", "停止中"].includes(run.status)) closeLiveUpdates();
};
eventSource.onerror = () => {
if (eventSource?.readyState === EventSource.CLOSED) {
errorBox.textContent = "实时连接已断开,请刷新页面后重试";
setBusy(false);
}
};
}
function renderRun(run) {
runStatus.textContent = run.status;
errorBox.textContent = run.error || "";
const active = ["运行中", "停止中"].includes(run.status);
setBusy(active);
emptyState.hidden = true;
instanceGrid.hidden = false;
instanceGrid.replaceChildren();
run.instances.forEach((item) => {
const card = document.createElement("article");
card.className = "instance-card";
const top = document.createElement("div");
top.className = "instance-top";
const name = document.createElement("span");
name.className = "instance-name";
name.textContent = `INSTANCE ${String(item.id).padStart(2, "0")}`;
const status = document.createElement("span");
status.className = `instance-status ${item.status === "已完成" ? "done" : item.status === "失败" ? "failed" : ""}`;
status.textContent = item.status;
top.append(name, status);
card.append(top);
if (["打开页面", "识别文字", "实时监控", "已停止"].includes(item.status)) {
const image = document.createElement("img");
image.className = "thumb live-view zoomable";
image.src = `${item.stream}?v=${Date.now()}`;
image.alt = `实例 ${item.id} 实时画面`;
image.title = "点击放大实时画面";
image.addEventListener("click", () => {
activeInstance = item;
modalImage.src = `${item.stream}?view=large&v=${Date.now()}`;
modalCaption.textContent = `INSTANCE ${String(item.id).padStart(2, "0")} · 实时画面 · ${item.title || "加载中"}`;
imageModal.hidden = false;
document.body.classList.add("modal-open");
connectControlSocket(item.control);
interactionLayer.focus({ preventScroll: true });
});
card.append(image);
} else {
const placeholder = document.createElement("div");
placeholder.className = "thumb-placeholder";
placeholder.textContent = "正在连接实时画面";
card.append(placeholder);
}
const bottom = document.createElement("div");
bottom.className = "instance-bottom";
bottom.textContent = item.message || item.title || "正在准备...";
card.append(bottom);
instanceGrid.append(card);
});
}
form.addEventListener("submit", async (event) => {
event.preventDefault();
errorBox.textContent = "";
const data = {
url: document.querySelector("#url").value,
instances: Number(instancesInput.value),
action_text: document.querySelector("#action-text").value,
};
try {
setBusy(true);
const response = await fetch("/api/runs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
const payload = await response.json();
if (!response.ok) throw new Error(payload.detail?.[0]?.msg || payload.detail || "任务创建失败");
currentRunId = payload.id;
renderRun(payload);
connectLiveUpdates();
} catch (error) {
errorBox.textContent = error.message;
setBusy(false);
}
});
stopButton.addEventListener("click", async () => {
if (!currentRunId) return;
await fetch(`/api/runs/${currentRunId}/stop`, { method: "POST" });
});
function closeImageModal() {
closeControlSocket();
imageModal.hidden = true;
modalImage.removeAttribute("src");
document.body.classList.remove("modal-open");
}
function connectControlSocket(path) {
closeControlSocket();
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
controlSocket = new WebSocket(`${protocol}//${window.location.host}${path}`);
}
function closeControlSocket() {
if (controlSocket) {
controlSocket.close();
controlSocket = null;
}
}
function sendControl(event) {
if (controlSocket?.readyState === WebSocket.OPEN) {
controlSocket.send(JSON.stringify(event));
}
}
interactionLayer.addEventListener("click", (event) => {
const rect = interactionLayer.getBoundingClientRect();
const x = ((event.clientX - rect.left) / rect.width) * VIEWPORT_WIDTH;
const y = ((event.clientY - rect.top) / rect.height) * VIEWPORT_HEIGHT;
sendControl({ type: "click", x, y, clickCount: event.detail || 1 });
});
interactionLayer.addEventListener("wheel", (event) => {
event.preventDefault();
sendControl({ type: "wheel", deltaX: event.deltaX, deltaY: event.deltaY });
}, { passive: false });
interactionLayer.addEventListener("keydown", (event) => {
if (["Control", "Meta", "Alt", "Shift"].includes(event.key)) return;
event.preventDefault();
const modifiers = [];
if (event.ctrlKey) modifiers.push("Control");
if (event.metaKey) modifiers.push("Meta");
if (event.altKey) modifiers.push("Alt");
if (event.shiftKey) modifiers.push("Shift");
sendControl({ type: "key", key: event.key, modifiers });
});
interactionLayer.addEventListener("paste", (event) => {
const text = event.clipboardData?.getData("text") || "";
if (text) {
event.preventDefault();
sendControl({ type: "text", value: text });
}
});
document.querySelector("#close-modal").addEventListener("click", closeImageModal);
imageModal.addEventListener("click", (event) => {
if (event.target === imageModal) closeImageModal();
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape" && !imageModal.hidden) closeImageModal();
});