primordial-soup/viewer/replay.js

90 lines
2.6 KiB
JavaScript

import { replayFrames } from "../engine/index.js";
import { applyReplayChange } from "../engine/replay-view.js";
/** BGS owns the controls; the viewer owns the displayed historical position. */
export function createReplay({
render,
setReplayMode,
fetchLog,
setReplayInfo,
}) {
let latest, packet, requestedEnd, cursor;
let active = false;
const length = () => latest?.historyLength ?? latest?.history?.length ?? 0;
const cachedEnd = () => (packet ? packet.start + packet.steps.length : -1);
function show() {
if (!active || !latest) return;
if (packet && cursor >= packet.start && cursor <= cachedEnd()) {
let state = packet.state;
for (let i = 0; i < cursor - packet.start; i++)
state = applyReplayChange(state, packet.steps[i]);
render(state);
} else if (length() === 0) {
render(latest);
} else {
render({ ...latest, replayLoading: true });
}
setReplayInfo({ start: 0, current: cursor, end: length() });
}
function load() {
const end = length();
if (!latest || end === 0 || cachedEnd() >= cursor || requestedEnd === end)
return;
// BGS provides raw saved data for ended/cancelled games. Reconstruct those
// locally; ongoing games fetch only server-filtered public replay packets.
if (Array.isArray(latest.history) && typeof latest._seed === "string") {
packet = replayFrames(latest);
return;
}
requestedEnd = end;
fetchLog({ start: 0, end: end - 1 });
}
return {
get active() {
return active;
},
update(state) {
latest = state;
if (!active) {
render(state);
return;
}
cursor = Math.min(cursor ?? length(), length());
load();
show();
},
receive(data) {
if (!data?.replay) return false;
const incoming = data.replay;
if (incoming.start === 0 && incoming.steps.length >= cachedEnd())
packet = incoming;
if (cachedEnd() >= requestedEnd) requestedEnd = undefined;
// A delayed response may fill the cache after leaving replay, but must
// never repaint the live board or reopen BGS's controls.
show();
return true;
},
start() {
active = true;
cursor = latest ? length() : undefined;
setReplayMode(true);
load();
show();
},
to(position) {
if (!active || !Number.isInteger(position)) return;
cursor = Math.min(length(), Math.max(0, position));
load();
show();
},
end() {
active = false;
requestedEnd = undefined;
setReplayMode(false);
if (latest) render(latest);
},
};
}