feat: show what each backup is doing as a light that moves like a rocket

Replace the single-shot meteor with a per-orbit activity system. A backup's state
is read from how a small glowing triangle moves, not from a drawing of a rocket.

- Events come from status changes between polls, so scheduled backups animate
  too. A click shows its own verdict until a poll that began after it has landed,
  which keeps one backup from being animated twice or flipping through a stale
  status. Loading the page only sets a baseline and never replays history.
- Queued waits on its star. Running circles it, climbing and spinning up.
- Success waits for a launch window, where the light's own motion already carries
  it round the black hole, then departs with that velocity. It falls under a
  pseudo-Newtonian pull after a burn that trims angular momentum to just under
  the capture limit, so the path spirals with the orbits, always arrives, and
  never slows on the way in. Near the shadow it reddens, dims and stretches, and
  the disk spins up as it feeds.
- Failure explodes in place or, when the hub says the transfer failed, launches,
  loses power and falls back. The star keeps its busy look until the outcome and
  then turns red. Rehearsal is a faint dashed light that lands on its star.
- Position and velocity are integrated and a mode change only swaps forces, so
  every transition is continuous and interruptible. Parameters use the shared
  spring tokens. Trails follow the path actually flown.
- At most ten lights are drawn; reduced motion draws none and shows outcomes at once.
- Pure modules with tests for activity, physics and trails. The Playwright capture
  script now checks lights by data-orbit. The animation guideline in docs/UI.md
  describes the simulation approach in place of the old single progress value.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 23:04:25 +07:00
parent d0f22c4ad0
commit 8b6efe1eaa
16 changed files with 1571 additions and 143 deletions

View File

