MBO-Tech-IT-Webseite/components/NetField.tsx

341 lines
11 KiB
TypeScript

"use client";
import { useEffect, useRef, useState } from "react";
import { Pause, Play } from "lucide-react";
/*
* Das Netz im Hero: Punkte unterschiedlicher Größe, verbunden wie ein Netzwerk.
* Die großen Knoten sitzen an den Begriffen (.hero__net li), kleine Datenpakete
* wandern über die Leitungen. Links bleibt es ruhig, dort steht der Text.
* 30 fps, pausiert außerhalb des Sichtfelds und per Taste; bei reduzierter Bewegung ein Standbild.
*/
type Node = { bx: number; by: number; r: number; ph: number; amp: number; sp: number; hub: boolean; warm: boolean };
type Packet = { a: number; b: number; p: number; v: number; warm: boolean };
function rng(seed: number) {
let s = seed >>> 0;
return () => {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
export default function NetField() {
const wrapRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const heldRef = useRef(false);
const syncRef = useRef<() => void>(() => {});
const [live, setLive] = useState(false);
const [held, setHeld] = useState(false);
const [canPause, setCanPause] = useState(false);
useEffect(() => {
const wrap = wrapRef.current;
const canvas = canvasRef.current;
const hero = wrap?.parentElement;
if (!wrap || !canvas || !hero) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const reduced = window.matchMedia("(prefers-reduced-motion: reduce)");
const wide = window.matchMedia("(min-width: 60.01rem)");
const fine = window.matchMedia("(pointer: fine)");
let W = 0;
let H = 0;
let nodes: Node[] = [];
let edges: [number, number][] = [];
let adj: number[][] = [];
let packets: Packet[] = [];
let blue = "";
let orange = "";
let dark = false;
let pointer: { x: number; y: number } | null = null;
let visible = true;
let raf = 0;
let last = 0;
let lastT = 0;
let t0 = performance.now();
let tPaused = 0;
const readColors = () => {
const cs = getComputedStyle(document.documentElement);
blue = cs.getPropertyValue("--color-accent").trim() || blue;
orange = cs.getPropertyValue("--color-signal").trim() || orange;
dark = document.documentElement.classList.contains("dark");
};
const build = () => {
const r = hero.getBoundingClientRect();
W = r.width;
H = r.height;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
canvas.width = Math.round(W * dpr);
canvas.height = Math.round(H * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const rand = rng(20261104);
nodes = [];
const blocked: DOMRect[] = [];
if (wide.matches) {
hero.querySelectorAll<HTMLElement>(".hero__net li").forEach((li, i) => {
const b = li.getBoundingClientRect();
blocked.push(new DOMRect(b.left - r.left - 12, b.top - r.top - 10, b.width + 24, b.height + 20));
nodes.push({
bx: b.left - r.left - 14,
by: b.top - r.top + b.height / 2,
r: 6,
ph: rand() * 6.28,
amp: 2,
sp: 0.3,
hub: true,
warm: i % 2 === 0,
});
});
}
const count = wide.matches ? 150 : 55;
const x0 = wide.matches ? 0.47 : 0.25;
const y1 = wide.matches ? 0.97 : 0.42;
let guard = 0;
while (nodes.length < count + (wide.matches ? 8 : 0) && guard++ < 4000) {
const x = W * (x0 + rand() * (0.995 - x0));
const y = H * (0.05 + rand() * (y1 - 0.05));
// links dünner besetzt, damit der Übergang zum Text weich bleibt
const lean = (x / W - x0) / (1 - x0);
if (rand() > 0.35 + lean * 0.8) continue;
if (blocked.some((b) => x > b.left && x < b.right && y > b.top && y < b.bottom)) continue;
const s = rand();
nodes.push({
bx: x,
by: y,
r: 1 + s * s * 3.2,
ph: rand() * 6.28,
amp: 2 + rand() * 5,
sp: 0.2 + rand() * 0.4,
hub: false,
warm: rand() < 0.12,
});
}
// Verbindungen: jeder Punkt zu seinen nächsten Nachbarn
const seen = new Set<string>();
edges = [];
adj = nodes.map(() => []);
const link = (a: number, b: number) => {
const k = a < b ? `${a}-${b}` : `${b}-${a}`;
if (seen.has(k)) return;
seen.add(k);
edges.push([a, b]);
adj[a].push(b);
adj[b].push(a);
};
nodes.forEach((n, i) => {
const near = nodes
.map((m, j) => ({ j, d: Math.hypot(m.bx - n.bx, m.by - n.by) }))
.filter((o) => o.j !== i)
.sort((p, q) => p.d - q.d);
const k = n.hub ? 5 : 3;
near.slice(0, k).forEach((o) => {
if (o.d < (n.hub ? 240 : 140)) link(i, o.j);
});
});
packets = [];
const pc = wide.matches ? 22 : 8;
for (let i = 0; i < pc && edges.length; i++) {
const [a, b] = edges[Math.floor(rand() * edges.length)];
packets.push({ a, b, p: rand(), v: 70 + rand() * 70, warm: i % 3 === 0 });
}
};
const pos = (n: Node, t: number) => [n.bx + Math.sin(t * n.sp + n.ph) * n.amp, n.by + Math.cos(t * n.sp * 0.8 + n.ph) * n.amp];
const draw = (t: number, dt: number) => {
ctx.clearRect(0, 0, W, H);
const P = nodes.map((n) => pos(n, t));
// Leitungen
ctx.lineWidth = 1;
ctx.strokeStyle = blue;
for (const [a, b] of edges) {
const hubEdge = nodes[a].hub || nodes[b].hub;
ctx.globalAlpha = (hubEdge ? 0.34 : 0.18) * (dark ? 1.25 : 1);
ctx.beginPath();
ctx.moveTo(P[a][0], P[a][1]);
ctx.lineTo(P[b][0], P[b][1]);
ctx.stroke();
}
// Zeiger: kurze Verbindungen zu nahen Punkten
if (pointer) {
for (let i = 0; i < nodes.length; i++) {
const d = Math.hypot(P[i][0] - pointer.x, P[i][1] - pointer.y);
if (d > 130) continue;
ctx.globalAlpha = (1 - d / 130) * 0.5;
ctx.strokeStyle = orange;
ctx.beginPath();
ctx.moveTo(pointer.x, pointer.y);
ctx.lineTo(P[i][0], P[i][1]);
ctx.stroke();
}
ctx.strokeStyle = blue;
}
// Punkte
for (let i = 0; i < nodes.length; i++) {
const n = nodes[i];
const near = pointer ? Math.max(0, 1 - Math.hypot(P[i][0] - pointer.x, P[i][1] - pointer.y) / 130) : 0;
const r = n.r * (1 + near * 0.6);
if (n.hub) {
ctx.globalAlpha = 0.25 + 0.15 * Math.sin(t * 1.4 + n.ph);
ctx.strokeStyle = n.warm ? orange : blue;
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(P[i][0], P[i][1], r + 6, 0, Math.PI * 2);
ctx.stroke();
ctx.lineWidth = 1;
ctx.globalAlpha = 1;
ctx.fillStyle = n.warm ? orange : blue;
} else {
ctx.globalAlpha = Math.min(1, 0.35 + n.r * 0.16 + near * 0.4);
ctx.fillStyle = n.warm ? orange : blue;
}
ctx.beginPath();
ctx.arc(P[i][0], P[i][1], r, 0, Math.PI * 2);
ctx.fill();
}
// Datenpakete
ctx.globalAlpha = 1;
for (const k of packets) {
const ax = P[k.a][0];
const ay = P[k.a][1];
const bx = P[k.b][0];
const by = P[k.b][1];
const len = Math.max(1, Math.hypot(bx - ax, by - ay));
k.p += (k.v * dt) / len;
if (k.p >= 1) {
const next = adj[k.b].filter((j) => j !== k.a);
const pick = next.length ? next[Math.floor(Math.random() * next.length)] : k.a;
k.a = k.b;
k.b = pick;
k.p = 0;
}
const x = ax + (bx - ax) * Math.min(1, k.p);
const y = ay + (by - ay) * Math.min(1, k.p);
ctx.fillStyle = k.warm ? orange : blue;
ctx.beginPath();
ctx.arc(x, y, 2.4, 0, Math.PI * 2);
ctx.fill();
}
ctx.globalAlpha = 1;
};
const still = () => draw(reduced.matches ? 3 : tPaused, 0);
const running = () => visible && !heldRef.current && !reduced.matches;
const loop = (now: number) => {
raf = 0;
if (!running()) return;
if (now - last >= 33) {
const t = (now - t0) / 1000;
draw(t, Math.min(0.1, t - lastT));
lastT = t;
last = now;
}
raf = requestAnimationFrame(loop);
};
const sync = () => {
if (running()) {
if (!raf) {
t0 = performance.now() - tPaused * 1000;
lastT = tPaused;
raf = requestAnimationFrame(loop);
}
} else {
if (raf) cancelAnimationFrame(raf);
raf = 0;
tPaused = lastT;
still();
}
};
syncRef.current = sync;
readColors();
build();
still();
setLive(true);
setCanPause(!reduced.matches);
sync();
const ro = new ResizeObserver(() => {
build();
if (!running()) still();
});
ro.observe(hero);
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
sync();
});
io.observe(hero);
const mo = new MutationObserver(() => {
readColors();
if (!running()) still();
});
mo.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
const onMove = (e: PointerEvent) => {
if (!fine.matches) return;
const r = hero.getBoundingClientRect();
pointer = { x: e.clientX - r.left, y: e.clientY - r.top };
};
const onLeave = () => {
pointer = null;
};
hero.addEventListener("pointermove", onMove);
hero.addEventListener("pointerleave", onLeave);
const onMotion = () => {
setCanPause(!reduced.matches);
sync();
};
reduced.addEventListener("change", onMotion);
return () => {
if (raf) cancelAnimationFrame(raf);
ro.disconnect();
io.disconnect();
mo.disconnect();
hero.removeEventListener("pointermove", onMove);
hero.removeEventListener("pointerleave", onLeave);
reduced.removeEventListener("change", onMotion);
};
}, []);
const toggle = () => {
heldRef.current = !heldRef.current;
setHeld(heldRef.current);
syncRef.current();
};
return (
<>
<div ref={wrapRef} className={`hero__field${live ? " is-live" : ""}`} aria-hidden="true">
<canvas ref={canvasRef} />
</div>
{canPause && (
<button type="button" className="hero__pause" onClick={toggle} aria-pressed={held}>
{held ? <Play className="icon--s" aria-hidden="true" /> : <Pause className="icon--s" aria-hidden="true" />}
{held ? "Animation fortsetzen" : "Animation anhalten"}
</button>
)}
</>
);
}