Add the AirDef tablet web panel and battle archive (#153)
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||
font-size: 16px;
|
||||
background: #0b121a;
|
||||
color: #e4edf1;
|
||||
--surface: #111e29;
|
||||
--surface-raised: #182936;
|
||||
--border: #2b4250;
|
||||
--muted: #9ab0bb;
|
||||
--accent: #70d7c9;
|
||||
--warning: #edbd6c;
|
||||
--danger: #f08c83;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-width: 280px; min-height: 100vh; min-height: 100dvh; }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button, select { cursor: pointer; }
|
||||
button, input, select, textarea {
|
||||
min-height: 44px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 9px;
|
||||
background: #12232e;
|
||||
color: inherit;
|
||||
}
|
||||
button { padding: .6rem .9rem; font-weight: 650; }
|
||||
button:hover:not(:disabled) { background: #213c48; border-color: #52717c; }
|
||||
button:active:not(:disabled) { transform: translateY(1px); }
|
||||
button:disabled { cursor: not-allowed; opacity: .48; }
|
||||
input, select, textarea { width: 100%; padding: .6rem .7rem; }
|
||||
select {
|
||||
appearance: none;
|
||||
padding-right: 1.8rem;
|
||||
background-image: linear-gradient(45deg, transparent 50%, #9ab0bb 50%), linear-gradient(135deg, #9ab0bb 50%, transparent 50%);
|
||||
background-position: calc(100% - 15px) center, calc(100% - 10px) center;
|
||||
background-size: 5px 5px;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
input[type="checkbox"], input[type="radio"] { width: auto; min-height: auto; accent-color: var(--accent); }
|
||||
label { display: grid; gap: .35rem; color: var(--muted); font-size: .88rem; font-weight: 600; }
|
||||
a { color: var(--accent); }
|
||||
:focus-visible { outline: 3px solid #9af4e5; outline-offset: 3px; }
|
||||
h1, h2, h3, p { margin-top: 0; }
|
||||
h1 { font-size: clamp(1.15rem, 2.4vw, 1.55rem); margin-bottom: 0; }
|
||||
h2 { font-size: 1rem; margin-bottom: .8rem; }
|
||||
h3 { font-size: .9rem; margin-bottom: .55rem; }
|
||||
.shell { width: min(100%, 1680px); margin: 0 auto; padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left)); }
|
||||
.topbar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .65rem 1rem; padding: .3rem .1rem .9rem; }
|
||||
.topbar p { margin: .2rem 0 0; color: var(--muted); font-size: .82rem; }
|
||||
.status, [role="status"] { color: var(--muted); font-size: .85rem; }
|
||||
.tabs { display: flex; gap: .4rem; overflow-x: auto; padding: 0 0 .75rem; scrollbar-width: thin; }
|
||||
.tabs button, .tabs a { flex: 0 0 auto; }
|
||||
.tabs [aria-selected="true"], .tabs [aria-current="page"], .tabs .active { background: #1b4c4a; border-color: #70d7c9; color: #e6fffa; }
|
||||
.workspace { display: grid; grid-template-columns: minmax(0, 1fr) minmax(260px, 340px); gap: .85rem; align-items: start; }
|
||||
.map-column, .side-panel { min-width: 0; display: grid; gap: .75rem; }
|
||||
.map-wrap { position: relative; overflow: hidden; min-height: 260px; border: 1px solid #35515d; border-radius: 12px; background: #101c24; }
|
||||
.map-wrap canvas { display: block; width: 100%; height: auto; touch-action: none; }
|
||||
.map-tools, .toolbar, .row { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; }
|
||||
.map-tools > *, .toolbar > * { flex: 0 1 auto; }
|
||||
.card { min-width: 0; padding: 1rem; border: 1px solid var(--border); border-radius: 12px; background: var(--surface); }
|
||||
.card > :last-child { margin-bottom: 0; }
|
||||
.card + .card { margin-top: 0; }
|
||||
.list { display: grid; gap: .5rem; padding: 0; margin: 0; list-style: none; }
|
||||
.list > * { min-width: 0; padding: .7rem; border: 1px solid #29404c; border-radius: 8px; background: #142530; overflow-wrap: anywhere; }
|
||||
.empty { color: var(--muted); line-height: 1.5; padding: .6rem 0; }
|
||||
small, .muted { color: var(--muted); }
|
||||
.success { color: var(--accent); }
|
||||
.warning { color: var(--warning); }
|
||||
.error, .danger { color: var(--danger); }
|
||||
[hidden] { display: none !important; }
|
||||
dialog { width: min(90vw, 540px); max-height: min(85vh, 800px); overflow: auto; padding: 1.2rem; border: 1px solid #4d6974; border-radius: 14px; background: #152630; color: inherit; box-shadow: 0 20px 70px #0009; }
|
||||
dialog::backdrop { background: #02080dc9; }
|
||||
@media (max-width: 800px) {
|
||||
.workspace { grid-template-columns: minmax(0, 1fr); }
|
||||
.side-panel { grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr)); }
|
||||
.map-wrap { min-height: 200px; }
|
||||
}
|
||||
@media (max-width: 420px) {
|
||||
.shell { padding-left: max(8px, env(safe-area-inset-left)); padding-right: max(8px, env(safe-area-inset-right)); }
|
||||
.card { padding: .8rem; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { scroll-behavior: auto !important; transition-duration: 0s !important; animation-duration: 0s !important; } }
|
||||
|
||||
.map-wrap canvas { height: clamp(280px, 59dvh, 690px); }
|
||||
.map-tools { justify-content: space-between; }
|
||||
.map-actions { display: flex; gap: .35rem; }
|
||||
.map-actions button { min-width: 44px; }
|
||||
.legend { display: flex; flex-wrap: wrap; gap: .65rem 1rem; padding: .65rem .85rem; }
|
||||
.legend label { display: flex; align-items: center; min-height: 34px; cursor: pointer; }
|
||||
.side-panel > .card { display: grid; gap: .7rem; }
|
||||
.pairing { max-width: 410px; margin: clamp(36px, 15vh, 160px) auto 0; }
|
||||
.pairing form, #scenario-form { display: grid; gap: .7rem; }
|
||||
.scroller { max-height: 380px; overflow-y: auto; scrollbar-color: #42636f transparent; }
|
||||
.list button { text-align: left; min-height: 44px; font-size: .9rem; }
|
||||
.list [aria-pressed="true"] { border-color: var(--accent); background: #193b40; }
|
||||
.subcard, .object-card:not(:empty) { border-bottom: 1px solid var(--border); padding-bottom: .7rem; }
|
||||
.subcard h3:not(:first-child) { margin-top: .9rem; }
|
||||
.scroller.chain { max-height: 225px; }
|
||||
.detail-row { margin: .25rem 0; line-height: 1.4; font-size: .9rem; }
|
||||
.fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .55rem; }
|
||||
.object-card button { margin-top: .5rem; }
|
||||
#history-more, #preview, #confirm-launch { color: #b6f3eb; border-color: #447672; }
|
||||
#launch-status:empty, #pair-error:empty, #map-status:empty { display: none; }
|
||||
@media (min-width: 801px) and (min-height: 680px) { .map-column { position: sticky; top: .75rem; } }
|
||||
@media (max-width: 800px) { .map-wrap canvas { height: clamp(240px, 46dvh, 580px); } }
|
||||
@@ -0,0 +1,774 @@
|
||||
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();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
@@ -0,0 +1,114 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<meta name="theme-color" content="#0b121a">
|
||||
<title>Веб-пульт AirDef</title>
|
||||
<link rel="stylesheet" href="./app.css">
|
||||
<link rel="manifest" href="./manifest.webmanifest">
|
||||
<link rel="apple-touch-icon" href="./icons/icon-192.png">
|
||||
<link rel="icon" href="./icons/icon-192.png">
|
||||
<script type="module" src="./app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main class="shell">
|
||||
<header class="topbar">
|
||||
<div><h1>AirDef</h1><p>Командный пункт</p></div>
|
||||
<div class="row">
|
||||
<span id="connection" role="status">Подключение…</span>
|
||||
<button id="install" type="button" hidden>Установить</button>
|
||||
<button id="logout" type="button" hidden>Отвязать</button>
|
||||
</div>
|
||||
</header>
|
||||
<section id="pairing" class="card pairing" hidden>
|
||||
<h2>Подключить устройство</h2>
|
||||
<form id="pair-form">
|
||||
<label>Одноразовый код с ПК<input id="pair-code" type="password" maxlength="64" required autocomplete="off"></label>
|
||||
<button type="submit">Подключить</button>
|
||||
<p id="pair-error" class="error" role="alert"></p>
|
||||
</form>
|
||||
</section>
|
||||
<section id="dashboard" hidden>
|
||||
<nav class="tabs" aria-label="Разделы">
|
||||
<button type="button" data-tab="live" aria-current="page">Карта</button>
|
||||
<button type="button" data-tab="history">История</button>
|
||||
<button type="button" data-tab="scenario">Сценарий</button>
|
||||
</nav>
|
||||
<div class="workspace">
|
||||
<section id="map-panel" class="map-column" aria-label="Карта боя">
|
||||
<div class="map-tools">
|
||||
<label>Ракурс<select id="perspective">
|
||||
<option value="network">Картина игрока</option>
|
||||
<option value="enemy" hidden>Что известно противнику</option>
|
||||
<option value="truth" hidden>Истина · песочница</option>
|
||||
</select></label>
|
||||
<button type="button" id="return-live" hidden>К прямому эфиру</button>
|
||||
<div class="map-actions">
|
||||
<button type="button" id="zoom-in" aria-label="Приблизить">+</button>
|
||||
<button type="button" id="zoom-out" aria-label="Отдалить">−</button>
|
||||
<button type="button" id="fit">Вся карта</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="map-wrap"><canvas id="map" aria-label="Карта игровых объектов"></canvas></div>
|
||||
<div class="card legend" id="layer-options">
|
||||
<label><input type="checkbox" data-layer="units" checked> □ Техника</label>
|
||||
<label><input type="checkbox" data-layer="objects" checked> ◇ Объекты</label>
|
||||
<label><input type="checkbox" data-layer="contacts" checked> ○ Контакты</label>
|
||||
<label><input type="checkbox" data-layer="interceptors" checked> ▵ Перехватчики</label>
|
||||
</div>
|
||||
<p id="map-status" role="status"></p>
|
||||
</section>
|
||||
<aside class="side-panel">
|
||||
<section id="live-panel" class="card">
|
||||
<div id="object-card" class="object-card" tabindex="-1"></div>
|
||||
<label>Найти на карте<input id="object-search" type="search" autocomplete="off"></label>
|
||||
<div id="object-list" class="list scroller" aria-label="Объекты на карте"></div>
|
||||
</section>
|
||||
<section id="history-panel" class="card" hidden>
|
||||
<h2>История боя</h2>
|
||||
<label>Налёт<select id="raid"></select></label>
|
||||
<label>Момент повтора<input type="range" id="timeline" min="0" max="0" value="0" disabled></label>
|
||||
<p id="timeline-caption" aria-live="polite" class="muted"></p>
|
||||
<div class="fields">
|
||||
<label>ID комплекса<input id="event-unit" type="number" min="0" inputmode="numeric"></label>
|
||||
<label>ID контакта<input id="event-target" type="number" min="0" inputmode="numeric"></label>
|
||||
<label>ID объекта<input id="event-object" type="number" min="1" inputmode="numeric"></label>
|
||||
<label>От секунды<input id="event-since" type="number" min="0" inputmode="numeric" disabled></label>
|
||||
<label>До секунды<input id="event-until" type="number" min="0" inputmode="numeric" disabled></label>
|
||||
</div>
|
||||
<label>Поиск в журнале<input id="event-query" type="search" autocomplete="off"></label>
|
||||
<p id="history-status" role="status"></p>
|
||||
<article id="event-card" class="subcard" hidden></article>
|
||||
<div id="events" class="list scroller" aria-label="События боя"></div>
|
||||
<button type="button" id="history-more" hidden>Более ранние</button>
|
||||
</section>
|
||||
<section id="scenario-panel" class="card" hidden>
|
||||
<h2>Сценарий налёта</h2>
|
||||
<form id="scenario-form">
|
||||
<label>Готовый состав<select id="preset"></select></label>
|
||||
<div class="fields">
|
||||
<label>Подход<select id="approach"></select></label>
|
||||
<label>Цель<select id="aim"></select></label>
|
||||
<label>Расстояние, блоки<input id="distance" type="number" required inputmode="numeric"></label>
|
||||
</div>
|
||||
<div id="counts" class="fields"></div>
|
||||
<p id="scenario-summary" role="status"></p>
|
||||
<button id="preview" type="submit">Предпросмотр</button>
|
||||
</form>
|
||||
<p id="launch-status" role="status"></p>
|
||||
</section>
|
||||
</aside>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<dialog id="confirmation">
|
||||
<h2>Подтвердить сценарий</h2>
|
||||
<div id="preview-details"></div>
|
||||
<div class="toolbar">
|
||||
<button id="confirm-launch" type="button">Запустить</button>
|
||||
<button id="cancel-launch" type="button">Назад</button>
|
||||
</div>
|
||||
</dialog>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"name": "AirDef — пульт управления",
|
||||
"short_name": "AirDef",
|
||||
"description": "Локальный планшетный пульт AirDef",
|
||||
"id": "./",
|
||||
"start_url": "./",
|
||||
"scope": "./",
|
||||
"display": "standalone",
|
||||
"background_color": "#0b121a",
|
||||
"theme_color": "#0b121a",
|
||||
"icons": [
|
||||
{ "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" },
|
||||
{ "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
const styles = [
|
||||
["units", "unit", "#6adcd2"],
|
||||
["objects", "object", "#a9baf6"],
|
||||
["contacts", "contact", "#f0bf6a"],
|
||||
["interceptors", "interceptor", "#b2e68f"],
|
||||
];
|
||||
const clamp = (x, low, high) => Math.min(high, Math.max(low, x));
|
||||
|
||||
export function createMap(canvas, {onSelect, onView}) {
|
||||
const ctx = canvas.getContext("2d");
|
||||
const view = {x: 0, z: 0, scale: .22};
|
||||
const fingers = new Map();
|
||||
let points = [], visible = [], selected, width = 1, height = 1, drawnFrame;
|
||||
let moved = false, autoFit = true, queued = false;
|
||||
|
||||
function paint() {
|
||||
queued = false;
|
||||
const ratio = Math.min(2, window.devicePixelRatio || 1);
|
||||
width = Math.max(1, canvas.clientWidth);
|
||||
height = Math.max(1, canvas.clientHeight);
|
||||
const w = Math.round(width * ratio), h = Math.round(height * ratio);
|
||||
if (canvas.width !== w || canvas.height !== h) {
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
}
|
||||
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
|
||||
ctx.fillStyle = "#101c24";
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
const {x, z, scale} = view;
|
||||
const px = v => (v - x) * scale + width / 2;
|
||||
const py = v => (v - z) * scale + height / 2;
|
||||
const left = x - width / (2 * scale), top = z - height / (2 * scale);
|
||||
const steps = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000];
|
||||
const step = steps.find(s => s * scale >= 48) || steps.at(-1);
|
||||
ctx.strokeStyle = "#233947";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
for (let a = Math.ceil(left / step) * step; px(a) < width; a += step) {
|
||||
const line = Math.round(px(a)) + .5;
|
||||
ctx.moveTo(line, 0);
|
||||
ctx.lineTo(line, height);
|
||||
}
|
||||
for (let a = Math.ceil(top / step) * step; py(a) < height; a += step) {
|
||||
const line = Math.round(py(a)) + .5;
|
||||
ctx.moveTo(0, line);
|
||||
ctx.lineTo(width, line);
|
||||
}
|
||||
ctx.stroke();
|
||||
ctx.font = "12px system-ui, sans-serif";
|
||||
ctx.fillStyle = "#b6c8d0";
|
||||
ctx.fillText("↑ N", width - 36, 20);
|
||||
ctx.fillText(`X ${Math.round(x)} · Z ${Math.round(z)}`, 14, 20);
|
||||
const bar = steps.find(s => s * scale >= 40) || steps.at(-1);
|
||||
ctx.fillText(`${bar} бл.`, 14, height - 23);
|
||||
ctx.fillRect(14, height - 16, bar * scale, 2);
|
||||
visible = [];
|
||||
for (const point of points) {
|
||||
const {row, color, kind} = point;
|
||||
const x = px(row.x), y = py(row.z);
|
||||
if (x < -40 || y < -40 || x > width + 40 || y > height + 40) continue;
|
||||
visible.push({...point, x, y});
|
||||
const r = point.key === selected ? 8 : 5;
|
||||
ctx.beginPath();
|
||||
if (kind === "unit") {
|
||||
ctx.rect(x - r, y - r, 2 * r, 2 * r);
|
||||
} else if (kind === "contact") {
|
||||
ctx.arc(x, y, r, 0, Math.PI * 2);
|
||||
} else {
|
||||
ctx.moveTo(x, y - r);
|
||||
ctx.lineTo(x + r, kind === "object" ? y : y + r);
|
||||
if (kind === "object") ctx.lineTo(x, y + r);
|
||||
ctx.lineTo(x - r, kind === "object" ? y : y + r);
|
||||
ctx.closePath();
|
||||
}
|
||||
ctx.strokeStyle = ctx.fillStyle = color;
|
||||
ctx.lineWidth = 2;
|
||||
if (kind !== "contact") ctx.fill();
|
||||
if (row.status?.startsWith("Оценка")) ctx.setLineDash([3, 2]);
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
if (point.key === selected && row.radius > 0) {
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, Math.min(380, row.radius * scale), 0, Math.PI * 2);
|
||||
ctx.setLineDash([5, 5]);
|
||||
ctx.strokeStyle = "#798f98";
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
if (Number.isFinite(row.vx) && Number.isFinite(row.vz)) {
|
||||
const n = Math.hypot(row.vx, row.vz) || 1;
|
||||
const length = clamp(n * scale / 3, 5, 28);
|
||||
ctx.strokeStyle = color;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, y);
|
||||
ctx.lineTo(x + row.vx / n * length, y + row.vz / n * length);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
const focus = visible.find(item => item.key === selected);
|
||||
if (focus) {
|
||||
const links = [
|
||||
focus.row.target != null ? `contact:${focus.row.target}` : null,
|
||||
focus.row.source != null ? `unit:${focus.row.source}` : null,
|
||||
];
|
||||
for (const key of links) {
|
||||
const other = visible.find(item => item.key === key);
|
||||
if (!other || other.key === focus.key) continue;
|
||||
ctx.strokeStyle = "#90bdc0";
|
||||
ctx.setLineDash([5, 5]);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(focus.x, focus.y);
|
||||
ctx.lineTo(other.x, other.y);
|
||||
ctx.stroke();
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
ctx.font = "bold 13px system-ui, sans-serif";
|
||||
const label = focus.row.label || focus.key;
|
||||
const length = Math.min(width - 22, ctx.measureText(label).width + 12);
|
||||
const left = clamp(focus.x + 12, 8, Math.max(8, width - length - 8));
|
||||
const top = clamp(focus.y - 20, 6, Math.max(6, height - 27));
|
||||
ctx.fillStyle = "#081017";
|
||||
ctx.fillRect(left, top, length, 23);
|
||||
ctx.fillStyle = "#eaf7fa";
|
||||
ctx.fillText(label, left + 6, top + 16, length - 12);
|
||||
}
|
||||
if (!points.length) {
|
||||
ctx.fillStyle = "#9ab0bb";
|
||||
ctx.textAlign = "center";
|
||||
ctx.fillText(drawnFrame ? "На выбранных слоях нет объектов" : "Нет снимка карты", width / 2, height / 2);
|
||||
ctx.textAlign = "left";
|
||||
}
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
if (!queued) {
|
||||
queued = true;
|
||||
requestAnimationFrame(paint);
|
||||
}
|
||||
}
|
||||
|
||||
function fit() {
|
||||
if (!points.length) return;
|
||||
let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
|
||||
for (const {row} of points) {
|
||||
minX = Math.min(minX, row.x);
|
||||
maxX = Math.max(maxX, row.x);
|
||||
minZ = Math.min(minZ, row.z);
|
||||
maxZ = Math.max(maxZ, row.z);
|
||||
}
|
||||
view.x = (maxX + minX) / 2;
|
||||
view.z = (maxZ + minZ) / 2;
|
||||
view.scale = clamp(Math.min((canvas.clientWidth - 64) / Math.max(80, maxX - minX),
|
||||
(canvas.clientHeight - 64) / Math.max(80, maxZ - minZ)), .006, 5);
|
||||
autoFit = false;
|
||||
onView({...view});
|
||||
schedule();
|
||||
}
|
||||
|
||||
function zoom(factor, x = width / 2, y = height / 2) {
|
||||
const before = view.scale;
|
||||
view.scale = clamp(before * factor, .006, 12);
|
||||
view.x += (x - width / 2) * (1 / before - 1 / view.scale);
|
||||
view.z += (y - height / 2) * (1 / before - 1 / view.scale);
|
||||
onView({...view});
|
||||
schedule();
|
||||
}
|
||||
|
||||
function coords(event) {
|
||||
const rect = canvas.getBoundingClientRect();
|
||||
return [event.clientX - rect.left, event.clientY - rect.top];
|
||||
}
|
||||
|
||||
canvas.addEventListener("wheel", event => {
|
||||
event.preventDefault();
|
||||
zoom(Math.exp(clamp(-event.deltaY * .002, -.4, .4)), ...coords(event));
|
||||
}, {passive: false});
|
||||
canvas.addEventListener("pointerdown", event => {
|
||||
if (fingers.size === 0) moved = false;
|
||||
if (fingers.size > 0) moved = true;
|
||||
canvas.setPointerCapture(event.pointerId);
|
||||
const at = coords(event);
|
||||
fingers.set(event.pointerId, {at, start: at});
|
||||
});
|
||||
canvas.addEventListener("pointermove", event => {
|
||||
const finger = fingers.get(event.pointerId);
|
||||
if (!finger) return;
|
||||
const at = coords(event), before = finger.at;
|
||||
finger.at = at;
|
||||
const dx = at[0] - before[0], dy = at[1] - before[1];
|
||||
if (fingers.size === 1) {
|
||||
if (Math.hypot(at[0] - finger.start[0], at[1] - finger.start[1]) > 5) moved = true;
|
||||
if (!moved) return;
|
||||
view.x -= dx / view.scale;
|
||||
view.z -= dy / view.scale;
|
||||
} else {
|
||||
const other = [...fingers.values()].find(value => value !== finger).at;
|
||||
const ratio = Math.hypot(at[0] - other[0], at[1] - other[1]) /
|
||||
Math.max(2, Math.hypot(before[0] - other[0], before[1] - other[1]));
|
||||
zoom(ratio, (at[0] + other[0]) / 2, (at[1] + other[1]) / 2);
|
||||
view.x -= dx / (2 * view.scale);
|
||||
view.z -= dy / (2 * view.scale);
|
||||
}
|
||||
onView({...view});
|
||||
schedule();
|
||||
});
|
||||
canvas.addEventListener("pointerup", event => {
|
||||
fingers.delete(event.pointerId);
|
||||
if (moved) return;
|
||||
const [x, y] = coords(event);
|
||||
let hit, distance = 21;
|
||||
for (const p of visible) {
|
||||
const d = Math.hypot(x - p.x, y - p.y);
|
||||
if (d < distance) [hit, distance] = [p, d];
|
||||
}
|
||||
if (hit) onSelect(hit.key);
|
||||
});
|
||||
canvas.addEventListener("pointercancel", event => fingers.delete(event.pointerId));
|
||||
new ResizeObserver(schedule).observe(canvas);
|
||||
|
||||
return {
|
||||
draw(frame, options) {
|
||||
drawnFrame = frame;
|
||||
selected = options.selected;
|
||||
points = styles.flatMap(([group, kind, color]) => options.layers[group] === false ? [] : (frame?.[group] || [])
|
||||
.filter(row => Number.isFinite(row.x) && Number.isFinite(row.z))
|
||||
.map(row => ({row, color, kind, key: `${kind}:${row.id}`})));
|
||||
if (autoFit && canvas.clientWidth > 100 && points.length) fit();
|
||||
schedule();
|
||||
},
|
||||
fit,
|
||||
zoom,
|
||||
restore(saved) {
|
||||
if (saved && [saved.x, saved.z, saved.scale].every(Number.isFinite)) {
|
||||
Object.assign(view, saved, {scale: clamp(saved.scale, .006, 12)});
|
||||
autoFit = false;
|
||||
} else {
|
||||
autoFit = true;
|
||||
}
|
||||
schedule();
|
||||
},
|
||||
focus(id) {
|
||||
const item = points.find(point => point.key === id);
|
||||
if (!item) return;
|
||||
view.x = item.row.x;
|
||||
view.z = item.row.z;
|
||||
onView({...view});
|
||||
schedule();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/* Cache only the public, versioned application shell. API responses are never cached. */
|
||||
const CACHE = 'airdef-shell-v7';
|
||||
const FILES = ['index.html', 'app.css', 'app.js', 'map.js', 'manifest.webmanifest', 'icons/icon-192.png', 'icons/icon-512.png'];
|
||||
const scope = new URL(self.registration.scope);
|
||||
const shellUrls = FILES.map(path => new URL(path, scope).href);
|
||||
|
||||
self.addEventListener('install', event => {
|
||||
event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(shellUrls)).then(() => self.skipWaiting()));
|
||||
});
|
||||
self.addEventListener('activate', event => {
|
||||
event.waitUntil(caches.keys().then(keys => Promise.all(keys.filter(key => key.startsWith('airdef-shell-') && key !== CACHE).map(key => caches.delete(key)))).then(() => self.clients.claim()));
|
||||
});
|
||||
self.addEventListener('fetch', event => {
|
||||
const request = event.request;
|
||||
const url = new URL(request.url);
|
||||
if (request.method !== 'GET' || url.origin !== scope.origin || url.search ||
|
||||
!url.pathname.startsWith(scope.pathname) || /(^|\/)api(?:\/|$)/.test(url.pathname)) return;
|
||||
if (request.mode === 'navigate' && (url.pathname === scope.pathname || url.pathname === new URL('index.html', scope).pathname)) {
|
||||
event.respondWith(caches.match(new URL('index.html', scope).href).then(cached => cached || fetch(request)));
|
||||
} else if (shellUrls.includes(url.href)) {
|
||||
event.respondWith(caches.match(request).then(cached => cached || fetch(request)));
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user