@@ -1,18 +1,21 @@
import { useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { animate, motion, spring, useMotionValue, useTransform, type MotionStyle, type MotionValue } from "motion/react";
import { animate, motion, useMotionValue, useTransform, type MotionStyle, type MotionValue } from "motion/react";
import type { Orbit, Snapshot } from "../../api";
import { orbitStatus } from "../../lib/format";
import { LABEL_HEIGHT, placeLabels, type Rect } from "../../lib/galaxyLabelLayout";
import {
assignOrbitSlots, CAPTURE_HIGHLIGHT_START, capturePhases, moonPoses, orbitCapacity, orbitPose, orbitRadii, ORBIT_TILT,
SCENE_HEIGHT, SCENE_WIDTH, spiralPoint, trailAngle, type Vec2,
assignOrbitSlots, moonPoses, orbitCapacity, orbitPose, orbitRadii, ORBIT_TILT,
SCENE_HEIGHT, SCENE_WIDTH, trailAngle, type Vec2,
} from "../../lib/galaxyLayout";
import { useGalaxyMotion } from "../../hooks/useGalaxyMotion";
import { useScreenTransition } from "../../hooks/useScreenTransition";
import { ambientSpring, gentleSpring, uiSpring } from "../../lib/motion";
import { gentleSpring, uiSpring } from "../../lib/motion";
import { VaultCore } from "./VaultCore";
import type { CoreSignal } from "../../lib/blackhole/controller";
import { SCENE_UNITS_PER_M } from "../../lib/blackhole/layout";
import { createActivity, observeStatuses, type FailureCause } from "../../lib/orbitActivity";
import { applyActivity, createField, fieldActive, starPose, stepField, type FieldEvent } from "../../lib/rocket";
import { RocketSprites, createSpriteRefs, paintSprites } from "./RocketSprites";
export type CaptureEffect = { orbitId: string; key: number; snapshotId?: string };
@@ -28,6 +31,8 @@ type Props = {
signal: CoreSignal;
svgCore: boolean;
captureReady: boolean;
/** Why a backup failed, for orbits where the hub can tell. Picks between an explosion and a fall. */
resolveFailure?: (orbit: Orbit) => Promise<FailureCause>;
onSelectOrbit: (id: string) => void;
onSelectSnapshot: (id: string) => void;
};
@@ -38,41 +43,51 @@ const labelFont = "500 11px ui-monospace, monospace";
const MAX_LABELS = 12;
const clamp = (value: number) => Math.max(0, Math.min(1, value));
const ACCRETION_SECONDS = 6.4;
const TRAIL_WIDTHS = [0.8, 1.4, 2.3];
/** Star colour by status: cool mint when healthy, amber while working, ember red when failed. */
/** Glow falloff, close to a gaussian so there is no visible edge. */
const GLOW_STOPS: [number, number][] = [[0, 0.9], [0.06, 0.6], [0.14, 0.34], [0.26, 0.14], [0.42, 0.045], [0.65, 0.01], [1, 0]];
/** Star colour by status: cool mint when healthy, amber while working, ember red when failed. */
/** A diffraction spike: a thin diamond that tapers to nothing at both ends. */
const SPIKE = "M-14 0 L0 -.7 L14 0 L0 .7Z";
const STAR_TONES: [string, string][] = [["green", "#b4efd9"], ["amber", "#f2bc80"], ["red", "#ff9484"], ["grey", "#cdd3dc"]];
type Body = {
id: string; index: number; x: number; y: number; look: number; kind: "calm" | "busy" | "failed";
trail?: SVGGElement | null; life?: SVGGElement | null;
};
/** A stable number per orbit, so its rocket always scatters the same way. */
function seedOf(id: string) {
let value = 7;
for (const char of id) value = (value * 31 + char.charCodeAt(0)) % 997;
return value + 1;
}
/** How long a star keeps looking busy while waiting for its rocket's outcome, at most. */
const HOLD_LIMIT_MS = 8000;
export function BlackholeGalaxy({
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, bigScreen, captureEffect, captureGlow, signal, svgCore, captureReady, onSelectOrbit, onSelectSnapshot,
orbits, selectedOrbitId, recentSnapshots, flowing, reducedMotion, bigScreen, captureEffect, captureGlow, signal, svgCore, captureReady, resolveFailure, onSelectOrbit, onSelectSnapshot,
}: Props) {
const frame = useRef<HTMLDivElement>(null);
const bodyNodes = useRef(new Map<SVGGElement, {
id: string; index: number; x: number; y: number; look: number; kind: "calm" | "busy" | "failed";
trail?: SVGGElement | null; life?: SVGGElement | null;
}>());
const bodyNodes = useRef(new Map<SVGGElement, Body>());
const bodyState = useRef(new WeakMap<SVGGElement, Body>());
const ambient = useRef(0);
const ringNodes = useRef(new Map<number, SVGEllipseElement>());
const slotsBefore = useRef<ReturnType<typeof assignOrbitSlots>>(undefined);
const elapsed = useRef(0);
const entrance = useRef(0);
const core = useRef<SVGGElement>(null);
const capture = useRef<{ event: CaptureEffect; time: number; source: Vec2; progress: ReturnType<typeof spring>; done: boolean; waiting: boolean }>(undefined);
const skippedCapture = useRef<CaptureEffect>(undefined);
const sourceFlare = useRef<SVGCircleElement>(null);
const field = useRef(createField());
const activity = useRef(createActivity());
const sprites = useRef(createSpriteRefs());
const highlight = useRef<{ effect: CaptureEffect; armed: boolean; played: boolean }>(undefined);
const [held, setHeld] = useState<ReadonlySet<string>>(new Set());
const shownStatus = (orbit: Orbit) => (held.has(orbit.id) ? "running" : orbit.last_status);
const busyAngle = useRef(0);
const diskTime = useRef(0);
const hasRunning = orbits.some(orbit => orbitStatus(orbit.last_status).busy);
const trailId = useId();
const hasRunning = orbits.some(orbit => orbitStatus(shownStatus(orbit)).busy);
const knockoutId = useId();
const starId = useId();
const trail = useRef<SVGPathElement>(null);
const trailSegments = useRef<(SVGUseElement | null)[]>([]);
const head = useRef<SVGCircleElement>(null);
const effect = useRef<SVGGElement>(null);
const [width, setWidth] = useState(0);
const [coasting, setCoasting] = useState(false);
const rate = useMotionValue(flowing && !reducedMotion ? 1 : 0);
@@ -142,7 +157,83 @@ export function BlackholeGalaxy({
}
}, [moving, reducedMotion, selectedX, selectedY, selectionX, selectionY]);
useGalaxyMotion((delta) => {
// Holding a star's busy look until its outcome plays out means it turns red at the explosion and green on arrival,
// not the moment the status changes.
const movingNow = useRef(moving);
movingNow.current = moving;
const hold = (id: string) => {
setHeld((current) => (current.has(id) ? current : new Set(current).add(id)));
window.setTimeout(() => release(id), HOLD_LIMIT_MS);
};
const release = (id: string) => {
setHeld((current) => {
if (!current.has(id)) return current;
const next = new Set(current);
next.delete(id);
return next;
});
};
const outcome = (event: FieldEvent) => {
if (event.kind === "arrive") {
release(event.id);
const light = highlight.current;
if (light && light.effect.orbitId === event.id) light.armed = true;
} else if (event.kind === "boom" || event.kind === "landed") {
release(event.id);
}
};
// What the backups are doing decides what the rockets do. This runs before the loop is (re)started below.
useLayoutEffect(() => {
if (reducedMotion) {
field.current = createField();
activity.current = createActivity();
setHeld((current) => (current.size ? new Set() : current));
return;
}
const statuses = new Map(orbits.map((orbit) => [orbit.id, orbit.last_status]));
for (const event of observeStatuses(activity.current, statuses)) {
const slot = slots.get(event.id);
if (!slot) continue;
const orbit = orbits.find(({ id }) => id === event.id);
const now = () => starPose(slot, elapsed.current, movingNow.current ? Math.max(0, rate.get()) : 0);
if (event.kind === "fail" && orbit?.application_id && resolveFailure) {
// The hub can say whether the backup failed before it left or while it was transferring. Wait briefly for it.
hold(event.id);
void Promise.race([
resolveFailure(orbit),
new Promise<FailureCause>((done) => window.setTimeout(() => done("unknown"), 700)),
]).catch((): FailureCause => "unknown").then((cause) => {
if (!applyActivity(field.current, { ...event, cause }, now(), seedOf(event.id))) release(event.id);
wake();
});
continue;
}
if (event.kind === "launch" || event.kind === "fail") hold(event.id);
if (!applyActivity(field.current, event, now(), seedOf(event.id))) release(event.id);
}
}, [orbits, slots, reducedMotion]);
// A click-started capture arms its snapshot flash. It plays once the rocket arrives and the snapshot is listed, or
// after a few seconds if the rocket never flew, for example when there was no room for another one.
useLayoutEffect(() => {
captureGlow.stop();
captureGlow.set(0);
if (!captureEffect?.snapshotId || reducedMotion) {
highlight.current = undefined;
return;
}
const entry = { effect: captureEffect, armed: false, played: false };
highlight.current = entry;
const timer = window.setTimeout(() => {
if (highlight.current !== entry || entry.played) return;
entry.armed = true;
wake();
}, 3500);
return () => window.clearTimeout(timer);
}, [captureEffect, captureGlow, reducedMotion]);
const wake = useGalaxyMotion((delta) => {
const speed = moving ? Math.max(0, rate.get()) : 0;
elapsed.current += delta * speed;
if (hasRunning && !reducedMotion && delta > 0) {
@@ -184,7 +275,8 @@ export function BlackholeGalaxy({
const phase = body.index * 2.399;
const wave = 0.6 * Math.sin(time * rate + phase) + 0.4 * Math.sin(time * rate * 2.3 + phase * 1.7);
const depth = body.kind === "busy" ? 0.16 : body.kind === "failed" ? 0.12 : 0.07;
body.life.setAttribute("transform", `scale(${1 + depth * wave})`);
const swell = field.current.pulses.get(body.id)?.value ?? 0;
body.life.setAttribute("transform", `scale(${(1 + depth * wave) * (1 + 0.7 * swell)})`);
body.life.setAttribute("opacity", String(1 - depth * 0.45 * (1 - wave)));
}
}
@@ -193,62 +285,24 @@ export function BlackholeGalaxy({
selectionX.jump(point.x);
selectionY.jump(point.y);
}
if (reducedMotion) skippedCapture.current = captureEffect;
const event = captureEffect === skippedCapture.current ? undefined : captureEffect;
const slot = event && slots.get(event.orbitId);
if (event && slot && capture.current?.event !== event) {
captureGlow.set(0);
effect.current?.setAttribute("opacity", "0");
const source = orbitPose(slot, elapsed.current);
capture.current = {
event, source, time: 0, done: false, waiting: false,
progress: spring({ ...ambientSpring, keyframes: [0, 1], restDelta: 0.002 }),
};
if (event.snapshotId) {
const points = Array.from({ length: 36 }, (_, i) => spiralPoint(source, i / 35));
trail.current?.setAttribute("d", points.map(({ x, y }, i) => `${i ? "L" : "M"} ${x} ${y}`).join(" "));
}
}
const current = capture.current;
// Rockets. The field integrates each rocket's position and velocity, then the sprites are placed to match.
// Nothing is keyframed, so any outcome can interrupt any other and the motion stays continuous.
let absorption = 0;
let capturing = false;
if (event && current?.event === event && !current.done) {
// The impact can finish while the snapshot list is still refreshing.
if (!current.waiting || captureReady) current.time += delta * 1000;
const { value, done } = current.progress.next(current.time);
const success = !!event.snapshotId;
current.waiting = success && !captureReady && value >= CAPTURE_HIGHLIGHT_START;
const progress = current.waiting ? CAPTURE_HIGHLIGHT_START : done ? 1 : value;
const phases = capturePhases(progress);
current.done = done && !current.waiting;
const source = slot ? orbitPose(slot, elapsed.current) : current.source;
const pulse = success ? phases.flare : phases.failure;
sourceFlare.current?.setAttribute("cx", String(source.x));
sourceFlare.current?.setAttribute("cy", String(source.y));
sourceFlare.current?.setAttribute("r", String(7 + 13 * clamp(value)));
sourceFlare.current?.setAttribute("stroke", success ? "#ffd3a5" : "#f59183");
sourceFlare.current?.setAttribute("opacity", String(0.75 * pulse));
if (success) {
const { x, y } = spiralPoint(current.source, phases.flight);
head.current?.setAttribute("cx", String(x));
head.current?.setAttribute("cy", String(y));
head.current?.setAttribute("r", String(3.5 * (1 - phases.flight ** 4)));
const segmentLength = Math.min(phases.flight, 0.19) * (1 - phases.flight ** 6) / TRAIL_WIDTHS.length;
trailSegments.current.forEach((segment, index) => {
segment?.setAttribute("stroke-dasharray", `${segmentLength} 1`);
segment?.setAttribute("stroke-dashoffset", String((TRAIL_WIDTHS.length - index) * segmentLength - phases.flight));
});
effect.current?.setAttribute("opacity", String(clamp(phases.flight * 14) * (1 - phases.flight ** 8)));
absorption = phases.absorption;
captureGlow.set(phases.highlight);
}
capturing = !current.done && !current.waiting;
} else {
sourceFlare.current?.setAttribute("opacity", "0");
effect.current?.setAttribute("opacity", "0");
captureGlow.set(0);
if (!reducedMotion) {
const dt = Math.min(delta, 0.05);
const starOf = (id: string) => {
const slot = slots.get(id);
return slot ? starPose(slot, elapsed.current, speed) : undefined;
};
if (dt > 0) for (const event of stepField(field.current, dt, starOf)) outcome(event);
paintSprites(sprites.current, field.current, { starOf, lookAt: signal.lookAt, time: ambient.current, dt });
absorption = Math.max(0, field.current.absorption.value);
}
// The snapshot flash waits for the rocket to arrive and for the confirmed snapshot to show up in the list.
const light = highlight.current;
if (light?.armed && !light.played && captureReady) {
light.played = true;
animate(captureGlow, 1, { ...uiSpring, onComplete: () => { animate(captureGlow, 0, gentleSpring); } });
}
if (delta > 0 && (speed || absorption)) {
@@ -265,7 +319,7 @@ export function BlackholeGalaxy({
if (coreStyle && (absorption || coreStyle.getPropertyValue("--capture-absorption") !== "0")) {
coreStyle.setProperty("--capture-absorption", String(absorption));
}
return moving || entering || capturing || (hasRunning && !reducedMotion);
return moving || entering || fieldActive(field.current) || (hasRunning && !reducedMotion);
});
// The overlay follows the radar wave: each marker and ring takes the look at its own distance from the hole, so
@@ -302,7 +356,7 @@ export function BlackholeGalaxy({
const visible = orbits.filter(({ id }) => slots.has(id));
const byPriority = (orbit: Orbit) =>
orbit.id === selectedOrbitId ? 0 : orbit.last_status === "failed" ? 1 : orbitStatus(orbit.last_status).busy ? 2 : 3;
orbit.id === selectedOrbitId ? 0 : shownStatus(orbit) === "failed" ? 1 : orbitStatus(shownStatus(orbit)).busy ? 2 : 3;
const labelCandidates = [...visible].sort((a, b) => byPriority(a) - byPriority(b))
.filter((orbit) => width >= 530 || orbit.id === selectedOrbitId)
.slice(0, MAX_LABELS);
@@ -330,14 +384,18 @@ export function BlackholeGalaxy({
const renderOrbits = visible.map((orbit, index) => {
const selected = orbit.id === selectedOrbitId;
const status = orbitStatus(orbit.last_status);
const status = orbitStatus(shownStatus(orbit));
const radius = slots.get(orbit.id)?.radius;
return (
<motion.g
key={orbit.id}
ref={(node) => {
if (!node) return;
bodyNodes.current.set(node, { id: orbit.id, index, x: 0, y: 0, look: 0, kind: status.tone === "red" ? "failed" : status.busy ? "busy" : "calm" });
// The per-node state outlives re-renders, so a marker keeps its position and look between them.
const body = bodyState.current.get(node) ?? { id: orbit.id, index, x: 0, y: 0, look: 0, kind: "calm" as const };
Object.assign(body, { id: orbit.id, index, kind: status.tone === "red" ? "failed" : status.busy ? "busy" : "calm" });
bodyState.current.set(node, body);
bodyNodes.current.set(node, body);
return () => { bodyNodes.current.delete(node); };
}}
initial={false}
@@ -457,15 +515,7 @@ export function BlackholeGalaxy({
/>
)}
</g>
<circle ref={sourceFlare} className="capture-flare" opacity="0" pointerEvents="none" fill="none" />
<g ref={effect} className="capture-arrival" opacity="0" pointerEvents="none">
<defs><path id={trailId} ref={trail} pathLength="1" /></defs>
{TRAIL_WIDTHS.map((strokeWidth, index) => (
<use key={strokeWidth} ref={node => { trailSegments.current[index] = node; }}
href={`#${trailId}`} fill="none" strokeWidth={strokeWidth} opacity={0.35 + index * 0.3} />
))}
<circle ref={head} r="3.5" />
</g>
<RocketSprites refs={sprites.current} />
</svg>
<div aria-hidden="true" className="scene-labels" style={{ font: labelFont }}>
{labels.map(({ id, x, y, width: labelWidth }, index) => (