Add battle timeline markers and incremental web map updates (#153)
build / mod (push) Successful in 30m14s

This commit is contained in:
2026-12-02 11:54:02 +03:00
parent 906159b17f
commit 9e0cec13f2
11 changed files with 470 additions and 70 deletions
+13
View File
@@ -103,3 +103,16 @@ dialog::backdrop { background: #02080dc9; }
#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); } }
.timeline-marker-rail { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: .1rem; }
.timeline-marker-slot { display: flex; justify-content: center; min-width: 0; }
.timeline-marker { min-width: 44px; padding: .25rem; border-color: #526977; font-size: .9rem; }
.timeline-marker[data-type="impact"] { color: var(--danger); }
.timeline-marker[data-type="refusal"] { color: var(--warning); }
.timeline-marker[data-type="miss"] { color: #b7c8fa; }
.timeline-marker[data-type="mixed"] { color: var(--accent); }
.timeline-marker.selected, .timeline-marker[aria-expanded="true"] { border-color: var(--accent); background: #193b40; }
.timeline-marker-details:not(:empty) { display: grid; gap: .35rem; max-height: 220px; overflow-y: auto; margin-top: .4rem; }
.timeline-marker-heading { margin: 0; font-size: .8rem; }
.timeline-marker-choice { text-align: left; font-size: .82rem; overflow-wrap: anywhere; }
.timeline-marker-choice[aria-current="true"] { border-color: var(--accent); }
+135 -28
View File
@@ -1,4 +1,6 @@
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) => {
@@ -76,12 +78,16 @@ let selected = prefs.selected, connected = false, http = false, polling = false,
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 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 => {
if (historical) return;
prefs.views[perspective] = view;
write("view", prefs);
},
@@ -110,9 +116,10 @@ function showAuth() {
}
function updateStatus() {
const status = $("connection");
const updated = live?.updated ?? network?.updated;
status.className = connected ? "success" : "warning";
status.textContent = connected ? `Игра в сети · ${when(live?.updated)}`
: auth ? live?.updated ? `Нет связи · снимок от ${when(live.updated)}` : "Ожидание игры"
: auth ? updated ? `Нет связи · снимок от ${when(updated)}` : "Ожидание игры"
: http ? "Ожидает подключения" : "Нет соединения";
$("logout").disabled = !http;
}
@@ -133,6 +140,7 @@ function draw() {
const frame = activeFrame();
map.draw(frame, {selected, layers: prefs.layers});
$("return-live").hidden = !historical;
$("history-live").hidden = !historical;
$("perspective").disabled = !!historical;
const status = [];
if (historical) {
@@ -241,6 +249,11 @@ async function updateObjectEvent(opened) {
}
function forgetCachedData() {
clearTimeout(frameTimer);
clearTimeout(eventTimer);
frameGeneration++;
historyGeneration++;
clearEvent();
cache("all", null);
network = live = historical = null;
connected = false;
@@ -248,12 +261,14 @@ function forgetCachedData() {
offlineEvents = [];
offlineFrames = {};
offlineRaids = {raids: []};
offlineTimelines = {};
timelineGeneration++;
timelineRequests.clear();
events = [];
raids = [];
raid = null;
latestRequest = null;
write("launch-request", null);
$("event-card").hidden = true;
}
async function poll() {
@@ -267,20 +282,30 @@ async function poll() {
showAuth();
}
const mode = perspective;
const params = new URLSearchParams({mode});
if (live?.perspective === mode) params.set("after", live.revision || "");
const data = await api(`/live?${params}`);
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 (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.selected = null;
delete prefs.views.network;
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);
}
@@ -293,7 +318,11 @@ async function poll() {
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) {
@@ -325,39 +354,56 @@ function setTab(next) {
$("history-panel").hidden = next !== "history";
$("scenario-panel").hidden = next !== "scenario";
if (next === "history") {
refreshRaids().then(() => readEvents());
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)}` : "";
$("event-card").hidden = true;
$("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[perspective]);
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 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}`));
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 : "";
}
$("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;
@@ -365,6 +411,51 @@ async function refreshRaids() {
$("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) {
@@ -440,9 +531,12 @@ function renderEvents(saved) {
() => 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)];
@@ -462,21 +556,25 @@ async function openEvent(event) {
$("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), showChain(event, chainRequest)]);
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 = {
@@ -503,7 +601,7 @@ async function showChain(event, generation) {
}
card.append(items);
}
async function loadFrame(session, tick, start) {
async function loadFrame(session, tick, start, focus = false) {
const generation = ++frameGeneration;
const key = `${session}:${tick}`;
let scene;
@@ -526,7 +624,7 @@ async function loadFrame(session, tick, start) {
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);
if (focus && selected) map.focus(selected);
}
function setupScenario() {
@@ -677,22 +775,30 @@ $("perspective").addEventListener("change", () => {
draw();
poll();
});
$("return-live").addEventListener("click", () => {
function returnLive() {
clearTimeout(frameTimer);
clearEvent();
frameGeneration++;
historical = null;
selected = prefs.selected;
perspective = "network";
$("perspective").value = "network";
live = network;
map.restore(prefs.views.network);
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(() => {
@@ -739,12 +845,13 @@ $("install").addEventListener("click", async () => {
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)));
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;
+4 -1
View File
@@ -69,7 +69,11 @@
<h2>История боя</h2>
<label>Налёт<select id="raid"></select></label>
<label>Момент повтора<input type="range" id="timeline" min="0" max="0" value="0" disabled></label>
<div id="timeline-markers" aria-label="События на шкале повтора"></div>
<p id="timeline-status" class="muted" hidden></p>
<button id="history-live" type="button" hidden>К прямому эфиру</button>
<p id="timeline-caption" aria-live="polite" class="muted"></p>
<article id="event-card" class="subcard" hidden></article>
<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>
@@ -79,7 +83,6 @@
</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>
+20
View File
@@ -0,0 +1,20 @@
function mergeFields(base, change) {
const result = {...base, ...change.set};
for (const key of change.unset || []) delete result[key];
return result;
}
export function applyLiveUpdate(base, update) {
if (!Object.hasOwn(update, "base")) return update;
if (!base?.frame || update.base !== base.revision) return null;
const result = {...mergeFields(base, update.change), revision: update.revision};
result.frame = mergeFields(base.frame, update.frameChange);
for (const [layer, {remove = [], upsert = [], order}] of Object.entries(update.frameChange.layers || {})) {
const entities = new Map(base.frame[layer].map(row => [row.id, row]));
for (const id of remove) entities.delete(id);
for (const entity of upsert) entities.set(entity.id, entity);
result.frame[layer] = order ? order.map(id => entities.get(id)) : [...entities.values()];
}
return result;
}
+2 -2
View File
@@ -1,6 +1,6 @@
/* 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 CACHE = 'airdef-shell-v8';
const FILES = ['index.html', 'app.css', 'app.js', 'map.js', 'live.js', 'timeline.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);
+99
View File
@@ -0,0 +1,99 @@
// Markers are grouped into a small number of time buckets so every control
// remains large enough to tap, including on narrow screens.
const names = { impact: "Попадание", refusal: "Отказ", miss: "Промах" };
const symbols = {impact: "◆", miss: "×", refusal: "!"};
const refusalLabels = new Set([
"Огонь запрещён", "Комплекс на марше", "Перезарядка", "Ожидает пополнения",
"Ожидает данных о рельефе", "Траектория перекрыта",
"Орудие недоступно", "Пусковая недоступна", "Нет свежего захвата", "Вне дальности орудия",
]);
function markerType(event) {
if (Object.hasOwn(names, event.marker)) return event.marker;
const label = event.label || "";
if (label.startsWith("Попадание") || label === "Комплекс уничтожен") return "impact";
if (label.startsWith("Промах")) return "miss";
if (event.kind === "decisions" && refusalLabels.has(label)) return "refusal";
return null;
}
export function createTimeline(container, onOpen, clock) {
let expanded = null;
let raidKey = null;
let signature = "";
return {
render(raid, events, selectedId) {
const key = raid ? `${raid.session}:${raid.raid}` : null;
if (key !== raidKey) { expanded = null; raidKey = key; }
const buckets = Array.from({ length: 5 }, () => []);
for (const event of events) {
const type = markerType(event);
const at = event.data?.at;
if (!raid || !type || !Number.isFinite(at) || at < 0) continue;
// A terminal event can be a tick beyond the sampled replay length.
const slot = Math.min(4, Math.floor(at / Math.max(1, raid.length) * 5));
buckets[slot].push({ event, type, at });
}
const next = JSON.stringify([key, expanded, selectedId, buckets.map(bucket => bucket.map(item => item.event.id))]);
if (next === signature) return;
signature = next;
const focused = container.contains(document.activeElement) ? document.activeElement.dataset.markerFocus : null;
const oldScroll = container.querySelector(".timeline-marker-details")?.scrollTop ?? 0;
container.replaceChildren();
if (buckets.every(bucket => !bucket.length)) return;
const rail = document.createElement("div");
rail.className = "timeline-marker-rail";
rail.setAttribute("role", "group");
rail.setAttribute("aria-label", "Маркеры событий повтора");
const details = document.createElement("div");
details.className = "timeline-marker-details";
for (const [index, bucket] of buckets.entries()) {
const slot = document.createElement("div");
slot.className = "timeline-marker-slot";
rail.append(slot);
if (!bucket.length) continue;
bucket.sort((a, b) => a.at - b.at || a.event.id - b.event.id);
const button = document.createElement("button");
button.type = "button";
button.className = "timeline-marker";
button.dataset.markerFocus = `group-${index}`;
const types = [...new Set(bucket.map(item => item.type))];
button.dataset.type = types.length === 1 ? types[0] : "mixed";
const description = types.map(type => `${names[type]} × ${bucket.filter(item => item.type === type).length}`).join(", ");
const span = bucket.length === 1 ? clock(bucket[0].at) : `${clock(bucket[0].at)}–${clock(bucket.at(-1).at)}`;
button.setAttribute("aria-label", `${span} · ${description} · ${bucket.length === 1 ? bucket[0].event.label : `${bucket.length} событий`}`);
if (bucket.some(item => String(item.event.id) === String(selectedId))) button.classList.add("selected");
const primary = Object.keys(symbols).find(type => types.includes(type));
button.textContent = bucket.length === 1 ? symbols[primary] : `${symbols[primary]} ${bucket.length}`;
if (bucket.length > 1) button.setAttribute("aria-expanded", String(expanded === index));
button.addEventListener("click", () => {
if (bucket.length === 1) { onOpen(bucket[0].event); return; }
expanded = expanded === index ? null : index;
this.render(raid, events, selectedId);
});
slot.append(button);
if (expanded === index && bucket.length > 1) {
const heading = document.createElement("p");
heading.className = "muted timeline-marker-heading";
heading.textContent = `Событий в группе ${bucket.length}`;
details.append(heading);
for (const { event, at } of bucket) {
const choice = document.createElement("button");
choice.type = "button";
choice.className = "timeline-marker-choice";
choice.dataset.markerFocus = `event-${event.id}`;
choice.textContent = `${clock(at)} · ${event.label}`;
if (String(event.id) === String(selectedId)) choice.setAttribute("aria-current", "true");
choice.addEventListener("click", () => onOpen(event));
details.append(choice);
}
}
}
container.append(rail, details);
details.scrollTop = oldScroll;
if (focused) {
[...container.querySelectorAll("button")].find(node => node.dataset.markerFocus === focused)?.focus({preventScroll: true});
}
},
};
}