import { useId, useLayoutEffect, useMemo, useRef, useState } from "react"; import { animate, motion, useMotionValue, useTransform, type MotionStyle, type MotionValue } from "motion/react"; import type { PointerEvent as ReactPointerEvent } from "react"; import type { Orbit, Snapshot } from "../../api"; import { orbitStatus } from "../../lib/format"; import { LABEL_HEIGHT, placeLabels, type Rect } from "../../lib/galaxyLabelLayout"; import { assignOrbitSlots, DEFAULT_VIEW, LIFT_MAX, LIFT_MIN, moonPoses, orbitCapacity, orbitPose, orbitRadii, SCENE_HEIGHT, SCENE_WIDTH, tiltOf, trailAngle, type Vec2, type View, } from "../../lib/galaxyLayout"; import { useGalaxyMotion } from "../../hooks/useGalaxyMotion"; import { useScreenTransition } from "../../hooks/useScreenTransition"; import { gentleSpring, uiSpring } from "../../lib/motion"; import { VaultCore } from "./VaultCore"; import type { CoreSignal } from "../../lib/blackhole/controller"; import { SCENE_UNITS_PER_M, SHADOW_SCENE_RADIUS } 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 }; type Props = { orbits: Orbit[]; selectedOrbitId?: string; recentSnapshots: Snapshot[]; flowing: boolean; reducedMotion: boolean; bigScreen: boolean; captureEffect?: CaptureEffect; captureGlow: MotionValue; 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; 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 MAX_BIG_LABELS = 60; /** On the big screen the picked orbit's label stands off its star, on the end of an elbowed leader line. */ const BIG_LABEL_GAP = 64; /** Radians of yaw and of lift per pixel dragged, and how far a press may wander and still be a click. */ const YAW_PER_PX = 0.006; const LIFT_PER_PX = 0.003; const CLICK_SLOP = 5; /** A click this close to the hole, in scene units from its centre, sends the camera back to the default view. */ const HOLE_CLICK_RADIUS = 72; const clamp = (value: number) => Math.max(0, Math.min(1, value)); const ACCRETION_SECONDS = 6.4; /** 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, resolveFailure, onSelectOrbit, onSelectSnapshot, }: Props) { const frame = useRef(null); const bodyNodes = useRef(new Map()); const bodyState = useRef(new WeakMap()); const ambient = useRef(0); const ringNodes = useRef(new Map()); const slotsBefore = useRef>(undefined); const elapsed = useRef(0); const entrance = useRef(0); const core = useRef(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>(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(shownStatus(orbit)).busy); const knockoutId = useId(); const starId = useId(); const [width, setWidth] = useState(0); const [coasting, setCoasting] = useState(false); const rate = useMotionValue(flowing && !reducedMotion ? 1 : 0); const moving = !reducedMotion && (flowing || coasting); const [lockedPhase, setLockedPhase] = useState(0); const reveal = useMotionValue(flowing ? 0 : 1); const revealStyle = useTransform(reveal, clamp); const revealVariables: MotionStyle & { "--lock-reveal": MotionValue } = { "--lock-reveal": revealStyle }; const selectionX = useMotionValue(0); const selectionY = useMotionValue(0); const selectionPlaced = useRef(false); // The camera. The two values are what the loop paints from; `view` is what the labels and moons are laid out from, and // only catches up once the camera comes to rest, so a drag never triggers a layout. const viewYaw = useMotionValue(0); const viewLift = useMotionValue(0); const [view, setView] = useState(DEFAULT_VIEW); const [turning, setTurning] = useState(false); const painted = useRef(DEFAULT_VIEW); const turn = useRef<{ x: number; y: number; yaw: number; lift: number; moved: boolean } | undefined>(undefined); useLayoutEffect(() => () => { rate.stop(); reveal.stop(); selectionX.stop(); selectionY.stop(); viewYaw.stop(); viewLift.stop(); }, [rate, reveal, selectionX, selectionY, viewYaw, viewLift]); useLayoutEffect(() => { if (reducedMotion) { rate.jump(0); reveal.jump(1); setLockedPhase(elapsed.current); setCoasting(false); return; } if (flowing) animate(reveal, 0, gentleSpring); const target = flowing ? 1 : 0; if (rate.get() === target && !rate.isAnimating()) return; setCoasting(!flowing); animate(rate, target, { ...uiSpring, restDelta: 0.025, restSpeed: 0.25, onComplete: () => { if (!flowing) { setLockedPhase(elapsed.current); animate(reveal, 1, gentleSpring); } setCoasting(false); }, }); }, [flowing, rate, reducedMotion, reveal]); const slots = useMemo( () => assignOrbitSlots(orbits.map(({ id }) => id), slotsBefore.current, selectedOrbitId), [orbits, selectedOrbitId], ); useLayoutEffect(() => { slotsBefore.current = slots; }, [slots]); useScreenTransition(frame, bigScreen, reducedMotion, setWidth); const selectedSlot = selectedOrbitId ? slots.get(selectedOrbitId) : undefined; const selectedPosition = selectedSlot && orbitPose(selectedSlot, lockedPhase, view); const selectedX = selectedPosition?.x; const selectedY = selectedPosition?.y; useLayoutEffect(() => { if (selectedX === undefined || selectedY === undefined) { selectionPlaced.current = false; } else if (!selectionPlaced.current || reducedMotion) { selectionX.jump(selectedX); selectionY.jump(selectedY); selectionPlaced.current = true; } else if (!moving) { animate(selectionX, selectedX, uiSpring); animate(selectionY, selectedY, uiSpring); } }, [moving, reducedMotion, selectedX, selectedY, selectionX, selectionY]); // 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((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) { busyAngle.current = (busyAngle.current + 105 * delta) % 360; frame.current?.style.setProperty("--busy-angle", `${busyAngle.current}deg`); } const wasEntering = entrance.current < 0.6; if (slots.size) entrance.current = reducedMotion ? 0.6 : Math.min(0.6, entrance.current + delta); const entering = !reducedMotion && slots.size > 0 && entrance.current < 0.6; const live: View = { yaw: viewYaw.get(), lift: viewLift.get() }; const viewChanged = live.yaw !== painted.current.yaw || live.lift !== painted.current.lift; if (viewChanged) { // The orbit plane tips as the camera rises and falls; the circles turn into ellipses and back. const tilt = tiltOf(live); for (const [radius, ring] of ringNodes.current) ring.setAttribute("ry", String(radius * tilt)); painted.current = live; } if (!delta || moving || viewChanged || (!reducedMotion && wasEntering)) { for (const [node, { id, index }] of bodyNodes.current) { const slot = slots.get(id)!; const { x, y } = orbitPose(slot, elapsed.current, live); const depth = y / (slot.radius * tiltOf(live)); const appear = entering ? clamp((entrance.current - Math.min(index * 0.013, 0.33)) / 0.23) : 1; node.setAttribute("transform", `translate(${x} ${y}) scale(${0.95 + depth * 0.08})`); // A star on the far side of the hole, seen through its shadow, is hidden by it. This only happens once the // camera has come down far enough for the far side to reach the shadow. const hidden = depth < 0 ? clamp((Math.hypot(x, y) - SHADOW_SCENE_RADIUS * 0.95) / (SHADOW_SCENE_RADIUS * 0.4)) : 1; node.setAttribute("opacity", String(appear * (0.88 + depth * 0.12) * hidden)); const body = bodyNodes.current.get(node)!; body.x = x; body.y = y; // A short comet tail behind each moving marker. It points back along the orbit, lengthens with speed and // fades out as the map stops. body.trail ??= node.querySelector(".marker-trail"); if (body.trail) { body.trail.setAttribute("transform", `rotate(${(trailAngle(slot, elapsed.current, live) * 180) / Math.PI}) scale(${0.55 + 0.45 * Math.min(1, speed)} 1)`); body.trail.setAttribute("opacity", String(Math.min(1, speed * 1.6) * (1 - body.look))); } } } // Stars shimmer. It rides the loop that is already running, so a map that has stopped is perfectly still, and it // is off under reduced motion. Working and failed stars shimmer more, so activity reads at a glance. if (delta > 0) ambient.current += delta; if (!reducedMotion && delta > 0) { const time = ambient.current; for (const [node, body] of bodyNodes.current) { body.life ??= node.querySelector(".star-life"); if (!body.life) continue; const rate = 0.7 + (0.8 * ((body.index * 7) % 5)) / 4; 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; 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))); } } if ((moving || viewChanged) && selectedSlot) { const point = orbitPose(selectedSlot, elapsed.current, live); selectionX.jump(point.x); selectionY.jump(point.y); } // 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; 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, view: live }); 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)) { diskTime.current += delta * (speed + 3.2 * absorption); const phase = (diskTime.current % ACCRETION_SECONDS) / ACCRETION_SECONDS; core.current?.style.setProperty("--accretion-offset", String(-100 * phase)); } if (signal.time !== diskTime.current || signal.absorption !== absorption || signal.yaw !== live.yaw || signal.lift !== live.lift) { signal.time = diskTime.current; signal.absorption = absorption; signal.yaw = live.yaw; signal.lift = live.lift; signal.wake?.(); } const coreStyle = core.current?.style; if (coreStyle && (absorption || coreStyle.getPropertyValue("--capture-absorption") !== "0")) { coreStyle.setProperty("--capture-absorption", String(absorption)); } 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 // stars give way to instrument dots, and quiet tracks to full rings, as the front passes. const paintLook = () => { const at = signal.lookAt; for (const [node, body] of bodyNodes.current) { body.look = at ? at(Math.hypot(body.x, body.y) / SCENE_UNITS_PER_M) : 0; node.querySelector(".marker-star")?.setAttribute("opacity", String(1 - body.look)); node.querySelector(".marker-dot")?.setAttribute("opacity", String(body.look)); // The dark backing keeps radar dots readable; a glowing star does not need it. node.querySelector(".orbit-knockout")?.setAttribute("opacity", String(0.08 + 0.92 * body.look)); if (body.look > 0.99) node.querySelector(".marker-trail")?.setAttribute("opacity", "0"); } for (const [radius, ring] of ringNodes.current) { const look = at ? at(radius / SCENE_UNITS_PER_M) : 0; ring.style.setProperty("--track", String(0.12 + 0.24 * look)); } }; useLayoutEffect(() => { signal.onLook = paintLook; return () => { signal.onLook = undefined; }; }); useLayoutEffect(paintLook); const scale = width / SCENE_WIDTH; const height = SCENE_HEIGHT * scale; const hitRadius = Math.max(12, scale ? 12 / scale : 12); const positions = [...slots.values()].map((slot) => orbitPose(slot, lockedPhase, view)); 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 : 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) // The big screen has room for every orbit; placement still drops a label that would land on another. .slice(0, bigScreen ? MAX_BIG_LABELS : 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 = []; if (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)!, lockedPhase, view)); 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))], selectedOrbitId, bigScreen ? BIG_LABEL_GAP : 0); } const focusLabel = labels.find(({ id }) => id === selectedOrbitId); const revealRing = (radius: number | undefined, on: boolean) => { if (radius !== undefined) ringNodes.current.get(radius)?.classList.toggle("is-hover", on); }; const renderOrbits = visible.map((orbit, index) => { const selected = orbit.id === selectedOrbitId; const status = orbitStatus(shownStatus(orbit)); const radius = slots.get(orbit.id)?.radius; return ( { if (!node) return; // 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} animate="idle" whileHover="hover" data-orbit-marker={orbit.id} className={`orbit-marker orbit-marker--${status.tone}${selected ? " orbit-marker--selected" : ""}`} > {status.tone === "red" && } {status.busy && } {/* Realistic look: a star. Four diffraction spikes set it apart from the sky's own stars, which have none. */} {/* Radar look: the plain instrument dot. */} onSelectOrbit(orbit.id)} onPointerEnter={() => revealRing(radius, true)} onPointerLeave={() => revealRing(radius, false)} /> ); }); // Wake the loop whenever the camera moves, so a locked map draws while it turns and goes back to sleep after. useLayoutEffect(() => { const stops = [viewYaw.on("change", wake), viewLift.on("change", wake)]; return () => stops.forEach((stop) => stop()); }, [viewYaw, viewLift, wake]); const settle = () => { setView({ yaw: viewYaw.get(), lift: viewLift.get() }); setTurning(false); }; /** Back to the default view by the short way round, with the shared spring. */ const resetView = () => { const full = 2 * Math.PI; const yawTarget = Math.round(viewYaw.get() / full) * full; if (reducedMotion) { viewYaw.jump(0); viewLift.jump(0); settle(); return; } setTurning(true); animate(viewLift, 0, gentleSpring); animate(viewYaw, yawTarget, { ...gentleSpring, onComplete: () => { viewYaw.jump(0); settle(); }, }); }; const startTurn = (event: ReactPointerEvent) => { if (!event.isPrimary || event.button !== 0 || (event.target as Element).closest("[data-orbit-marker], .orbit-hit, [data-snapshot-marker]")) return; turn.current = { x: event.clientX, y: event.clientY, yaw: viewYaw.get(), lift: viewLift.get(), moved: false }; }; const moveTurn = (event: ReactPointerEvent) => { const drag = turn.current; if (!drag) return; const dx = event.clientX - drag.x; const dy = event.clientY - drag.y; if (!drag.moved) { if (Math.hypot(dx, dy) < CLICK_SLOP) return; drag.moved = true; viewYaw.stop(); viewLift.stop(); event.currentTarget.setPointerCapture(event.pointerId); setTurning(true); } // Dragging right brings the near side of the orbits to the right; dragging down raises the camera. viewYaw.set(drag.yaw - dx * YAW_PER_PX); viewLift.set(Math.min(LIFT_MAX, Math.max(LIFT_MIN, drag.lift + dy * LIFT_PER_PX))); }; const endTurn = (event: ReactPointerEvent) => { const drag = turn.current; turn.current = undefined; if (!drag) return; if (drag.moved) { if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId); settle(); return; } // A click on the black hole itself puts the camera back. const box = event.currentTarget.getBoundingClientRect(); const radius = (HOLE_CLICK_RADIUS * box.width) / SCENE_WIDTH; if (event.type === "pointerup" && Math.hypot(event.clientX - (box.left + box.width / 2), event.clientY - (box.top + box.height / 2)) <= radius && (viewYaw.get() !== 0 || viewLift.get() !== 0)) { resetView(); } }; return ( {orbits.length >= orbitCapacity &&

Select an orbit in the list to inspect it

}
); }