feat: rebuild the orbital vault as an operational map

This commit is contained in:
2026-11-09 22:01:14 +07:00
parent 2129e80c38
commit fba4a1e628
25 changed files with 1342 additions and 1333 deletions

View File

@@ -1,283 +1,203 @@
import { useEffect, useMemo, useRef, useState, type RefObject } from "react";
import type { Orbit } from "../../api";
import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { Orbit, Snapshot } from "../../api";
import { orbitStatus } from "../../lib/format";
import { LABEL_HEIGHT, placeLabels, type Rect } from "../../lib/galaxyLabelLayout";
import {
assignShells,
shellPose,
spiralPoint,
type Vec2,
assignOrbitSlots, moonPoses, orbitCapacity, orbitPose, orbitRadii, ORBIT_TILT,
SCENE_HEIGHT, SCENE_WIDTH, spiralPoint, type Vec2,
} from "../../lib/galaxyLayout";
import { useGalaxyTime } from "../../hooks/useGalaxyMotion";
import { useGalaxyMotion } from "../../hooks/useGalaxyMotion";
import { VaultCore } from "./VaultCore";
const METEOR_MS = 2600;
export type CaptureArrival = { orbitId: string; snapshotId: string };
function shorten(name: string) {
return name.length > 16 ? `${name.slice(0, 14)}…` : name;
}
type Props = {
orbits: Orbit[];
selectedOrbitId?: string;
recentSnapshots: Snapshot[];
flowing: boolean;
arrival?: CaptureArrival;
onSelectOrbit: (id: string) => void;
onSelectSnapshot: (id: string) => void;
};
const HALF_WIDTH = SCENE_WIDTH / 2;
const HALF_HEIGHT = SCENE_HEIGHT / 2;
const labelFont = "500 11px ui-monospace, monospace";
const MAX_LABELS = 12;
const METEOR_SECONDS = 1.4;
export function BlackholeGalaxy({
orbits,
flowing,
capturing,
capturePulse = 0,
onToggleFlow,
onSelectOrbit,
}: {
orbits: Orbit[];
snapshots?: unknown;
flowing: boolean;
capturing?: boolean;
capturePulse?: number;
onToggleFlow: () => void;
onSelectSnapshot?: (id: string) => void;
onSelectOrbit: (id: string) => void;
selectedSnapshotId?: string | null;
}) {
const t = useGalaxyTime(!flowing);
const shells = useMemo(() => assignShells(orbits.length), [orbits.length]);
orbits, selectedOrbitId, recentSnapshots, flowing, arrival, onSelectOrbit, onSelectSnapshot,
}: Props) {
const frame = useRef<HTMLDivElement>(null);
const bodyNodes = useRef(new Map<SVGGElement, { id: string; far: boolean }>());
const slotsBefore = useRef<ReturnType<typeof assignOrbitSlots>>(undefined);
const elapsed = useRef(0);
const meteor = useRef<{ id: string; time: number; source: Vec2 }>(undefined);
const trail = useRef<SVGPathElement>(null);
const head = useRef<SVGCircleElement>(null);
const effect = useRef<SVGGElement>(null);
const [width, setWidth] = useState(0);
const poses = shells.map((body) => shellPose(body, t));
const poseRef = useRef(poses);
poseRef.current = poses;
const meteor = useMeteor(capturePulse, poseRef);
const slots = useMemo(
() => assignOrbitSlots(orbits.map(({ id }) => id), slotsBefore.current, selectedOrbitId),
[orbits, selectedOrbitId],
);
useLayoutEffect(() => { slotsBefore.current = slots; }, [slots]);
useLayoutEffect(() => {
const element = frame.current;
if (!element) return;
const measure = () => setWidth(element.clientWidth);
const observer = new ResizeObserver(measure);
observer.observe(element);
measure();
return () => observer.disconnect();
}, []);
const draw = useCallback((delta: number) => {
const moving = flowing && slots.size > 0;
if (moving) elapsed.current += delta;
for (const [node, { id, far }] of bodyNodes.current) {
const slot = slots.get(id);
if (!slot) continue;
const { x, y } = orbitPose(slot, elapsed.current);
const visible = far === (y < 0);
const display = visible ? "" : "none";
if (node.style.display !== display) node.style.display = display;
if (!visible) continue;
node.setAttribute("transform", `translate(${x} ${y})`);
}
if (!arrival) {
effect.current?.setAttribute("opacity", "0");
return moving;
}
const slot = slots.get(arrival.orbitId);
if (meteor.current?.id !== arrival.snapshotId && slot) {
const source = orbitPose(slot, elapsed.current);
meteor.current = { id: arrival.snapshotId, time: 0, source };
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 = meteor.current;
if (!current || current.id !== arrival.snapshotId) return moving;
current.time += delta;
const progress = Math.min(1, current.time / METEOR_SECONDS);
const { x, y } = spiralPoint(current.source, progress);
head.current?.setAttribute("cx", String(x));
head.current?.setAttribute("cy", String(y));
trail.current?.setAttribute("stroke-dashoffset", String(0.2 - progress));
effect.current?.setAttribute("opacity", String(progress >= 1 ? 0 : Math.min(1, (1 - progress) * 6)));
return moving || progress < 1;
}, [arrival, flowing, slots]);
useGalaxyMotion((flowing && slots.size > 0) || !!arrival, draw);
const scale = width / SCENE_WIDTH;
const height = SCENE_HEIGHT * scale;
const hitRadius = Math.max(12, scale ? 12 / scale : 12);
const selectedSlot = selectedOrbitId ? slots.get(selectedOrbitId) : undefined;
const selectedPosition = !flowing && selectedSlot ? orbitPose(selectedSlot, elapsed.current) : undefined;
const positions = !flowing ? [...slots.values()].map((slot) => orbitPose(slot, elapsed.current)) : [];
const moons = selectedPosition
? moonPoses(selectedPosition, recentSnapshots.length, 2 * hitRadius + 3, positions)
: [];
const screen = ({ x, y }: Vec2) => ({ x: (x + HALF_WIDTH) * scale, y: (y + HALF_HEIGHT) * scale });
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;
const labelCandidates = [...visible].sort((a, b) => byPriority(a) - byPriority(b))
.filter((orbit) => width >= 530 || orbit.id === selectedOrbitId)
.slice(0, MAX_LABELS);
const box = (point: Vec2, r: number): Rect => {
const { x, y } = screen(point);
return { x: x - r, y: y - r, width: r * 2, height: r * 2 };
};
let labels: ReturnType<typeof placeLabels> = [];
if (!flowing && width && labelCandidates.length) {
const measure = document.createElement("canvas").getContext("2d");
if (measure) measure.font = labelFont;
const markers = positions.map((point) => box(point, 7));
const core = box({ x: 0, y: 0 }, 65 * scale);
labels = placeLabels(labelCandidates.map(({ id, name }) => {
const point = screen(orbitPose(slots.get(id)!, elapsed.current));
return { id, ...point, width: Math.min(146, Math.ceil(measure?.measureText(name).width ?? name.length * 7) + 16) };
}), width, height, [core, ...markers, ...moons.map((moon) => box(moon, 12))]);
}
const focusLabel = labels.find(({ id }) => id === selectedOrbitId);
const renderOrbits = (far: boolean) => visible.map((orbit) => {
const point = orbitPose(slots.get(orbit.id)!, elapsed.current);
// Each marker switches layers when it crosses the orbital plane.
const selected = orbit.id === selectedOrbitId;
const status = orbitStatus(orbit.last_status);
return (
<g
key={orbit.id}
ref={(node) => {
if (!node) return;
bodyNodes.current.set(node, { id: orbit.id, far });
return () => { bodyNodes.current.delete(node); };
}}
transform={`translate(${point.x} ${point.y})`}
style={{ display: far === (point.y < 0) ? "" : "none" }}
data-orbit-marker={orbit.id}
className={`orbit-marker orbit-marker--${status.tone}${selected ? " orbit-marker--selected" : ""}`}
>
<circle className="orbit-halo" r={selected ? 16 : 10} />
{status.tone === "red" && <path className="orbit-alert" d="M0 -8 8 0 0 8 -8 0Z" />}
{status.busy && <circle className="orbit-busy" r="8.5" />}
{selected && <circle className="orbit-selection" r="13" />}
<circle className="orbit-light" r="4.6" />
<circle className="orbit-hit" r={hitRadius} onClick={() => onSelectOrbit(orbit.id)} />
</g>
);
});
return (
<div className="absolute inset-0 flex items-center justify-center pt-14 pb-24 px-4 pointer-events-none">
<svg
viewBox="-300 -300 600 600"
className="h-full w-full max-h-[min(86dvh,920px)] max-w-[min(96vw,1100px)] pointer-events-auto"
role="img"
aria-label="Vault orrery"
>
<defs>
<linearGradient id="diskBand" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stopColor="#6a3414" stopOpacity="0" />
<stop offset="18%" stopColor="#c4622a" stopOpacity="0.55" />
<stop offset="42%" stopColor="#ffb15e" stopOpacity="0.95" />
<stop offset="58%" stopColor="#fff1d4" stopOpacity="1" />
<stop offset="78%" stopColor="#ff8a3a" stopOpacity="0.85" />
<stop offset="100%" stopColor="#6a3414" stopOpacity="0" />
</linearGradient>
<linearGradient id="topArc" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stopColor="#ff9a4a" stopOpacity="0" />
<stop offset="50%" stopColor="#ffd7a4" stopOpacity="0.95" />
<stop offset="100%" stopColor="#ff9a4a" stopOpacity="0" />
</linearGradient>
<radialGradient id="warmBody" cx="36%" cy="32%" r="68%">
<stop offset="0%" stopColor="#fff6ea" />
<stop offset="42%" stopColor="#ffb15a" />
<stop offset="100%" stopColor="#c4621e" />
</radialGradient>
<radialGradient id="coolBody" cx="36%" cy="32%" r="68%">
<stop offset="0%" stopColor="#ffffff" />
<stop offset="45%" stopColor="#e7eefc" />
<stop offset="100%" stopColor="#9aa6c4" />
</radialGradient>
<filter id="softGlow" x="-40%" y="-40%" width="180%" height="180%">
<feGaussianBlur stdDeviation="2.2" />
</filter>
<filter id="diskGlow" x="-20%" y="-80%" width="140%" height="260%">
<feGaussianBlur stdDeviation="1.4" />
</filter>
</defs>
<LensedHole t={t} onToggle={onToggleFlow} />
{shells.map((body, i) => {
const pose = poses[i];
const behind = pose.angle - 0.28;
const wake = {
x: Math.cos(behind) * body.radius,
y: Math.sin(behind) * body.radius,
};
const color = body.warm ? "#ffb15a" : "#d5def4";
<div ref={frame} className="galaxy-frame" data-flowing={flowing}>
<svg viewBox={`${-HALF_WIDTH} ${-HALF_HEIGHT} ${SCENE_WIDTH} ${SCENE_HEIGHT}`} aria-hidden="true">
<g className="orbit-tracks" pointerEvents="none">
{orbitRadii.map((radius) => (
<ellipse key={radius} rx={radius} ry={radius * ORBIT_TILT} className={selectedSlot?.radius === radius ? "is-selected" : ""} />
))}
</g>
<g className="orbit-layer orbit-layer--far">{renderOrbits(true)}</g>
<VaultCore />
<g className="orbit-layer orbit-layer--near">{renderOrbits(false)}</g>
{selectedPosition && moons.map(({ x, y }, index) => {
const snapshot = recentSnapshots[index];
return (
<g key={orbits[i].id}>
<line
x1={wake.x}
y1={wake.y}
x2={pose.x}
y2={pose.y}
stroke={color}
strokeWidth={body.warm ? 2.4 : 1.5}
strokeLinecap="round"
opacity={0.45}
/>
<circle
cx={pose.x}
cy={pose.y}
r={body.size * 2.1}
fill={color}
opacity={0.16}
filter="url(#softGlow)"
/>
<circle
cx={pose.x}
cy={pose.y}
r={body.size}
fill={body.warm ? "url(#warmBody)" : "url(#coolBody)"}
className={!flowing ? "cursor-pointer" : undefined}
onClick={(e) => {
e.stopPropagation();
if (!flowing) onSelectOrbit(orbits[i].id);
}}
/>
{!flowing && (
<text
x={pose.x + Math.cos(pose.angle) * (body.size + 14)}
y={pose.y + Math.sin(pose.angle) * (body.size + 14)}
textAnchor="middle"
fill="#c9d4ea"
fontSize="10"
className="font-mono pointer-events-none"
>
{shorten(orbits[i].name)}
</text>
)}
<g key={snapshot.id} data-snapshot-marker={snapshot.id} className="snapshot-marker">
<line x1={selectedPosition.x} y1={selectedPosition.y} x2={x} y2={y} />
<rect className="snapshot-light" x={x - 4} y={y - 4} width="8" height="8" rx="1" transform={`rotate(45 ${x} ${y})`} />
<circle className="orbit-hit" cx={x} cy={y} r={hitRadius} onClick={() => onSelectSnapshot(snapshot.id)} />
</g>
);
})}
{meteor && <InboundMeteor source={meteor.source} u={meteor.u} />}
{selectedPosition && focusLabel && (
<line className="focus-leader"
x1={selectedPosition.x} y1={selectedPosition.y}
x2={(focusLabel.x + focusLabel.width / 2) / scale - HALF_WIDTH}
y2={(focusLabel.y + LABEL_HEIGHT / 2) / scale - HALF_HEIGHT}
/>
)}
<g ref={effect} className="capture-arrival" opacity="0" pointerEvents="none">
<path ref={trail} pathLength="1" strokeDasharray=".2 1" fill="none" />
<circle ref={head} r="3.5" />
</g>
</svg>
<div aria-hidden="true" className="scene-labels" style={{ font: labelFont }}>
{labels.map(({ id, x, y, width: labelWidth }) => (
<span key={id} style={{ left: x, top: y, width: labelWidth }} className={id === selectedOrbitId ? "is-selected" : ""}>
{labelCandidates.find((orbit) => orbit.id === id)?.name}
</span>
))}
</div>
{orbits.length >= orbitCapacity && <p className="scene-density">Select an orbit in the list to inspect it</p>}
</div>
);
}
function LensedHole({ t, onToggle }: { t: number; onToggle: () => void }) {
const shimmer = 0.82 + 0.18 * Math.sin(t * 0.8);
return (
<g>
<ellipse
cx="0"
cy="0"
rx="168"
ry="22"
fill="none"
stroke="url(#diskBand)"
strokeWidth="16"
opacity={0.55 * shimmer}
filter="url(#diskGlow)"
/>
<ellipse
cx="18"
cy="0"
rx="150"
ry="11"
fill="none"
stroke="url(#diskBand)"
strokeWidth="5"
opacity="0.95"
/>
<path
d="M -120,10 Q 10,28 168,6"
fill="none"
stroke="url(#diskBand)"
strokeWidth="4.5"
strokeLinecap="round"
opacity="0.8"
/>
<circle cx="0" cy="0" r="38" fill="#000" />
<circle
cx="0"
cy="0"
r="41"
fill="none"
stroke="#fff4e4"
strokeWidth="1.7"
opacity="0.95"
/>
<circle
cx="0"
cy="0"
r="45"
fill="none"
stroke="#ffb15a"
strokeWidth="3.2"
opacity="0.55"
/>
<path
d="M -108,-6 C -46,-102 46,-102 108,-6"
fill="none"
stroke="url(#topArc)"
strokeWidth="10"
strokeLinecap="round"
opacity={0.95 * shimmer}
filter="url(#diskGlow)"
/>
<circle
cx="0"
cy="0"
r="48"
fill="transparent"
className="cursor-pointer"
onClick={onToggle}
/>
</g>
);
}
function InboundMeteor({ source, u }: { source: Vec2; u: number }) {
const head = spiralPoint(source, u);
const samples = Array.from({ length: 14 }, (_, i) => {
const k = u - (i / 13) * 0.42;
return spiralPoint(source, Math.max(0, k));
});
const fade = u > 0.88 ? 1 - (u - 0.88) / 0.12 : 1;
const trail = [...samples].reverse();
const d = trail
.map((p, i) => `${i === 0 ? "M" : "L"} ${p.x.toFixed(1)} ${p.y.toFixed(1)}`)
.join(" ");
return (
<g opacity={Math.max(0, fade)} pointerEvents="none">
<path
d={d}
fill="none"
stroke="#ffb15a"
strokeWidth="5"
strokeLinecap="round"
opacity="0.4"
filter="url(#softGlow)"
/>
<path
d={d}
fill="none"
stroke="#ffe6c4"
strokeWidth="1.7"
strokeLinecap="round"
/>
<circle cx={head.x} cy={head.y} r="4.2" fill="#fffaf3" />
</g>
);
}
function useMeteor(
pulse: number,
poseRef: RefObject<{ x: number; y: number }[]>,
) {
const [run, setRun] = useState<{ started: number; source: Vec2 } | null>(null);
const [now, setNow] = useState(0);
useEffect(() => {
if (!pulse) return;
const live = poseRef.current?.[0];
if (!live) return;
setNow(0);
setRun({ started: performance.now(), source: { x: live.x, y: live.y } });
}, [pulse, poseRef]);
useEffect(() => {
if (!run) return;
let raf = 0;
const tick = () => {
const u = (performance.now() - run.started) / METEOR_MS;
setNow(u);
if (u < 1) raf = requestAnimationFrame(tick);
else setRun(null);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [run]);
if (!run || now >= 1) return null;
return { source: run.source, u: now };
}