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

775 lines
32 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";
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 ||= {};
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: []};
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),
onView: view => {
prefs.views[perspective] = view;
write("view", prefs);
},
});
map.restore(prefs.views.network);
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;
}
if (!auth?.permissions?.debug) perspective = "network";
updateStatus();
}
function updateStatus() {
const status = $("connection");
status.className = connected ? "success" : "warning";
status.textContent = connected ? `Игра в сети · ${when(live?.updated)}`
: auth ? live?.updated ? `Нет связи · снимок от ${when(live.updated)}` : "Ожидание игры"
: http ? "Ожидает подключения" : "Нет соединения";
$("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 draw() {
const frame = activeFrame();
map.draw(frame, {selected, layers: prefs.layers});
$("return-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 oldScroll = $("object-list").scrollTop;
const focused = document.activeElement?.dataset.objectKey;
const nodes = matched.slice(0, 130).map(({row, key}) => {
const node = button([fullname(row), row.status].filter(Boolean).join(" · "), () => select(key, true));
node.dataset.objectKey = key;
node.setAttribute("aria-pressed", String(key === selected));
return node;
});
if (matched.length > nodes.length) nodes.push(paragraph(`Показано ${nodes.length} из ${matched.length}. Уточните поиск.`));
if (!nodes.length) nodes.push(make("p", "Подходящих объектов нет", "empty"));
$("object-list").replaceChildren(...nodes);
$("object-list").scrollTop = oldScroll;
if (focused) nodes.find(node => node.dataset.objectKey === focused)?.focus({preventScroll: true});
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.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() {
cache("all", null);
network = live = historical = null;
connected = false;
latestObject = {key: "", checked: 0, event: null};
offlineEvents = [];
offlineFrames = {};
offlineRaids = {raids: []};
events = [];
raids = [];
raid = null;
latestRequest = null;
write("launch-request", null);
$("event-card").hidden = true;
}
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 params = new URLSearchParams({mode});
if (live?.perspective === mode) params.set("after", live.revision || "");
const data = await api(`/live?${params}`);
http = true;
if (mode !== perspective) return;
if (data) {
live = data;
connected = data.connected;
if (mode === "network" && data.frame) {
if (prefs.world && prefs.world !== data.world) {
prefs.selected = selected = null;
map.restore(null);
}
prefs.world = data.world;
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();
}
}
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());
}
draw();
}
function chooseRaid(value) {
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)}` : "";
$("event-card").hidden = true;
}
async function refreshRaids() {
let data;
try {
data = await api("/raids");
offlineRaids = data;
cache("raids", data);
} catch { data = offlineRaids; }
const previous = $("raid").value;
const incoming = data?.raids || [];
const changed = incoming.length !== raids.length || incoming.some((r, i) =>
r.session !== raids[i]?.session || r.raid !== raids[i]?.raid || r.length !== raids[i]?.length || r.active !== raids[i]?.active);
if (!changed) return;
raids = incoming;
const options = [new Option("Все налёты", "")];
for (const r of raids) {
const date = new Date(r.time * 1000).toLocaleString("ru-RU", {dateStyle: "short", timeStyle: "short"});
options.push(new Option(`№${r.raid} · ${date}${r.active ? " · идёт" : ""}`, `${r.session}:${r.raid}`));
}
$("raid").replaceChildren(...options);
$("raid").value = options.some(o => o.value === previous) ? previous : "";
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 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;
}
async function openEvent(event) {
const chainRequest = ++chainGeneration;
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) {
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;
}
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), showChain(event, chainRequest)]);
}
async function showChain(event, generation) {
let chain;
try {
chain = await api(`/chain?event=${event.id}`);
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) {
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 (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();
});
}
$("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);
$("perspective").addEventListener("change", () => {
perspective = $("perspective").value;
selected = perspective === "network" ? prefs.selected : null;
live = perspective === "network" ? network : null;
map.restore(prefs.views[perspective]);
draw();
poll();
});
$("return-live").addEventListener("click", () => {
frameGeneration++;
historical = null;
selected = prefs.selected;
perspective = "network";
$("perspective").value = "network";
live = network;
setTab("live");
poll();
});
$("raid").addEventListener("change", () => {
chooseRaid($("raid").value);
readEvents();
});
$("timeline").addEventListener("input", () => {
clearTimeout(frameTimer);
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] = await Promise.all(
["auth", "network", "events", "raids", "frames"].map(key => cache(key)));
network = live = savedNetwork ?? null;
offlineEvents = cachedEvents ?? [];
offlineRaids = cachedRaids ?? {raids: []};
offlineFrames = cachedFrames ?? {};
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, 1200);
start();