Files
airdef/tools/web_remote/static/app.js
T

958 lines
39 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {createMap} from "./map.js";
import {applyLiveUpdate} from "./live.js";
import {createTimeline} from "./timeline.js";
const $ = id => document.getElementById(id);
const make = (tag, text, cls) => {
const element = document.createElement(tag);
if (text !== undefined) element.textContent = text;
if (cls) element.className = cls;
return element;
};
const paragraph = text => make("p", text, "detail-row");
const button = (text, action) => {
const node = make("button", text);
node.type = "button";
node.addEventListener("click", action);
return node;
};
const read = (key, fallback) => {
try { return JSON.parse(localStorage.getItem(`airdef-${key}`)) ?? fallback; }
catch { return fallback; }
};
const write = (key, value) => {
try { localStorage.setItem(`airdef-${key}`, JSON.stringify(value)); } catch {}
};
const archive = new Promise(resolve => {
if (!("indexedDB" in window)) return resolve(null);
const request = indexedDB.open("airdef-panel", 1);
request.onupgradeneeded = () => request.result.createObjectStore("content");
request.onsuccess = () => resolve(request.result);
request.onerror = () => resolve(null);
request.onblocked = () => resolve(null);
});
async function cache(key, value) {
try {
const db = await archive;
if (!db) return;
const tx = db.transaction("content", value === undefined ? "readonly" : "readwrite");
const items = tx.objectStore("content");
const op = value === undefined ? items.get(key) : value === null ? items.clear() : items.put(value, key);
return await new Promise(resolve => {
op.onsuccess = () => resolve(op.result);
op.onerror = () => resolve(undefined);
});
} catch { return undefined; }
}
class APIError extends Error {
constructor(status, text) {
super(text);
this.status = status;
}
}
async function api(path, {method = "GET", data} = {}) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 6000);
try {
const response = await fetch(`/api${path}`, {
method, signal: controller.signal, cache: "no-store",
headers: data ? {"Content-Type": "application/json"} : {},
body: data ? JSON.stringify(data) : undefined,
});
if (response.status === 204) return null;
const body = await response.json();
if (!response.ok) throw new APIError(response.status, body.error || "Запрос отклонён");
return body;
} finally {
clearTimeout(timeout);
}
}
const groups = [["units", "unit"], ["objects", "object"], ["contacts", "contact"], ["interceptors", "interceptor"]];
const prefs = read("view", {layers: {}, views: {}, selected: null});
prefs.layers ||= {};
prefs.views ||= {};
const LIVE_POLL_MS = 650;
let mapMode = prefs.mapMode === "radar" ? "radar" : "map";
let radarOptions = "";
let auth = null, network = null, live = null, historical = null, tab = "live", perspective = "network";
let selected = prefs.selected, connected = false, http = false, polling = false, catalog = null;
let events = [], raids = [], raid = null, more = false, historyGeneration = 0, frameGeneration = 0, chainGeneration = 0;
let eventTimer, frameTimer, receiptTimer, latestRequest = read("launch-request", null), installPrompt;
let offlineEvents = [], offlineFrames = {}, offlineRaids = {raids: []};
let offlineTimelines = {}, selectedEvent = null, timelineGeneration = 0;
const timelineRequests = new Map();
const timeline = createTimeline($("timeline-markers"), openEvent, time);
const viewKey = () => mapMode === "radar" ? `radar:${perspective}` : perspective;
const eventFields = {unit: "unit", contact: "target", object: "object"};
const eventOrder = {observations: 0, decisions: 1, events: 2};
let latestObject = {key: "", checked: 0, event: null};
const map = createMap($("map"), {
onSelect: key => select(key),
onTerrain: message => {
if ($("map-source").textContent !== message) $("map-source").textContent = message;
},
onView: view => {
if (historical) return;
prefs.views[viewKey()] = view;
write("view", prefs);
},
});
map.restore(prefs.views[viewKey()]);
function time(ticks) {
const tenths = Math.floor(Math.max(0, ticks) / 2);
return `${Math.floor(tenths / 600)}:${((tenths % 600) / 10).toFixed(1).padStart(4, "0")}`;
}
function when(value) {
return value ? new Date(value * 1000).toLocaleTimeString("ru-RU") : "—";
}
function fullname(row) { return row.label || `№${row.id}`; }
function showAuth() {
$("pairing").hidden = !!auth;
$("dashboard").hidden = !auth;
$("logout").hidden = !auth;
$("logout").disabled = !http;
for (const option of $("perspective").options) {
option.hidden = option.value !== "network" && !auth?.permissions?.debug;
option.disabled = option.hidden;
}
$("perspective-label").hidden = !auth?.permissions?.debug;
if (!auth?.permissions?.debug) perspective = "network";
updateStatus();
}
function updateStatus() {
const status = $("connection");
const updated = live?.updated ?? network?.updated;
status.className = connected ? "success" : "warning";
status.textContent = connected ? "Игра в сети"
: auth ? updated ? `Нет связи · снимок от ${when(updated)}` : "Ожидание игры"
: http ? "Ожидает подключения" : "Нет соединения";
$("refresh-rate").hidden = !connected;
if (connected) {
const rate = (live.sampleMs || 1000) / 1000;
$("refresh-rate").textContent = `Снимок каждые ${rate.toLocaleString("ru-RU")} с · получен в ${when(live.updated)}`;
}
$("logout").disabled = !http;
}
function activeFrame() {
if (historical) return historical.frame?.frame ?? null;
return live?.frame || (perspective === "network" ? network?.frame : null);
}
function select(key, centre = false) {
selected = key;
if (!historical && perspective === "network") {
prefs.selected = key;
write("view", prefs);
}
draw();
if (centre) map.focus(key);
}
function radarStations(frame) {
return frame?.units?.filter(row => row.radarRange > 0) || [];
}
function draw() {
const frame = activeFrame();
const stations = radarStations(frame);
const signature = JSON.stringify(stations.map(({id, label}) => [id, label]));
if (signature !== radarOptions) {
radarOptions = signature;
const options = [new Option("Вся сеть", ""), ...stations.map(row => new Option(`${fullname(row)} №${row.id}`, row.id))];
$("radar-site").replaceChildren(...options);
}
const station = stations.find(row => String(row.id) === prefs.radarSite);
$("radar-site").value = station ? prefs.radarSite : "";
$("radar-site-label").hidden = mapMode !== "radar" || stations.length === 0;
for (const node of document.querySelectorAll("[data-map-mode]")) {
node.setAttribute("aria-pressed", String(node.dataset.mapMode === mapMode));
}
const scope = historical ? historical.frame?.terrain : live?.terrain ?? network?.terrain;
const center = historical ? null : live?.mapCenter ?? network?.mapCenter;
$("player-center").hidden = !center;
map.draw(frame, {selected, layers: prefs.layers, mode: mapMode, radarId: $("radar-site").value, scope, center,
online: !historical && connected && Boolean(live?.terrain)});
$("return-live").hidden = !historical;
$("history-live").hidden = !historical;
$("perspective").disabled = !!historical;
const status = [];
if (historical) {
const actual = historical.frame?.tick;
status.push(actual === undefined ? "Карта для этого момента недоступна" :
actual === historical.requested ? `Записанный кадр · ${time(actual - historical.start)}`
: `Ближайший сохранённый кадр · ${time(actual - historical.start)}`);
} else if (frame) {
if (frame.summary) status.push(`Сбито ${frame.summary.kills} · попаданий ${frame.summary.hits}`);
if (frame.summary?.planning) status.push("Игра готовит налёт");
if (frame.summary?.hold) status.push("Огонь запрещён");
if (perspective === "enemy") status.push(`Донесений ${frame.contacts?.length || 0} · вылетов разведки ${frame.sorties?.length || 0}`);
if (perspective === "truth") status.push("Песочница · истинные позиции");
}
if (frame?.limited) status.push("Часть отметок за пределом отображения");
$("map-status").textContent = status.join(" · ");
const data = groups.flatMap(([group, kind]) => prefs.layers[group] === false ? [] : (frame?.[group] || [])
.map(row => ({row, kind, key: `${kind}:${row.id}`})));
const opened = data.find(item => item.key === selected);
showObject(opened, frame);
const filter = $("object-search").value.toLocaleLowerCase("ru");
const matched = data.filter(({row}) => !filter || fullname(row).toLocaleLowerCase("ru").includes(filter) || String(row.id) === filter);
const list = $("object-list");
const existing = new Map([...list.children].map(node => [node.dataset.objectKey, node]));
const nodes = matched.slice(0, 130).map(({row, key, kind}) => {
const node = existing.get(key) || button("", () => select(key, true));
node.dataset.objectKey = key;
node.dataset.kind = kind;
node.setAttribute("aria-pressed", String(key === selected));
const label = fullname(row);
if (!node.firstChild) node.append(make("span", label), make("small", row.status || ""));
if (node.firstChild.textContent !== label) node.firstChild.textContent = label;
const sublabel = row.status || "";
if (node.lastChild.textContent !== sublabel) node.lastChild.textContent = sublabel;
node.lastChild.hidden = !sublabel;
return node;
});
const note = matched.length > nodes.length ? `Показано ${nodes.length} из ${matched.length}. Уточните поиск.` :
nodes.length === 0 ? "Подходящих объектов нет" : "";
if (note) {
const node = existing.get(undefined) || make("p", "", "empty");
if (node.textContent !== note) node.textContent = note;
nodes.push(node);
}
for (const [index, node] of nodes.entries()) {
if (list.children[index] !== node) list.insertBefore(node, list.children[index] ?? null);
}
while (list.children.length > nodes.length) list.lastChild.remove();
drawScenario();
}
function showObject(opened, frame) {
const card = $("object-card");
if (!opened) {
const nodes = [make("p", historical && selected ? "Этой отметки нет на сохранённом снимке" :
"Коснитесь отметки или выберите объект из списка", "empty")];
if (perspective === "enemy" && !historical && frame?.sorties?.length) {
const phases = {outbound: "на маршруте", looking: "осматривает район", reporting: "передаёт донесение", done: "завершён"};
nodes.push(make("h2", "Игровая разведка"));
frame.sorties.slice(0, 8).forEach(s => nodes.push(paragraph(
`${phases[s.phase] || s.phase} · районов осталось ${s.zones}`)));
}
card.replaceChildren(...nodes);
return;
}
const {row, kind} = opened;
const nodes = [make("h2", fullname(row)), paragraph([row.status, row.details].filter(Boolean).join(" · ")),
paragraph(`X ${Math.round(row.x)} · Y ${Math.round(row.y)} · Z ${Math.round(row.z)} · ID ${row.id}`)];
if (row.health != null) nodes.push(paragraph(`Состояние ${Math.round(row.health * 100)}%`));
if (row.age != null) nodes.push(paragraph(`Давность ${(row.age / 20).toFixed(1)} с`));
if (row.confidence) nodes.push(paragraph(`Достоверность · ${row.confidence}`));
if (row.quality != null) nodes.push(paragraph(`Качество · ${row.quality}`));
if (row.radarRange > 0) nodes.push(paragraph(`Номинальная дальность радара · ${Math.round(row.radarRange)} бл.`));
if (row.radius > 0) nodes.push(paragraph(`Область оценки · ±${Math.round(row.radius)} бл.`));
if (row.target) nodes.push(button(`Контакт №${row.target}`, () => select(`contact:${row.target}`, true)));
if (row.source) {
const linked = frame?.units?.some(unit => unit.id === row.source);
nodes.push(linked ? button(`Источник №${row.source}`, () => select(`unit:${row.source}`, true))
: paragraph(`Источник · ${row.source}`));
}
const focus = historical ? historical.frame?.selected : live?.selected;
if (focus?.unit === row.id && kind === "unit") {
nodes.push(paragraph(`${historical ? "На сохранённом снимке" : "Текущая проверка"} · ${focus.reason}`));
}
if (perspective === "enemy" && !historical) {
const reasons = frame?.reports?.filter(r => r.contact === row.id);
const reasonNames = {plan: "задание плана", sead: "известная позиция ПВО", react: "свежее донесение",
replace: "замена потерянной отметки", refresh: "обновлённое донесение"};
for (const reason of reasons?.slice(0, 8) || []) nodes.push(paragraph(`Игровое назначение · ${reasonNames[reason.reason] || reason.reason}`));
}
if (eventFields[kind] && (perspective === "network" || historical)) {
if (!historical && latestObject.key === `${live?.session}:${opened.key}` && latestObject.event) {
const event = latestObject.event;
nodes.push(paragraph(`${kind === "unit" ? "Последнее решение" : "Последняя запись"} · ${time(event.data.at)} · ${event.label}`));
}
if (!historical) updateObjectEvent(opened);
nodes.push(button("События объекта", () => {
for (const field of Object.values(eventFields)) $(`event-${field}`).value = field === eventFields[kind] ? row.id : "";
setTab("history");
}));
}
card.replaceChildren(...nodes);
}
async function updateObjectEvent(opened) {
if (!connected || !live?.session) return;
const key = `${live.session}:${opened.key}`;
if (latestObject.key === key && Date.now() - latestObject.checked < 3000) return;
const check = {key, checked: Date.now(), event: latestObject.key === key ? latestObject.event : null};
latestObject = check;
const params = new URLSearchParams({session: live.session, limit: "1", [eventFields[opened.kind]]: opened.row.id});
if (opened.kind === "unit") params.set("kind", "decisions");
try {
const data = await api(`/events?${params}`);
if (latestObject === check && selected === opened.key) {
check.event = data.events[0] ?? null;
draw();
}
} catch {}
}
function forgetCachedData() {
clearTimeout(frameTimer);
clearTimeout(eventTimer);
frameGeneration++;
historyGeneration++;
clearEvent();
cache("all", null);
map.clearTerrain();
network = live = historical = null;
connected = false;
latestObject = {key: "", checked: 0, event: null};
offlineEvents = [];
offlineFrames = {};
offlineRaids = {raids: []};
offlineTimelines = {};
timelineGeneration++;
timelineRequests.clear();
events = [];
raids = [];
raid = null;
latestRequest = null;
write("launch-request", null);
}
async function poll() {
if (!auth || polling || document.hidden) return;
polling = true;
try {
if (!http) {
auth = await api("/session");
cache("auth", {role: auth.role});
http = true;
showAuth();
}
const mode = perspective;
const account = auth;
const base = live?.perspective === mode ? live : null;
const params = new URLSearchParams({mode, delta: "1"});
if (base?.revision) params.set("after", base.revision);
const update = await api(`/live?${params}`);
let data = update ? applyLiveUpdate(base, update) : null;
if (update && !data) data = await api(`/live?${new URLSearchParams({mode})}`);
if (account !== auth || mode !== perspective) return;
http = true;
if (data) {
live = data;
connected = data.connected;
if (mode === "network" && data.frame) {
if (prefs.world && prefs.world !== data.world) {
prefs.selected = null;
delete prefs.radarSite;
map.clearTerrain();
prefs.views = {};
if (!historical) {
selected = null;
map.restore(null);
}
}
const worldChanged = prefs.world !== data.world;
prefs.world = data.world;
if (worldChanged) write("view", prefs);
network = data;
if (data.connected) cache("network", data);
}
if (data.catalog && JSON.stringify(catalog) !== JSON.stringify(data.catalog)) {
catalog = data.catalog;
setupScenario();
}
draw();
if (tab === "history") {
await refreshRaids();
await newEvents();
}
} else {
connected = Boolean(base?.connected);
drawScenario();
}
if (tab === "history") refreshTimeline();
if (latestRequest && auth.permissions.launch) watchReceipt(latestRequest);
} catch (error) {
if (error.status === 401) {
auth = null;
forgetCachedData();
showAuth();
} else {
http = connected = false;
if (live?.perspective !== "network") {
perspective = "network";
$("perspective").value = "network";
live = network;
}
draw();
}
} finally {
polling = false;
updateStatus();
}
}
function setTab(next) {
tab = next;
for (const control of document.querySelectorAll("[data-tab]")) {
if (control.dataset.tab === next) control.setAttribute("aria-current", "page");
else control.removeAttribute("aria-current");
}
$("live-panel").hidden = next !== "live";
$("history-panel").hidden = next !== "history";
$("scenario-panel").hidden = next !== "scenario";
if (next === "history") {
refreshRaids().then(() => {
readEvents();
refreshTimeline();
});
}
draw();
}
function chooseRaid(value) {
clearTimeout(frameTimer);
frameGeneration++;
clearEvent();
raid = raids.find(r => `${r.session}:${r.raid}` === value) || null;
$("event-since").disabled = $("event-until").disabled = !raid;
$("timeline").disabled = !raid;
$("timeline").max = raid?.length || 0;
$("timeline").value = $("timeline").max;
$("timeline-caption").textContent = raid ? `Момент ${time(raid.length)}` : "";
if (raid) loadFrame(raid.session, raid.start + raid.length, raid.start);
else {
historical = null;
selected = perspective === "network" ? prefs.selected : null;
map.restore(prefs.views[viewKey()]);
draw();
}
refreshTimeline();
}
async function refreshRaids() {
let data;
const generation = timelineGeneration;
try {
data = await api("/raids");
if (generation !== timelineGeneration) return;
offlineRaids = data;
cache("raids", data);
} catch { data = offlineRaids; }
if (generation !== timelineGeneration) return;
const previous = $("raid").value;
const incoming = data?.raids || [];
const optionsChanged = incoming.length !== raids.length || incoming.some((r, i) =>
raidKey(r) !== raidKey(raids[i]) || r.active !== raids[i]?.active);
if (optionsChanged) {
const options = [new Option("Все налёты", "")];
for (const r of incoming) {
const date = new Date(r.time * 1000).toLocaleString("ru-RU", {dateStyle: "short", timeStyle: "short"});
options.push(new Option(`№${r.raid} · ${date}${r.active ? " · идёт" : ""}`, raidKey(r)));
}
$("raid").replaceChildren(...options);
$("raid").value = options.some(o => o.value === previous) ? previous : "";
}
raids = incoming;
const old = raid;
raid = raids.find(r => `${r.session}:${r.raid}` === $("raid").value) || null;
$("event-since").disabled = $("event-until").disabled = !raid;
$("timeline").disabled = !raid;
$("timeline").max = raid?.length || 0;
if (!historical || !old) $("timeline").value = $("timeline").max;
}
function raidKey(value) {
return value ? `${value.session}:${value.raid}` : "";
}
function paintTimeline() {
const saved = offlineTimelines[raidKey(raid)];
const markers = saved?.events ?? offlineEvents.filter(event => raidKey(event) === raidKey(raid));
timeline.render(raid, markers, selectedEvent);
const status = $("timeline-status");
status.hidden = !raid || !saved?.limited;
status.textContent = "На шкале показана часть отметок. Все доступные события есть в журнале.";
}
async function refreshTimeline() {
paintTimeline();
if (!raid || !http) return;
const key = raidKey(raid);
const previous = timelineRequests.get(key);
const interval = raid.active ? 4000 : 10000;
if (previous?.pending || (previous && previous.active === raid.active && Date.now() - previous.at < interval)) return;
const generation = timelineGeneration;
const params = new URLSearchParams({session: raid.session, raid: raid.raid});
if (offlineTimelines[key]?.revision) params.set("after", offlineTimelines[key].revision);
const request = {pending: true, at: Date.now(), active: raid.active};
timelineRequests.set(key, request);
try {
const data = await api(`/timeline?${params}`);
if (!data || generation !== timelineGeneration) return;
delete offlineTimelines[key];
offlineTimelines[key] = data;
for (const old of Object.keys(offlineTimelines).slice(0, -8)) {
delete offlineTimelines[old];
timelineRequests.delete(old);
}
cache("timelines", offlineTimelines);
if (raidKey(raid) === key) paintTimeline();
} catch {
if (timelineRequests.get(key) === request) timelineRequests.delete(key);
} finally {
request.pending = false;
}
}
function clearEvent() {
chainGeneration++;
selectedEvent = null;
$("event-card").hidden = true;
}
function historyParams(before) {
const params = new URLSearchParams({limit: "70"});
if (raid) {
params.set("session", raid.session);
params.set("raid", raid.raid);
}
for (const key of Object.values(eventFields)) {
const value = $(`event-${key}`).value;
if (/^\d+$/.test(value)) params.set(key, value);
}
for (const key of ["since", "until"]) {
const value = $(`event-${key}`).value;
if (raid && /^\d+$/.test(value)) params.set(key, raid.start + Number(value) * 20);
}
if ($("event-query").value.trim()) params.set("q", $("event-query").value.trim());
if (before) params.set("before", before);
return params;
}
async function readEvents(older = false) {
const token = ++historyGeneration;
const params = historyParams(older && events.at(-1)?.id);
let data;
let saved = false;
try {
data = await api(`/events?${params}`);
if (token !== historyGeneration) return;
rememberEvents(data.events);
} catch {
saved = true;
data = {events: offlineEvents.filter(event => [...params].every(([key, value]) => {
if (key === "q") return JSON.stringify(event).toLocaleLowerCase("ru").includes(value.toLocaleLowerCase("ru"));
if (key === "limit") return true;
if (key === "before") return event.id < Number(value);
if (key === "since") return event.tick >= Number(value);
if (key === "until") return event.tick <= Number(value);
return String(event[key]) === value;
})), more: false};
}
if (token !== historyGeneration) return;
events = older ? [...events, ...data.events] : data.events;
more = data.more;
renderEvents(saved);
}
function rememberEvents(incoming) {
const merged = new Map(offlineEvents.map(e => [e.id, e]));
for (const event of incoming) merged.set(event.id, event);
offlineEvents = [...merged.values()].sort((a, b) => b.id - a.id).slice(0, 600);
cache("events", offlineEvents);
}
async function newEvents() {
if (!events.length) return readEvents();
const generation = historyGeneration;
const params = historyParams();
params.set("after", events[0].id);
try {
const data = await api(`/events?${params}`);
if (!data.events.length || generation !== historyGeneration) return;
rememberEvents(data.events);
events = [...data.events.reverse(), ...events].slice(0, 500);
renderEvents(false);
} catch {}
}
function renderEvents(saved) {
const status = [];
if (saved) status.push("Доступна история, загруженная на это устройство");
if (raid?.gap) status.push("В журнале налёта есть пропуски");
if (offlineRaids?.limited) status.push("Старые записи за пределом хранения");
$("history-status").textContent = status.join(" · ");
const starts = new Map(raids.map(r => [`${r.session}:${r.raid}`, r.time]));
const at = event => (starts.get(`${event.session}:${event.raid}`) || 0) + event.data.at / 20;
const chronological = [...events].sort((a, b) => at(b) - at(a) || b.id - a.id);
const items = chronological.map(event => button(`№${event.raid} · ${time(event.data.at)} · ${event.label}`,
() => openEvent(event)));
$("events").replaceChildren(...(items.length ? items : [make("p", "События для этого фильтра отсутствуют", "empty")]));
$("history-more").hidden = !more;
paintTimeline();
}
async function openEvent(event) {
clearTimeout(frameTimer);
const chainRequest = ++chainGeneration;
selectedEvent = event.id;
const thisRaid = raids.find(r => r.session === event.session && r.raid === event.raid);
const start = thisRaid?.start ?? event.tick - event.data.at;
const nodes = [make("h3", event.label)];
if (!event.data.lines.length) nodes.push(paragraph(`Налёт №${event.raid} · ${time(event.data.at)}`));
for (const line of event.data.lines) {
if (!line.startsWith("На тот момент · ")) nodes.push(paragraph(line));
}
for (const [kind, field, label] of [["unit", "unit", "комплекс"], ["contact", "target", "контакт"], ["object", "object", "объект"]]) {
if (event[field] == null) continue;
nodes.push(button(`Открыть ${label} ${event[field]}`, () => {
setTab("live");
select(`${kind}:${event[field]}`, true);
$("object-card").focus({preventScroll: true});
$("object-card").scrollIntoView({block: "nearest"});
}));
}
$("event-card").replaceChildren(...nodes);
$("event-card").hidden = false;
if (thisRaid) {
const changed = raidKey(raid) !== raidKey(thisRaid);
raid = thisRaid;
$("event-since").disabled = $("event-until").disabled = false;
$("raid").value = `${raid.session}:${raid.raid}`;
$("timeline").max = raid.length;
$("timeline").value = event.data.at;
$("timeline").disabled = false;
if (changed) readEvents();
}
refreshTimeline();
selected = event.unit != null ? `unit:${event.unit}` : event.object != null ? `object:${event.object}` :
event.target != null ? `contact:${event.target}` : null;
await Promise.all([loadFrame(event.session, event.tick, start, true), showChain(event, chainRequest)]);
}
async function showChain(event, generation) {
let chain;
try {
chain = await api(`/chain?event=${event.id}`);
if (generation !== chainGeneration) return;
rememberEvents(chain.events);
} catch {
chain = {
context: event.target == null, limited: true,
events: offlineEvents.filter(item => item.session === event.session && item.raid === event.raid &&
(event.target == null ? event.unit != null && item.unit === event.unit && Math.abs(event.tick - item.tick) <= 200
: item.target === event.target))
.sort((a, b) => Number(b.id === event.id) - Number(a.id === event.id) ||
Math.abs(a.tick - event.tick) - Math.abs(b.tick - event.tick) || a.id - b.id).slice(0, 40)
.sort((a, b) => a.tick - b.tick || eventOrder[a.kind] - eventOrder[b.kind] || a.id - b.id),
};
}
if (generation !== chainGeneration || chain.events.length < 2) return;
const card = $("event-card");
card.append(make("h3", chain.context ? "События комплекса рядом по времени" : "Цепочка контакта"));
if (chain.limited) card.append(paragraph("Показана доступная часть цепочки"));
const items = make("div", undefined, "list scroller chain");
for (const related of chain.events) {
const links = [related.unit != null ? `комплекс ${related.unit}` : "",
chain.context && related.target != null ? `контакт ${related.target}` : ""].filter(Boolean);
const action = button([time(related.data.at), related.label, ...links].join(" · "), () => openEvent(related));
action.setAttribute("aria-pressed", String(related.id === event.id));
items.append(action);
}
card.append(items);
}
async function loadFrame(session, tick, start, focus = false) {
const generation = ++frameGeneration;
const key = `${session}:${tick}`;
let scene;
try {
scene = await api(`/frame?${new URLSearchParams({session, tick})}`);
if (generation !== frameGeneration) return;
delete offlineFrames[key];
offlineFrames[key] = scene;
const keys = Object.keys(offlineFrames);
for (const old of keys.slice(0, -20)) delete offlineFrames[old];
cache("frames", offlineFrames);
} catch {
scene = offlineFrames[key] || Object.entries(offlineFrames)
.filter(([id]) => id.startsWith(`${session}:`))
.map(([, item]) => item)
.sort((a, b) => Math.abs(a.frame.tick - tick) - Math.abs(b.frame.tick - tick))[0];
}
if (generation !== frameGeneration) return;
const frame = scene?.frame;
historical = {requested: tick, start, frame: frame && Math.abs(frame.tick - tick) <= 100 ? frame : null};
$("timeline-caption").textContent = `Момент ${time(tick - start)}`;
draw();
if (focus && selected) map.focus(selected);
}
function setupScenario() {
if (!catalog) return;
$("preset").replaceChildren(...catalog.presets.map((p, i) => new Option(p.name, i)), new Option("Черновик", "custom"));
$("approach").replaceChildren(...catalog.approaches.map((name, i) => new Option(name, i)));
$("aim").replaceChildren(...catalog.aims.map((name, i) => new Option(name, i)));
$("distance").min = catalog.distance[0];
$("distance").max = catalog.distance[1];
$("counts").replaceChildren(...catalog.kinds.map((name, i) => {
const label = make("label", name);
const input = make("input");
input.id = `count-${i}`;
input.type = "number";
input.inputMode = "numeric";
input.min = 0;
input.max = 80;
input.value = 0;
label.append(input);
return label;
}));
const saved = read("draft", null);
if (saved && saved.counts.length === catalog.kinds.length) {
$("preset").value = "custom";
applyDraft(saved);
} else {
$("preset").value = String(Math.min(catalog.presets.length - 1, 1));
applyDraft(catalog.presets[Number($("preset").value)]);
}
}
function applyDraft(value) {
if (!value) return;
$("distance").value = value.distance;
$("approach").value = String(value.approach);
$("aim").value = String(value.aim);
value.counts.forEach((value, i) => { $(`count-${i}`).value = value; });
drawScenario();
}
function draft() {
if (!catalog) return null;
return {
distance: Number($("distance").value),
approach: Number($("approach").value),
aim: Number($("aim").value),
counts: catalog.kinds.map((_, i) => Number($(`count-${i}`).value)),
};
}
function draftValid(value) {
return value && value.counts.some(n => n > 0) && $("scenario-form").checkValidity() &&
value.counts.every(n => Number.isInteger(n) && n >= 0 && n <= 80);
}
function drawScenario() {
const value = draft();
$("preview").disabled = !draftValid(value);
$("scenario-summary").textContent = value ? `Всего ${value.counts.reduce((sum, n) => sum + n, 0)} аппаратов` : "Состав появится после подключения игры";
$("confirm-launch").disabled = !connected || !live?.canLaunch || !auth?.permissions?.launch || !!historical || !!latestRequest;
}
function finishReceipt(result) {
$("launch-status").textContent = result.message;
if (["queued", "dispatching"].includes(result.state)) {
return;
}
latestRequest = null;
write("launch-request", null);
drawScenario();
}
async function watchReceipt(id) {
if (receiptTimer || !http || !id) return;
receiptTimer = true;
try {
finishReceipt(await api(`/launch/${id}`));
} catch (error) {
$("launch-status").textContent = error.status === 404
? "Сервер не сохранил ответ. Запрос автоматически не повторяется."
: "Ожидание ответа игры после восстановления связи";
if (error.status === 404) {
latestRequest = null;
write("launch-request", null);
}
} finally {
receiptTimer = false;
}
}
let confirmedDraft = null;
$("scenario-form").addEventListener("submit", event => {
event.preventDefault();
const value = draft();
if (!draftValid(value)) return;
confirmedDraft = value;
const summary = [
paragraph(`${catalog.approaches[value.approach]} · ${catalog.aims[value.aim]} · ${value.distance} бл.`),
...value.counts.flatMap((n, i) => n ? [paragraph(`${catalog.kinds[i]} × ${n}`)] : []),
];
if (!auth?.permissions?.launch) summary.push(paragraph("Для запуска подключите устройство кодом оператора."));
else if (!live?.canLaunch || historical) summary.push(paragraph("Запуск доступен при прямом эфире и готовой игре."));
$("preview-details").replaceChildren(...summary);
drawScenario();
$("confirmation").showModal();
});
$("confirm-launch").addEventListener("click", async () => {
if (!confirmedDraft || $("confirm-launch").disabled) return;
const request = Array.from(crypto.getRandomValues(new Uint8Array(16)), n => n.toString(16).padStart(2, "0")).join("");
latestRequest = request;
write("launch-request", request);
$("confirmation").close();
drawScenario();
$("launch-status").textContent = "Отправляем запрос…";
try {
finishReceipt(await api("/launch", {
method: "POST", data: {id: request, session: live.session, wave: confirmedDraft},
}));
} catch (error) {
if (error instanceof APIError) finishReceipt({message: error.message, state: "rejected"});
else $("launch-status").textContent = "Связь прервалась. После подключения проверим результат.";
}
});
$("cancel-launch").addEventListener("click", () => $("confirmation").close());
$("preset").addEventListener("change", () => {
applyDraft(catalog?.presets[Number($("preset").value)]);
write("draft", draft());
});
$("scenario-form").addEventListener("input", event => {
if (event.target !== $("preset")) {
$("preset").value = "custom";
write("draft", draft());
drawScenario();
}
});
for (const node of document.querySelectorAll("[data-tab]")) node.addEventListener("click", () => setTab(node.dataset.tab));
for (const node of document.querySelectorAll("[data-layer]")) {
node.checked = prefs.layers[node.dataset.layer] !== false;
node.addEventListener("change", () => {
prefs.layers[node.dataset.layer] = node.checked;
write("view", prefs);
draw();
});
}
function centerRadar() {
const station = radarStations(activeFrame()).find(row => String(row.id) === prefs.radarSite);
if (station) map.centerAt(station.x, station.z, station.radarRange);
}
for (const node of document.querySelectorAll("[data-map-mode]")) {
node.addEventListener("click", () => {
if (mapMode === node.dataset.mapMode) return;
mapMode = prefs.mapMode = node.dataset.mapMode;
if (!historical) {
map.restore(prefs.views[viewKey()]);
if (mapMode === "radar" && !prefs.views[viewKey()]) centerRadar();
}
write("view", prefs);
draw();
});
}
$("radar-site").addEventListener("change", () => {
prefs.radarSite = $("radar-site").value;
centerRadar();
write("view", prefs);
draw();
});
$("object-search").addEventListener("input", draw);
$("zoom-in").addEventListener("click", () => map.zoom(1.3));
$("zoom-out").addEventListener("click", () => map.zoom(1 / 1.3));
$("fit").addEventListener("click", map.fit);
$("player-center").addEventListener("click", () => {
const center = live?.mapCenter ?? network?.mapCenter;
if (center) map.centerAt(...center);
});
$("perspective").addEventListener("change", () => {
perspective = $("perspective").value;
selected = perspective === "network" ? prefs.selected : null;
live = perspective === "network" ? network : null;
map.restore(prefs.views[viewKey()]);
draw();
poll();
});
function returnLive() {
clearTimeout(frameTimer);
clearEvent();
frameGeneration++;
historical = null;
selected = prefs.selected;
perspective = "network";
$("perspective").value = "network";
live = network;
map.restore(prefs.views[viewKey()]);
setTab("live");
poll();
}
$("return-live").addEventListener("click", returnLive);
$("history-live").addEventListener("click", returnLive);
$("raid").addEventListener("change", () => {
chooseRaid($("raid").value);
readEvents();
});
$("timeline").addEventListener("input", () => {
clearTimeout(frameTimer);
frameGeneration++;
clearEvent();
paintTimeline();
const at = Number($("timeline").value);
$("timeline-caption").textContent = `Момент ${time(at)}`;
frameTimer = setTimeout(() => {
if (raid) loadFrame(raid.session, raid.start + at, raid.start);
}, 130);
});
for (const id of ["event-unit", "event-target", "event-object", "event-since", "event-until", "event-query"]) {
$(id).addEventListener("input", () => {
clearTimeout(eventTimer);
eventTimer = setTimeout(readEvents, 150);
});
}
$("history-more").addEventListener("click", () => readEvents(true));
$("pair-form").addEventListener("submit", async event => {
event.preventDefault();
try {
await api("/pair", {method: "POST", data: {code: $("pair-code").value.trim()}});
$("pair-code").value = "";
$("pair-error").textContent = "";
auth = await api("/session");
http = true;
cache("auth", {role: auth.role});
showAuth();
poll();
} catch (error) { $("pair-error").textContent = error.message; }
});
$("logout").addEventListener("click", async () => {
try { await api("/session", {method: "DELETE"}); }
catch (error) { if (error.status !== 401) return; }
auth = null;
forgetCachedData();
showAuth();
});
window.addEventListener("beforeinstallprompt", event => {
event.preventDefault();
installPrompt = event;
$("install").hidden = false;
});
$("install").addEventListener("click", async () => {
if (installPrompt) await installPrompt.prompt();
$("install").hidden = true;
});
if ("serviceWorker" in navigator && window.isSecureContext) navigator.serviceWorker.register("./sw.js").catch(() => {});
async function start() {
const [cachedAuth, savedNetwork, cachedEvents, cachedRaids, cachedFrames, cachedTimelines] = await Promise.all(
["auth", "network", "events", "raids", "frames", "timelines"].map(key => cache(key)));
network = live = savedNetwork ?? null;
offlineEvents = cachedEvents ?? [];
offlineRaids = cachedRaids ?? {raids: []};
offlineFrames = cachedFrames ?? {};
offlineTimelines = cachedTimelines ?? {};
try {
auth = await api("/session");
http = true;
cache("auth", {role: auth.role});
} catch (error) {
if (error.status === 401) {
http = true;
forgetCachedData();
} else if (cachedAuth) {
auth = {...cachedAuth, permissions: {launch: false, debug: false}};
}
}
catalog = network?.catalog;
setupScenario();
showAuth();
draw();
poll();
}
window.addEventListener("online", async () => {
if (auth) {
try { auth = await api("/session"); showAuth(); } catch {}
}
poll();
});
document.addEventListener("visibilitychange", () => { if (!document.hidden) poll(); });
setInterval(poll, LIVE_POLL_MS);
start();