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
+90 -30
View File
@@ -1,4 +1,6 @@
"""Single local game bridge. HTTP clients only see cached projections and the archive."""
from collections import deque
from dataclasses import dataclass, replace
import json
import os
import queue
@@ -12,6 +14,8 @@ from pathlib import Path
TOKEN = re.compile(r"[0-9a-f]{16,32}\Z")
MAX_PACKET = 1 << 20
MAX_REPLY = 1 << 18
MAP_LAYERS = ("units", "objects", "contacts", "interceptors")
LIVE_REVISIONS = 12
def local_chat(endpoint: Path, text: str):
@@ -87,6 +91,68 @@ def public_view(raw):
}
def changed_fields(before, after):
change = {}
fields = {key: value for key, value in after.items() if key not in before or before[key] != value}
if fields:
change["set"] = fields
removed = [key for key in before if key not in after]
if removed:
change["unset"] = removed
return change
def live_delta(before, after):
old_frame, new_frame = before["frame"], after["frame"]
fields = changed_fields({k: v for k, v in before.items() if k not in {"frame", "revision"}},
{k: v for k, v in after.items() if k not in {"frame", "revision"}})
frame = changed_fields({k: v for k, v in old_frame.items() if k not in MAP_LAYERS},
{k: v for k, v in new_frame.items() if k not in MAP_LAYERS})
layers = {}
for key in MAP_LAYERS:
old = {row["id"]: row for row in old_frame[key]}
new = {row["id"]: row for row in new_frame[key]}
upsert = [row for ident, row in new.items() if ident not in old or old[ident] != row]
removed = [ident for ident in old if ident not in new]
natural_order = [ident for ident in old if ident in new] + [ident for ident in new if ident not in old]
changes = {}
if upsert:
changes["upsert"] = upsert
if removed:
changes["remove"] = removed
if natural_order != list(new):
changes["order"] = list(new)
if changes:
layers[key] = changes
if layers:
frame["layers"] = layers
return {"base": before["revision"], "revision": after["revision"], "change": fields, "frameChange": frame}
@dataclass(frozen=True)
class LiveRevision:
number: int
network: dict
enemy: object = None
truth: object = None
connected: bool = False
updated: object = None
def project(self, epoch, mode, launch):
result = dict(self.network)
result.update({
"revision": f"{epoch}-{self.number}-{mode}", "connected": self.connected,
"updated": self.updated, "perspective": mode,
"canLaunch": launch and self.connected and mode == "network" and result.get("canLaunch", False),
})
if mode == "enemy":
result["frame"] = self.enemy
result.pop("selected", None)
if mode == "truth":
result["frame"] = dict(result.get("frame") or {}, contacts=self.truth or [])
return result
class Bridge:
def __init__(self, endpoint, data, store, *, debug=False, interval=1.0, transport=local_chat):
self.endpoint, self.data, self.store = endpoint, data, store
@@ -94,11 +160,7 @@ class Bridge:
self.lock = threading.Lock()
self.stop = threading.Event()
self.queue = queue.Queue(maxsize=8)
self.snapshot = None
self.raw_enemy, self.raw_truth = None, None
self.connected = False
self.updated = None
self.revision = 0
self.revisions = deque([LiveRevision(0, {})], maxlen=LIVE_REVISIONS)
self.epoch = secrets.token_hex(8)
self.cursors = {}
self.thread = threading.Thread(target=self.worker, name="airdef-local-bridge", daemon=True)
@@ -122,10 +184,7 @@ class Bridge:
backoff = self.interval
except (OSError, ValueError, TypeError, KeyError):
backoff = min(4.0, backoff * 1.5)
with self.lock:
if self.connected:
self.connected = False
self.revision += 1
self.disconnect()
next_poll = time.monotonic() + backoff
try:
job = self.queue.get(timeout=min(0.25, self.interval))
@@ -136,8 +195,8 @@ class Bridge:
def poll(self):
nonce = secrets.token_hex(12)
mode = "debug" if self.debug else "public"
epoch = self.snapshot["session"] if self.snapshot else "-"
cursor = epoch + ":" + ",".join(".".join(map(str, [raid, *indices])) for raid, indices in self.cursors.items())
session = self.revisions[-1].network.get("session", "-")
cursor = session + ":" + ",".join(".".join(map(str, [raid, *indices])) for raid, indices in self.cursors.items())
self.transport(self.endpoint, f"chat /airdef panel snapshot {nonce} {mode} {cursor}")
raw = read_json(self.data / "panel-snapshot-v1.json")
if raw.get("nonce") != nonce or raw.get("version") != 1 or not TOKEN.fullmatch(raw["session"]):
@@ -146,27 +205,28 @@ class Bridge:
self.store.append(raw, public)
self.cursors = {raid["id"]: raid["next"] for raid in raw["raids"]}
with self.lock:
self.snapshot = public
self.raw_enemy, self.raw_truth = raw.get("enemy"), raw.get("truth")
self.connected = True
self.updated = time.time()
self.revision += 1
number = self.revisions[-1].number + 1
self.revisions.append(LiveRevision(number, public, raw.get("enemy"), raw.get("truth"), True, time.time()))
def view(self, mode):
def disconnect(self):
with self.lock:
result = dict(self.snapshot or {})
connected = self.connected
result.update({
"revision": f"{self.epoch}-{self.revision}", "connected": connected,
"updated": self.updated, "perspective": mode,
"canLaunch": connected and mode == "network" and result.get("canLaunch", False),
})
if mode == "enemy":
result["frame"] = self.raw_enemy
result.pop("selected", None)
if mode == "truth":
result["frame"] = dict(result.get("frame") or {}, contacts=self.raw_truth or [])
return result
current = self.revisions[-1]
if current.connected:
self.revisions.append(replace(current, number=current.number + 1, connected=False))
def view(self, mode, *, after=None, delta=False, launch=True):
with self.lock:
current = self.revisions[-1]
previous = next((entry for entry in self.revisions
if after == f"{self.epoch}-{entry.number}-{mode}"), None) if after else None
if previous is current:
return None
result = current.project(self.epoch, mode, launch)
if delta and previous and previous.network.get("session") == result.get("session"):
base = previous.project(self.epoch, mode, launch)
if result.get("session") and base.get("frame") is not None and result.get("frame") is not None:
return live_delta(base, result)
return result
def submit(self, key, owner, session, payload):
state = self.view("network")
+10 -3
View File
@@ -26,6 +26,8 @@ ASSETS = {
"/index.html": ("index.html", "text/html; charset=utf-8"),
"/app.js": ("app.js", "text/javascript; charset=utf-8"),
"/map.js": ("map.js", "text/javascript; charset=utf-8"),
"/live.js": ("live.js", "text/javascript; charset=utf-8"),
"/timeline.js": ("timeline.js", "text/javascript; charset=utf-8"),
"/app.css": ("app.css", "text/css; charset=utf-8"),
"/sw.js": ("sw.js", "text/javascript; charset=utf-8"),
"/manifest.webmanifest": ("manifest.webmanifest", "application/manifest+json"),
@@ -193,13 +195,18 @@ class Handler(BaseHTTPRequestHandler):
raise ValueError("bad perspective")
if mode != "network" and not debug:
raise APIError(HTTPStatus.FORBIDDEN, "Этот ракурс требует отдельного доступа")
data = self.server.bridge.view(mode)
data["canLaunch"] = data["canLaunch"] and launch
if query.get("after") == data["revision"]:
data = self.server.bridge.view(mode, after=query.get("after"), delta=query.get("delta") == "1", launch=launch)
if data is None:
return self.reply(HTTPStatus.NO_CONTENT)
return self.reply(HTTPStatus.OK, data)
if (verb, path) == ("GET", "/api/raids"):
return self.reply(HTTPStatus.OK, self.server.store.raids())
if (verb, path) == ("GET", "/api/timeline"):
session, raid = query.get("session", ""), number(query.get("raid"))
if not TOKEN.fullmatch(session) or raid is None:
raise ValueError("bad timeline")
data = self.server.store.timeline(session, raid, after=query.get("after"))
return self.reply(HTTPStatus.NO_CONTENT) if data is None else self.reply(HTTPStatus.OK, data)
if (verb, path) == ("GET", "/api/chain"):
result = self.server.store.chain(number(query.get("event")))
if result is None:
+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});
}
},
};
}
+34
View File
@@ -12,7 +12,16 @@ MAX_FRAMES = 3600
MAX_FRAME_DISTANCE_TICKS = 100
MAX_EVENTS = 30000
MAX_RAIDS = 400
MAX_TIMELINE_MARKERS = 480
SESSION_AGE = 30 * 24 * 60 * 60
TIMELINE_LABELS = {
"Попадание по объекту": "impact", "Попадание по комплексу": "impact", "Комплекс уничтожен": "impact",
"Промах перехватчика": "miss", "Промах очереди": "miss",
"Огонь запрещён": "refusal", "Комплекс на марше": "refusal", "Перезарядка": "refusal",
"Ожидает пополнения": "refusal", "Ожидает данных о рельефе": "refusal", "Траектория перекрыта": "refusal",
"Орудие недоступно": "refusal", "Пусковая недоступна": "refusal", "Нет свежего захвата": "refusal",
"Вне дальности орудия": "refusal",
}
def compact(value):
@@ -184,6 +193,31 @@ class Store:
"context": context, "limited": len(rows) > 40,
}
def timeline(self, session, raid, after=None):
placeholders = ",".join("?" for _ in TIMELINE_LABELS)
matching = f"FROM events WHERE session=? AND raid=? AND label IN ({placeholders})"
args = (session, raid, *TIMELINE_LABELS)
with self.lock:
count, last = self.db.execute(f"SELECT count(*), coalesce(max(id), 0) {matching}", args).fetchone()
revision = f"{count}:{last}"
if after == revision:
return None
rows = self.db.execute(f"SELECT * {matching} ORDER BY tick, id", args).fetchall()
markers = []
for marker in ("impact", "miss", "refusal"):
candidates = [row for row in rows if TIMELINE_LABELS[row["label"]] == marker]
available = MAX_TIMELINE_MARKERS - len(markers)
if not available:
break
if len(candidates) > available:
if available == 1:
candidates = candidates[-1:]
else:
candidates = [candidates[i * (len(candidates) - 1) // (available - 1)] for i in range(available)]
markers.extend(dict(event_row(row), marker=marker) for row in candidates)
markers.sort(key=lambda event: (event["tick"], event["id"]))
return {"events": markers, "limited": len(markers) < len(rows), "revision": revision}
def frame(self, session, tick):
with self.lock:
before = self.db.execute("""SELECT data, tick FROM frames