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
+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;